Example #1
0
        public void Should_query_by_literal_guid()
        {
            var g = new Guid("CFF4EF1C-A0DB-4F0C-B1DE-FCFEC7028CFF");

            using var repo = new LiteRepository(dbFile).WithUtcDate();
            repo.Insert(new Entity {
                Id = g, Data = "123"
            });
            var e = repo.Query <Entity>().Where($"_id = GUID('{g}')").First();

            e.Data.Should().Be("123");
        }
Example #2
0
        public void Should_query_bson_document()
        {
            var g = new Guid("CFF4EF1C-A0DB-4F0C-B1DE-FCFEC7028CFF");

            using var repo = new LiteRepository(dbFile).WithUtcDate();
            repo.Insert(new Entity {
                Id = g, Data = "123"
            });
            var doc = repo.Query <BsonDocument>("Entity").Where($"_id = GUID('{g}')").First();

            doc["Data"].AsString.Should().Be("123");
        }
Example #3
0
        public Veiculo ObterPorPlaca(string numeroPlaca)
        {
            using (var db = new LiteRepository(_db.Context))
            {
                var dbModel = db.Query <VeiculoDbModel>()
                              .Include(x => x.ModeloVeiculo)
                              .Where(p => p.NumeroPlaca == numeroPlaca)
                              .FirstOrDefault();

                return(_mapper.Map <Veiculo>(dbModel));
            }
        }
Example #4
0
        public static IServiceCollection AddCoreComponentsForWebApi(this IServiceCollection services, IConfigurationRoot configuration)
        {
            services
            .AddLogging()
            .AddSingleton <ITimeProvider, TimeProvider>()
            .AddSingleton <IFluentInterfaceFactory, FluentInterfaceFactory>()
            .AddSingleton <IFileWrapper, FileWrapper>()
            .AddSingleton <IPathWrapper, PathWrapper>()
            .AddSingleton <IDirectoryWrapper, DirectoryWrapper>()
            .AddSingleton <IFlubuEnvironmentService, FlubuEnvironmentService>()
            .AddSingleton <ITaskFactory, DotnetTaskFactory>()
            .AddSingleton <FlubuCore.Infrastructure.IHttpClientFactory, FlubuCore.Infrastructure.HttpClientFactory>()
            .AddSingleton <IScriptProperties, ScriptProperties>()
            .AddSingleton <ITargetCreator, TargetCreator>()
            .AddSingleton <IBuildServer, BuildServer>()
            .AddScoped <IBuildPropertiesSession, BuildPropertiesSession>()
            .AddScoped <TargetTree>()
            .AddScoped <IFlubuSession, FlubuSession>()
            .AddScoped <ICommandFactory, CommandFactory>()
            .AddSingleton <IScriptServiceProvider, ScriptServiceProvider>()
            .AddScoped <CommandArguments, CommandArguments>()
            .AddSingleton <IFlubuTemplateTaskFactory, FlubuTemplateTaskFactory>()
            .AddSingleton <IFlubuTemplateTasksExecutor, FlubuTemplateTasksExecutor>();

            var connectionStrings      = configuration.GetSection("FlubuConnectionStrings");
            var liteDbConnectionString = connectionStrings["LiteDbConnectionString"];

            var db = new LiteRepository(liteDbConnectionString);
            ILiteRepositoryFactory liteRepositoryFactory = new LiteRepositoryFactory();

            services.AddSingleton(liteRepositoryFactory);
            services.AddSingleton <IRepositoryFactory>(new RepositoryFactory(liteRepositoryFactory, new TimeProvider()));
            services.AddSingleton(db);
            services.AddScoped <ApiExceptionFilter>();
            services.AddScoped <ValidateRequestModelAttribute>();
            services.AddScoped <EmailNotificationFilter>();
            services.AddScoped <RestrictApiAccessFilter>();
            services.AddTransient <IHashService, HashService>();
            services.AddTransient <IUserRepository, UserRepository>();
            services.AddTransient <ISecurityRepository, SecurityRepository>();
            services.AddTransient <INotificationService, NotificationService>();
            services.AddTransient <INugetPackageResolver, NugetPackageResolver>();
            services.AddTransient <ITargetExtractor, TargetExtractor>();

            IGitHubClient gitHubClient = new GitHubClient(new Octokit.ProductHeaderValue("FlubuCore"));

            services.AddSingleton(gitHubClient);

            IWebApiClient flubuWebApiClient = new WebApiClient(new HttpClient());

            services.AddSingleton(flubuWebApiClient);
            return(services);
        }
