/// <summary>
 /// Saves given user to db.
 /// </summary>
 /// <param name="nickname">New user nickname.</param>
 /// <returns>New user object.</returns>
 public static User Save(string nickname)
 {
     using (var db = new LiteRepository(@"MyData.db"))
     {
         User newUser = new User {
             Id = System.Guid.NewGuid(), Nickname = nickname
         };
         db.Insert <User>(newUser);
         return(newUser);
     }
 }
 /// <summary>
 /// Saves given chat room and returns latest chat room list.
 /// </summary>
 /// <param name="chatRoomName">Chat room name.</param>
 /// <returns>Latest chat room list.</returns>
 public static List <ChatRoom> SaveAndGetLatestChatRoomList(string chatRoomName)
 {
     using (var db = new LiteRepository(@"MyData.db"))
     {
         ChatRoom newChatRoom = new ChatRoom {
             Id = System.Guid.NewGuid(), Name = chatRoomName
         };
         db.Insert <ChatRoom>(newChatRoom);
         return(db.Query <ChatRoom>().ToList());
     }
 }
Beispiel #3
0
        private void Flush()
        {
            var logs = _cache.ToArray();

            _cache.Clear();

            Task.Factory.StartNew(() =>
            {
                _db.Insert((IEnumerable <Log>)logs, "EventLog");
            });
        }
Beispiel #4
0
 public void Write(Person person)
 {
     try
     {
         repository.Insert(person);
     }
     catch (LiteException)
     {
         repository.Update(person);
     }
 }
 public void Write(Poster poster)
 {
     try
     {
         repository.Insert(poster);
     }
     catch (LiteException)
     {
         repository.Update(poster);
     }
 }
Beispiel #6
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");
        }
Beispiel #7
0
        public Result <bool> Insert(T entity, string collectionName = null)
        {
            var result = new Result <bool>();

            try
            {
                _liteRepository.Insert(entity, collectionName);
                result.ResultObject = true;
            }
            catch (Exception ex)
            {
                result.ResultObject       = false;
                result.ResultCode         = (int)ResultStatusCode.InternalServerError;
                result.ResultMessage      = "Hata Oluştu => " + ex;
                result.ResultInnerMessage = "Hata Oluştu => " + ex.InnerException;

                result.ResultStatus = false;
            }

            return(result);
        }
Beispiel #8
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");
        }
Beispiel #9
0
        public void Create(IEnumerable <PvpApiRowModel> ladderRows)
        {
            if (ladderRows == null)
            {
                throw new ArgumentNullException(nameof(ladderRows));
            }

            foreach (PvpApiRowModel row in ladderRows)
            {
                _liteDbRepo.Insert(row);
            }
        }
        public Security GetSecurity()
        {
            var security = _repository.FirstOrDefault <Security>();

            if (security != null)
            {
                return(security);
            }

            security = new Security();
            _repository.Insert(security, "security");
            return(security);
        }
Beispiel #11
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);
        }
        /// <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());
            }
        }
Beispiel #13
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);
             }
         }
     }
 }
Beispiel #14
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);
     }
 }
Beispiel #15
0
        public async Task AddEvent(Event eEvent)
        {
            // Create & insert event into DB
            eEvent.Created = DateTimeOffset.Now;
            _db.Insert(eEvent);

            // Notify Users
            var list = await PermissionCheck(SimplePermissionType.PublishEvents);

            await _nService.NotifyUsers(new Notification
            {
                Message = _localizer["createEventMessage", eEvent.Author, eEvent.TakesPlace],
                Subject = _localizer["createEventSubject", eEvent.Name]
            }, list);
        }
Beispiel #16
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();
        }
Beispiel #17
0
        public UserModel Create(UserModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (!string.IsNullOrWhiteSpace(model.Password))
            {
                model.Password = BCrypt.Net.BCrypt.HashPassword(model.Password);
            }

            _instance.Insert <UserModel>(model);
            return(model);
        }
Beispiel #18
0
        public void Should_insert_new_bson_document_with_guid_id()
        {
            using var repo = new LiteRepository(dbFile).WithUtcDate();
            var collection = repo.Database.GetCollection("Entity", BsonAutoId.Guid);
            var doc        = new BsonDocument {
                ["Data"] = "666"
            };

            collection.Upsert(doc);
            repo.Insert(new Entity {
                Data = "555"
            });
            var docs = repo.Query <Entity>().ToList();

            docs.Should().OnlyContain(x => x.Id != Guid.Empty);
        }
Beispiel #19
0
        public void Read_untyped_object()
        {
            using var repo = new LiteRepository(dbFile).WithUtcDate();

            var custom = new SmallEntity {
                Id = Id <SmallEntity> .NewId(), Field1 = "ffff"
            };

            repo.Insert(new BigEntity {
                Field1 = "111", Field2 = "222", Custom = custom
            });
            var e       = repo.Query <BigEntity>().First();
            var custom2 = e.Custom.Should().BeOfType <SmallEntity>().Subject;

            custom2.Id.Should().Be(custom.Id);
            custom2.Field1.Should().Be(custom.Field1);
        }
Beispiel #20
0
        public void Should_insert_many_documents(int count)
        {
            var cts   = new CancellationTokenSource(TimeSpan.FromSeconds(180));
            var token = cts.Token;

            using var repo = new LiteRepository(dbFile).WithUtcDate();
            for (var i = 0; i < count; i++)
            {
                repo.Insert(new Entity {
                    Data = i.ToString()
                });
                if (token.IsCancellationRequested)
                {
                    break;
                }
            }
        }