Example #5
0
        public Loginform()
        {
            eventMediator = new EventMediator();
            // feliratkozás az ErrorMessage Event-re
            // hibaüzenet esetén az OnErrorMessage metódus megjeleníti a hibaüzenetet
            eventMediator.ErrorMessage += OnErrorMessage;

            FactorySupport factorySupport = new FactorySupport();

            Directory.CreateDirectory(@"C:\Log");
            Log.Logger = new LoggerConfiguration().WriteTo.File(@"C:\Log\Log.txt", rollingInterval: RollingInterval.Hour).CreateLogger();
            Directory.CreateDirectory(@"C:\db");
            LiteRepository repo = new LiteRepository(ApplicationConfig.DbConnectionString);

            frameWork = factorySupport.Create(isMySQL, repo, eventMediator);

            // példa: lekéri a GetService() -vel a UIFactory szervízt
            // utána kirajzol egy button-t a felhasználói felületen.

            uiFactory = (IUIFactory)(frameWork.GetService(typeof(IUIFactory)));

            if (uiFactory == null)
            {
                throw new Exception("Hibás UIFactory!");
            }

            // Betölti az egész adatbázist a memóriába
            //MessageBox.Show("Beolvasom az adatbázist a memóriába");
            frameWork.LoadDatabase();


            // példa: lekéri a GetService() -vel az IErrorservice szervízt
            // utána megjeleníti a hibaüzenetet

            IErrorService errorService = (IErrorService)(frameWork.GetService(typeof(IErrorService)));

            if (errorService == null)
            {
                throw new Exception("Hibás ErrorService!");
            }

            /*IError error = new Error(ErrorType.InputError, "Példa a beviteli hibára");
             * errorService.Write(error);
             *
             * // hibeüzenet 2. példa
             * IError errorExample2 = new Error(ErrorType.DatabaseError, "Példa: Adatbázis üzenet a datalayertől");
             * errorService.Write(errorExample2);*/

            userService = (IUserService)(frameWork.GetService(typeof(IUserService)));

            InitializeComponent();
        }
 public void Apply(LiteRepository repository)
 {
     // DropCollection will open a transaction so commit the current one
     repository.Database.Commit();
     if (repository.Database.CollectionExists("PluginEntity"))
     {
         repository.Database.DropCollection("PluginEntity");
     }
     if (repository.Database.CollectionExists("PluginSettingEntity"))
     {
         repository.Database.DropCollection("PluginSettingEntity");
     }
 }
Example #7
0
        public ILiteRepository GetRepository()
        {
            if (_tempStream is null)
            {
                _tempStream = new TempStream("abremir.AllMyBricks.Data.Tests.litedb");
            }

            var liteRepository = new LiteRepository(_tempStream);

            RepositoryService.RunMigrationsAndSetupIndexes(liteRepository.Database);

            return(liteRepository);
        }
Example #8
0
        public ContentStore(LiteDatabase liteDatabase)
        {
            _liteRepository = new LiteRepository(liteDatabase);

            var db = _liteRepository.Database;

            db.GetCollection <ContentCollection>().EnsureIndex("IX_ContentCollection_AppId", cc => cc.ContentType.AppId);
            db.GetCollection <ContentCollection>().EnsureIndex("IX_ContentCollection_Name", cc => cc.Name);

            db.GetCollection <ContentItem>().EnsureIndex("IX_ContentItem_AppId", ci => ci.AppId);
            db.GetCollection <ContentItem>().EnsureIndex("IX_ContentItem_CollectionId", ci => ci.CollectionId);
            db.GetCollection <ContentItem>().EnsureIndex("IX_ContentItem_ContentKey", ci => ci.ContentKey);
        }
Example #9
0
        public Fatura ObterPorId(string id)
        {
            using (var db = new LiteRepository(_db.Context))
            {
                var dbModel = db.Query <FaturaDbModel>()
                              .Include(x => x.Cobrancas)
                              .Include(x => x.Pagamento)
                              .Where(p => p.Id == id)
                              .FirstOrDefault();

                return(_mapper.Map <Fatura>(dbModel));
            }
        }
Example #10
0
 public IEnumerable <UserProfile> GetList(Expression <Func <UserProfile, bool> > filter)
 {
     using (var db = new LiteRepository(_pathToDb))
     {
         var query = db.Query <UserProfile>(CollectionName);
         if (filter != null)
         {
             query = query
                     .Where(filter); // conditional filter
         }
         return(query.ToList());
     }
 }
Example #11
0
 public void ClearPlaylist(string playlistName)
 {
     if (!string.IsNullOrWhiteSpace(playlistName))
     {
         var playlist = jukebox.Playlists.FirstOrDefault(p => p.Name.Equals(playlistName, StringComparison.CurrentCultureIgnoreCase));
         if (playlist != null)
         {
             jukebox.Playlists.Remove(playlist);
             using var db = new LiteRepository(cxstring);
             db.Delete <Playlist>(playlist.ID);
         }
     }
 }
Example #12
0
        public ILiteRepository GetRepository()
        {
            if (_tempStream == null)
            {
                _tempStream = new TempStream("abremir.postcrossing.engine.tests.litedb");
            }

            var liteRepository = new LiteRepository(_tempStream);

            RepositoryService.SetupIndexes(liteRepository.Database);

            return(liteRepository);
        }
Example #13
0
        public IEnumerable <Fatura> ListarPorCliente(string clienteId)
        {
            using (var db = new LiteRepository(_db.Context))
            {
                var dbModel = db.Query <FaturaDbModel>()
                              .Include(x => x.Cobrancas)
                              .Include(x => x.Pagamento)
                              .Where(x => x.ClienteId == clienteId)
                              .ToList();

                return(_mapper.Map <List <Fatura> >(dbModel));
            }
        }
Example #14
0
        public void Should_generate_guid_id()
        {
            using var repo = new LiteRepository(dbFile).WithUtcDate();
            var entity = new Entity {
                Data = "123"
            };

            repo.Insert(entity);
            var e = repo.Query <Entity>().Where(x => x.Id == entity.Id).First();

            e.Data.Should().Be("123");
            e.Id.Should().NotBe(Guid.Empty);
        }
        public async Task <int> Update(int id, T input)
        {
            int output = 0;

            using (var db = new LiteRepository(embeddedDatabaseContext.ConnectionString))
            {
                var col = db.Database.GetCollection <T>(_collectionName);
                col.Update(input);
                output = 1;
            }

            return(await Task.FromResult(output));
        }
Example #16
0
        public VariableLiteDbStore(string connectionString)
        {
            var con = new ConnectionString(connectionString);

            var fi = new FileInfo(con.Filename);

            if (!fi.Directory.Exists)
            {
                fi.Directory.Create();
            }

            Repository = new LiteRepository(con);
            Repository.Database.Mapper.Entity <Variable>().Id(emp => emp.FullPath, true);
        }
        public LiteDBRuleRepository(string connectionString)
        {
            var con = new ConnectionString(connectionString);

            var fi = new FileInfo(con.Filename);

            if (!fi.Directory.Exists)
            {
                fi.Directory.Create();
            }

            Repository = new LiteRepository(con);
            Repository.Database.Mapper.Entity <MiddlerRuleDbModel>().Id(emp => emp.Id, true);
        }
        public Fichario()
        {
            LiteDbService.Default.DefinirMapeamento <Registro>(map =>
            {
                map.Id(m => m.Id)
                .Field(m => m.Nome, "NomeCompleto")
                .Field(m => m.Telefone, "Telefone")
                .Field(m => m.EndEmail, "Email")
                .Ignore(m => m.Email);
            });
            _repositorio = LiteDbService.Default.GetLiteDbAccess();

            InicializarSequenceSeNecessario();
        }
        /// <summary>
        /// Get single document
        /// </summary>
        /// <param name="expression">The expression<see cref="System.Linq.Expressions.Expression{Func{T, bool}}"/></param>
        /// <returns>The <see cref="Task{T}"/></returns>
        public async Task <T> GetById(int id)
        {
            var output = default(T);

            await Task.Run(() =>
            {
                using (var db = new LiteRepository(embeddedDatabaseContext.ConnectionString))
                {
                    output = db.Query <T>().Where(x => x.Id == id).FirstOrDefault();
                }
            });

            return(output);
        }
        /// <summary>
        /// Finds the specified expression.
        /// </summary>
        /// <param name="expression">The expression.</param>
        /// <returns></returns>
        public async Task <List <T> > FindAll(Expression <Func <T, bool> > expression)
        {
            List <T> output = null;

            await Task.Run(() =>
            {
                using (var db = new LiteRepository(embeddedDatabaseContext.ConnectionString))
                {
                    output = db.Query <T>().Where(expression).ToList();
                }
            });

            return(output);
        }
        /// <summary>
        /// Saves new message and List Last 30 messages sent to given chat room.
        /// </summary>
        /// <param name="user">User name.</param>
        /// <param name="message">Message information.</param>
        /// <param name="chatRoom">Chat room.</param>
        /// <returns></returns>
        public static List <Message> SaveMessageAndListLastThirtyMessages(string user, string message, string chatRoom)
        {
            using (var db = new LiteRepository(@"MyData.db"))
            {
                Message newMessage = new Message {
                    Id = System.Guid.NewGuid(), MessageText = message, Sender = user, ChatRoom = chatRoom, SentTime = DateTime.Now
                };
                db.Insert <Message>(newMessage);
                db.Database.GetCollection <Message>().EnsureIndex("ChatRoom");
                var messages = db.Query <Message>().Where(x => x.ChatRoom == chatRoom).ToList();

                return(messages.OrderByDescending(x => x.SentTime).Take(30).ToList());
            }
        }