Beispiel #21
0
        public async Task <ActionResult> Create([FromBody] Event hggEvent)
        {
            var user = await _userManager.GetUserAsync(HttpContext.User);

            hggEvent.Author = user;

            if (ModelState.IsValid)
            {
                _db.Insert(hggEvent);

                return(Json("OK"));

                //return RedirectToAction(nameof(PublishedIndex));
            }

            return(BadRequest());
        }
Beispiel #22
0
        public ActionResult Create([Bind("TagName")] Tag tag)
        {
            if (ModelState.IsValid)
            {
                db.Insert(tag);
                _audit.Add(new TagAudit()
                {
                    Tag    = tag.TagName,
                    TagId  = tag.Id.ToString(),
                    Type   = "created",
                    User   = _userManager.GetUserName(User),
                    UserId = _userManager.GetUserId(User)
                });
                return(RedirectToAction(nameof(Index)));
            }

            return(View());
        }
Beispiel #23
0
        private static void EnsurePdfFile(this LiteRepository repo, PdfFile value, bool updateLastSeen = true)
        {
            var pdf = repo.GetPdf(value.Md5);

            if (pdf == null)
            {
                value.Id = (Guid)repo.Insert <PdfFile>(value);
            }
            else
            {
                value.Id = pdf.Id;
            }
            if (updateLastSeen)
            {
                value.LastSeen = DateTime.Now;
            }
            repo.Update(value);
        }
        public async Task Handle(SubmitOrder message, IMessageHandlerContext context)
        {
            log.Info($"Order arrived for movie {message.Movie}");

            var movie = db.Query <Movie>()
                        .Where(s => s.Id == message.Movie)
                        .SingleOrDefault();

            if (movie == null)
            {
                throw new ArgumentException($"Movie {message.Movie} not found in datastore", nameof(message.Movie));
            }

            var order = new Order
            {
                Id = Guid.NewGuid(),
                MovieIdentifier   = message.Movie,
                TheaterIdentifier = message.Theater,
                UserIdentifier    = message.UserId,
                MovieTime         = message.Time,
                NumberOfTickets   = message.NumberOfTickets
            };

            bool immediatelyApproved = movie.TicketType != TicketType.DrawingTicket;

            await context.Reply(new OrderSubmission()
            {
                OrderId         = Guid.NewGuid(),
                Movie           = message.Movie,
                MovieTime       = message.Time,
                Theater         = message.Theater,
                NumberOfTickets = message.NumberOfTickets,
                Approved        = immediatelyApproved,
            });

            // We could prevent publishing if it's a TicketType.DrawingTicket.
            // But what if in the future we do want to get notified? We'd have to change this handler again.
            // So let's put it in right now! :-)
            await context.Publish(new OrderAccepted(order.Id));

            // Insert last because it's a non-transactional resource that cannot easily be rolled back.
            db.Insert(order);
        }
Beispiel #25
0
        public void Should_serialize_and_deserialize_to_litedb()
        {
            using var repo = new LiteRepository(dbFileName).WithUtcDate();
            var cls = new Class {
                Id = Id <Class> .NewId(), Name = "Class1"
            };
            var rider = new Rider {
                Id = Id <Rider> .NewId(), Name = "Rider1", ClassId = cls.Id
            };

            repo.Insert(cls);
            repo.Upsert(rider);
            repo.Upsert(rider);
            repo.Query <Rider>().Count().Should().Be(1);

            var persistedRider = repo.Query <Rider>().Where(x => x.Id == rider.Id).First();

            persistedRider.Name.Should().Be("Rider1");
            var persistedClass = repo.Query <Class>().Where(x => x.Id == persistedRider.ClassId).First();

            persistedClass.Name.Should().Be("Class1");
        }
Beispiel #26
0
        IError IDataService.InsertItemActive(IItemActive item)
        {
            IError error = ErrorInit();

            try
            {
                repo.Insert((ItemActive)item);
                return(error);
            }
            catch (Exception ex)
            {
                error = Helpers.ErrorMessage(ErrorType.NoUniqueID,
                                             ex.Message);
                errorService.Write(error);
                return(error);
            }
        }
        public void Gravar(Registro registro)
        {
            EnsureNotDisposed();

            var ehTransiente = EhTransiente(registro.Id);

            if (ehTransiente)
            {
                int       id = registro.Id;
                BsonValue result;
                result = _repositorio.Insert(registro, ColecaoRegistros);

                _repositorio.Database.GetCollection <Registro>(ColecaoRegistros)
                .EnsureIndex(reg => reg.Id, true);

                registro.Id = result.AsInt32;

                ExcluirTransiente(id);
            }
            else
            {
                _repositorio.Update(registro, ColecaoRegistros);
            }
        }
Beispiel #28
0
    public IObservable <Tuple <OperationResult, TimeEntry> > EnterNewCustomTimeEntry(DateTime start, DateTime end)
    {
        TimeEntry entry = null;

        return(Observable.Start(() =>
        {
            if ((end - start).TotalHours < 0)
            {
                return new Tuple <OperationResult, TimeEntry>(OperationResult.EndedBeforeItStarted, null);
            }
            if (end.Date.DayOfWeek != start.Date.DayOfWeek)
            {
                return new Tuple <OperationResult, TimeEntry>(OperationResult.DifferenceBetweenDatesTooBig, null);
            }
            var id = repo.Insert <TimeEntry>(entry = new TimeEntry
            {
                EntryTimeEnd = end,
                EntryTimeStart = start
            });

            entry.Id = id;
            return new Tuple <OperationResult, TimeEntry>(OperationResult.OK, entry);
        }, Scheduler.ThreadPool));
    }
Beispiel #29
0
 public void Insert(T item)
 {
     var s = _liteRepository.Insert(item);
 }
Beispiel #30
0
 public void Add(ModuleSettingsEntity moduleSettingsEntity)
 {
     _repository.Insert(moduleSettingsEntity);
 }