Example #22
0
 private void AddTagIfNotExists(IEnumerable <TagDto> tags)
 {
     using (var db = new LiteRepository(_connectionString))
     {
         foreach (var tag in tags)
         {
             var exists = db.FirstOrDefault <TagDto>(x => x.NormalizedName == tag.NormalizedName);
             if (exists == null)
             {
                 db.Insert <TagDto>(tag);
             }
         }
     }
 }
Example #23
0
 public Order CreateNewOrder(List <OrderItem> model)
 {
     using (var db = new LiteRepository(connectionString))
     {
         var newOrder = new Order
         {
             OrderNumber = Guid.NewGuid(),
             Status      = "Pending",
             Items       = model
         };
         db.Insert <Order>(newOrder);
         return(newOrder);
     }
 }
Example #24
0
        public bool Remove(int id)
        {
            using (var db = new LiteRepository(_connectionString))
            {
                var entity = db.FirstOrDefault <TModel>(x => x.Id == id && !x.Removed);
                if (entity == null)
                {
                    return(false);
                }

                entity.Removed = true;
                return(db.Update(entity));
            }
        }
Example #25
0
        protected void Save <TState>(TState aggregateState, Guid id)
            where TState : struct
        {
            using (var db = new LiteRepository(_connectionString, _mapper))
            {
                var stateWrapped = new StateWrapper <TState>
                {
                    Id    = id,
                    State = aggregateState
                };

                db.Upsert(stateWrapped, _collectionName);
            }
        }
Example #26
0
        public EntityRepository(LiteRepository db, IChangedMessageBus <IEntity> eventSource) : base(db, CollectionName)
        {
            db.Database
            .GetCollection(CollectionName)
            .EnsureIndex(
                name: nameof(Entity.UniqueName),
                expression: $"$.{nameof(Entity.UniqueName)}",
                unique: true);

            db.Database
            .GetCollection <Entity>(CollectionName)
            .EnsureIndex(e => e.Category);

            this.eventSource = eventSource;
        }
Example #27
0
        //irasome duomenis i LitleDB
        private void InsertIntoLitleDB()
        {
            if (connectionString == "")
            {
                return;
            }

            using (var db = new LiteRepository(connectionString))
            {
                foreach (Elementas el in elementai)
                {
                    db.Upsert(el);
                }
            }
        }
Example #28
0
        public void Read_bson_with_more_fields_then_entity()
        {
            using var repo = new LiteRepository(dbFile).WithUtcDate();
            repo.Insert(new BigEntity {
                Field1 = "111", Field2 = "222"
            }, "col");
            var e = repo.Query <SmallEntity>("col").First();

            e.Field1.Should().Be("111");
            repo.Update(e, "col");
            var e2 = repo.Query <BigEntity>("col").First();

            e2.Field1.Should().Be("111");
            e2.Field2.Should().BeNullOrEmpty();
        }
Example #29
0
        protected TAggregate Get <TAggregate, TState>(Guid id, Func <TState, TAggregate> mapping)
            where TAggregate : class
            where TState : struct
        {
            using (var db = new LiteRepository(_connectionString, _mapper))
            {
                var state = db.First <StateWrapper <TState> >(
                    sw => sw.Id.Equals(id), _collectionName
                    ).State;

                var aggregate = mapping(state);

                return(aggregate);
            }
        }
Example #30
0
        public BuStarRepository(string connectionString,
                                string weatherApiKey,
                                IDataParseService dataParseServiceParam,
                                IDateTimeService dateTimeServiceParam,
                                IDataCache dataCacheParam,
                                IWeatherCache weatherCacheParam)
        {
            repository         = new LiteRepository(connectionString);
            this.weatherApiKey = weatherApiKey;

            this.dataParseService = dataParseServiceParam;
            this.dateTimeService  = dateTimeServiceParam;
            this.dataCache        = dataCacheParam;
            this.weatherCache     = weatherCacheParam;
        }