public void Initialize() { _data = new List<StoredUser> { new StoredUser {Id = 1, Name = "William Parker", MetaData = "Researcher"}, new StoredUser {Id = 2, Name = "Trudy Jones", MetaData = "Researcher"} }; _mockSet = MockUtility.CreateAsyncMockDbSet(_data, u => u.Id); var mockContext = new Mock<IAutoSysContext>(); mockContext.Setup(s => s.Users).Returns(_mockSet.Object); mockContext.Setup(s => s.Set<StoredUser>()).Returns(_mockSet.Object); mockContext.Setup(s => s.SaveChangesAsync()).Returns(Task.Run(() => { // Increment user ids automatically based on existing ids in mock data var max = _data.Max(u => u.Id); foreach (var user in _data.Where(u => u.Id == 0)) { user.Id = ++max; } return 1; // SaveChangesAsync returns number based on how many times it was called per default })); _context = mockContext; _repository = new DbRepository<StoredUser>(_context.Object); }
public static void Main() { var db = new ApplicationDbContext(); var repo = new DbRepository<Location>(db); var streamer = new StreamReader("../../data/cities.txt", Encoding.Default, true); using (streamer) { while (streamer.ReadLine() != null) { string currentLine = streamer.ReadLine(); var location = new Location() { Name = currentLine }; Console.WriteLine(currentLine); db.Locations.Add(location); db.SaveChanges(); } } Console.ReadLine(); }
public async Task SetUp() { databaseFile = Path.GetTempFileName(); db = new RestlessDb(databaseFile); repository = new DbRepository(db); await repository.Initialize(); }
static LockHelper() { locker = new object(); checkForLog = true; logFile = ConfigurationManager.AppSettings["LogFile"]; db = new DbRepository(); }
public static void Craw(ApplicationDbContext db) { var repo = new DbRepository<JokeCategory>(db); var categoriesService = new CategoriesService(repo); var configuration = AngleSharp.Configuration.Default.WithDefaultLoader(); var browsingContext = BrowsingContext.New(configuration); var jokes = new List<Joke>(); for (int i = 1; i <= 200; i++) { var url = string.Format("http://vicove.com/vic-{0}", i); var document = browsingContext.OpenAsync(url).Result; var jokeContent = document.QuerySelector("#content_box .post-content").TextContent.Trim(); if (!string.IsNullOrWhiteSpace(jokeContent)) { var categoryName = document.QuerySelector("#content_box .thecategory a").TextContent.Trim(); var category = categoriesService.EnsureCategory(categoryName); var joke = new Joke { Category = category, Title = "Joke " + i, Content = jokeContent }; jokes.Add(joke); if (jokes.Count == 100) { break; } } } db.Jokes.AddOrUpdate(jokes.ToArray()); db.SaveChanges(); }
public static void Main() { var db = new ApplicationDbContext(); var repo = new DbRepository<Category>(db); var categoriesService = new CategoriesService(repo); var configuration = Configuration.Default.WithDefaultLoader(); var browsingContext = BrowsingContext.New(configuration); for (int i = 1; i <= 10000; i++) { var url = $"http://vicove.com/vic-{i}"; var document = browsingContext.OpenAsync(url).Result; var jokeContent = document.QuerySelector("#content_box .post-content").TextContent.Trim(); //if (!string.IsNullOrWhiteSpace(jokeContent)) //{ // var categoryName = document.QuerySelector("#content_box .thecategory a").TextContent.Trim(); // var category = categoriesService.EnsureCategory(categoryName); // var joke = new Joke { Category = category, Content = jokeContent }; // db.Jokes.Add(joke); // db.SaveChanges(); // Console.WriteLine(i); //} } }
/// <summary> /// Initializes a new instance of the /// <see cref="TpContext"/> class. /// </summary> public TpContext() : base("TpContext") { Configuration.LazyLoadingEnabled = false; _assets = new DbRepository<Asset, int>(this, Assets, _ => _.Id); _jobs = new DbRepository<Job, int>(this, Jobs, _ => _.Id); }
public MainWindowModel(Func<SelectFileType, string, string, string> selectFile) { this.selectFile = selectFile; var canAddChild = this.ObserveProperty(x => x.SelectedItem).Select(x => x is ApiCollectionModel); AddApi = RxFunction.CreateAsync(async () => await OnAddApi(null)); AddApiCollection = RxFunction.CreateAsync(async () => await OnAddApiCollection(null)); AddChildApi = RxFunction.CreateAsync(async () => await OnAddApi((ApiCollectionModel)SelectedItem), canAddChild); AddChildApiCollection = RxFunction.CreateAsync(async () => await OnAddApiCollection((ApiCollectionModel)SelectedItem), canAddChild); Export = RxCommand.Create(OnExport); Import = RxCommand.CreateAsync(OnImport); Title = "Restless"; Items = new RxList<ApiItemModel>(); Methods = httpMethods.ToList(); OutputTypes = outputTypes.ToList(); SplitterPosition = Settings.Default.MainWindowSplitterPosition; ApiSplitterPosition = Settings.Default.ApiPanelSplitterPosition; this.ObservePropertyChange(x => x.SplitterPosition).Throttle(TimeSpan.FromSeconds(1)).Subscribe(x => { Settings.Default.MainWindowSplitterPosition = x; Settings.Default.Save(); }); this.ObservePropertyChange(x => x.ApiSplitterPosition).Throttle(TimeSpan.FromSeconds(1)).Subscribe(x => { Settings.Default.ApiPanelSplitterPosition = x; Settings.Default.Save(); }); ApiItemModel selectedItem = null; this.ObservePropertyChange(x => x.SelectedItem).Subscribe(x => { if (selectedItem != null) selectedItem.IsSelected = false; selectedItem = x; if (selectedItem != null) selectedItem.IsSelected = true; }); Repository = new DbRepository(new RestlessDb()); Task.Run(async () => { await Repository.Initialize(); await Repository.Load(); foreach (var apiItem in Repository.Items) { if (apiItem is Api) Items.Add(new ApiModel(this, null, (Api)apiItem)); else Items.Add(new ApiCollectionModel(this, null, (ApiCollection)apiItem)); } }); DeleteSelectedItem = RxCommand.CreateAsync(OnDeleteSelectedItem); }
public async Task QueryMultipleAsync_Retry_Success() { SetupAsync(); var attemptCount = 0; _db = new DbRepository( _dbResources.Object, _cache.Object, _ => { attemptCount++; if (attemptCount < 2) { throw new InvalidOperationException(); } return(_connection.Object); }); _db.OnError += (sender, args) => _onErrorEvents.Add(args); _db.OnQueryComplete += (sender, args) => _onQueryCompleteEvents.Add(args); var result = await _db.QueryMultipleAsync(new FakeMultipleStoredProc(), "foo"); Assert.AreEqual("multiple_result", result); Assert.AreEqual(2, attemptCount); _dbResources.Verify(x => x.ChooseDb("mobile_ro").SelectRandomly(), Times.Exactly(2)); Assert.AreEqual(1, _onErrorEvents.Count); Assert.IsInstanceOf <InvalidOperationException>(_onErrorEvents[0].Error); Assert.AreEqual(1, _onErrorEvents[0].AttemptCount); Assert.AreEqual(2, _onQueryCompleteEvents.Count); Assert.IsInstanceOf <FakeMultipleStoredProc>(_onQueryCompleteEvents[0].StoredProc); Assert.IsInstanceOf <FakeMultipleStoredProc>(_onQueryCompleteEvents[1].StoredProc); Assert.IsNotNull(_onQueryCompleteEvents[0].Error); Assert.IsNull(_onQueryCompleteEvents[1].Error); }
private void SaveNewProduct(DbRepository repository) { if (!ValidateRequiredFields()) { return; } if (!ValidateDuplicateRecord()) { return; } var productRepository = repository; if (FlatMessageBox.Show("Do you want to save new product?", "Update Product", DialogButtons.YesNo, DialogType.Question) == DialogButton.Yes) { var newProduct = new Products() { ProductCode = txtProductCode.Text.Trim(), ProductName = txtProductCode.Text.Trim(), SalesRate = decimal.Parse(txtSalesRate.Text), PurchaseRate = decimal.Parse(txtPurchaseRate.Text), Unit = txtUnit.Text.Trim(), Description = txtDescription.Text.Trim(), Quantity = int.Parse(txtQuantity.Text), DateTimeCreated = DateTime.Now, IsActive = true }; productRepository.Products.Add(newProduct); productRepository.Commit(); } ResetToDefault(); MessageAlert.Show("New product has successfully added.", "New Product", AlertType.Info); }
/// <summary> /// 删除 /// </summary> /// <param name="ids"></param> /// <returns></returns> public WebResult <bool> Delete_Role(string ids) { if (!ids.IsNotNullOrEmpty()) { return(Result(false, ErrorCode.sys_param_format_error)); } using (DbRepository entities = new DbRepository()) { var list = Cache_Get_RoleList(); //找到实体 entities.Role.Where(x => ids.Contains(x.ID)).ToList().ForEach(x => { //教练员不能删除 if (!x.ID.Equals("a4b6e88b815d4e2485c5f538cf225f66")) { x.Flag = x.Flag | (long)GlobalFlag.Removed; var index = list.FindIndex(y => y.ID.Equals(x.ID)); if (index > -1) { list[index] = x; } else { list.Add(x); } } }); if (entities.SaveChanges() > 0) { return(Result(true)); } else { return(Result(false, ErrorCode.sys_fail)); } } }
private bool ValidateDuplicateRecord() { ClearErrors(); var isValidated = true; using (var repository = new DbRepository(new DatabaseContext())) { var fullName = $"{txtSupplierName.Text}"; if (IsNew) { if (repository.Suppliers.IsExist(fullName)) { MessageAlert.Show(MessageHelper.DuplicateRecord(fullName), "Error", AlertType.Warning); //isValidated = SetErrorMessage(txtSupplierName, MessageHelper.DuplicateRecord(txtSupplierName.Text)); return(isValidated); } } else { var supplierId = GetSupplierId(); if (repository.Suppliers.IsExist(fullName, supplierId)) { MessageAlert.Show(MessageHelper.DuplicateRecord(fullName), "Error", AlertType.Warning); //isValidated = SetErrorMessage(txtSupplierName, MessageHelper.DuplicateRecord(txtSupplierName.Text)); return(isValidated); } } } return(isValidated); }
public void TestNumericDataTypesInsert() { // Setup var data = new Models.TypeMapNumeric { bigint_column = 123456789, bit_column = true, decimal_column = 12345.6789m, float_column = 12345.6789, int_column = 123456789, money_column = 12345.6789m, numeric_column = 12345.6789m, real_column = 12345, smallint_column = 123, smallmoney_column = 12345.6789m, tinyint_column = 12 }; // Act var sut = new DbRepository <SqlConnection>(Constants.TestDatabase); var id = sut.Insert(data); var result = sut.Query <Models.TypeMapNumeric>(top: 1).FirstOrDefault(); // Assert result.ShouldNotBeNull(); result.bigint_column.ShouldBe(data.bigint_column); result.bit_column.ShouldBe(data.bit_column); result.decimal_column.ShouldBe(data.decimal_column); result.float_column.ShouldBe(data.float_column); result.int_column.ShouldBe(data.int_column); result.money_column.ShouldBe(data.money_column); result.numeric_column.ShouldBe(data.numeric_column); result.real_column.ShouldBe(data.real_column); result.smallint_column.ShouldBe(data.smallint_column); result.smallmoney_column.ShouldBe(data.smallmoney_column); result.tinyint_column.ShouldBe(data.tinyint_column); }
/// <summary> /// 增加 /// </summary> /// <param name="model"></param> /// <returns></returns> public WebResult <bool> Add_Operate(Operate model) { using (DbRepository entities = new DbRepository()) { var limitFlags = entities.Operate.Where(x => (x.Flag & (long)GlobalFlag.Removed) == 0).Select(x => x.LimitFlag ?? 0).ToList(); var limitFlagAll = 0L; // 获取所有角色位值并集 limitFlags.ForEach(x => limitFlagAll |= x); var limitFlag = 0L; // 从低位遍历是否为空 for (var i = 0; i < 64; i++) { if ((limitFlagAll & (1 << i)) == 0) { limitFlag = 1 << i; break; } } model.LimitFlag = limitFlag; model.ID = Guid.NewGuid().ToString("N"); model.CreatedTime = DateTime.Now; model.Flag = (long)GlobalFlag.Normal; model.UpdatedTime = DateTime.Now; model.UpdaterID = Client.LoginUser.ID; entities.Operate.Add(model); if (entities.SaveChanges() > 0) { var list = Cache_Get_OperateList(); list.Add(model); return(Result(true)); } else { return(Result(false, ErrorCode.sys_fail)); } } }
public void TestUpdate() { //arrange var repository = new DbRepository <SqlConnection>(Constants.TestDatabase); var fixtureData = new Customer { Id = 1, FirstName = "Juan-EDITED", LastName = "de la Cruz-EDITED", MiddleName = "Pinto-EDITED", Address = "San Lorenzo, Makati, Philippines 4225-EDITED", IsActive = true, Email = "[email protected]", DateInsertedUtc = DateTime.UtcNow, LastUpdatedUtc = DateTime.UtcNow, LastUserId = Environment.UserName }; //act repository.Update(fixtureData, new { fixtureData.Id }); //assert var savedData = repository.Query <Customer>(fixtureData.Id).FirstOrDefault(); savedData.ShouldNotBeNull(); savedData.Id.ShouldNotBe(0); savedData.GlobalId.ShouldBe(fixtureData.GlobalId); savedData.FirstName.ShouldBe(fixtureData.FirstName); savedData.LastName.ShouldBe(fixtureData.LastName); savedData.MiddleName.ShouldBe(fixtureData.MiddleName); savedData.Address.ShouldBe(fixtureData.Address); savedData.Email.ShouldBe(fixtureData.Email); savedData.IsActive.ShouldBe(fixtureData.IsActive); //savedData.DateInsertedUtc.ShouldBe(fixtureData.DateInsertedUtc); //savedData.LastUpdatedUtc.ShouldBe(fixtureData.LastUpdatedUtc); savedData.LastUserId.ShouldBe(fixtureData.LastUserId); }
/// <summary> /// 获取分页列表 /// </summary> /// <param name="pageIndex">页码</param> /// <param name="pageSize">分页大小</param> /// <param name="title">标题 - 搜索项</param> /// <returns></returns> public PageList <Recharge> GetPageList(int pageIndex, int pageSize, string userName, PayState?stete, DateTime?createdTimeStart, DateTime?createdTimeEnd) { using (DbRepository db = new DbRepository()) { var query = db.Recharge.Where(x => !x.IsDelete); if (userName.IsNotNullOrEmpty()) { var userIDList = db.User.Where(x => !x.IsDelete && x.RealName.Contains(userName)).Select(x => x.ID).ToList(); query = query.Where(x => userIDList.Contains(x.UserID)); } if (createdTimeStart != null) { query = query.Where(x => x.CreatedTime >= createdTimeStart); } if (createdTimeEnd != null) { createdTimeEnd = createdTimeEnd.Value.AddDays(1); query = query.Where(x => x.CreatedTime < createdTimeEnd); } var count = query.Count(); var list = query.OrderByDescending(x => x.CreatedTime).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); var selectUserIDList = list.Select(x => x.UserID).ToList(); var userDic = db.User.Where(x => !x.IsDelete && selectUserIDList.Contains(x.ID)).ToDictionary(x => x.ID); list.ForEach(x => { if (x.UserID.IsNullOrEmpty() && userDic.ContainsKey(x.UserID)) { x.UserName = userDic[x.UserID]?.RealName; } x.TypeStr = x.Type.GetDescription(); x.StateStr = x.State.GetDescription(); }); return(CreatePageList(list, pageIndex, pageSize, count)); } }
public PageList <RelationGroup> GetPageList(int pageIndex, int pageSize, string sendUserName, string toUserName, DateTime?createdTimeStart, DateTime?createdTimeEnd) { using (DbRepository db = new DbRepository()) { var query = db.RelationGroup.Where(x => !x.IsDelete); if (sendUserName.IsNotNullOrEmpty()) { var userIdList = db.User.Where(x => !x.IsDelete & x.Name.Contains(sendUserName)).Select(x => x.ID).ToList(); if (userIdList != null && userIdList.Count > 0) { query = query.Where(x => userIdList.Contains(x.UserID) || userIdList.Contains(x.RelationUserID)); } } if (toUserName.IsNotNullOrEmpty()) { var userIdList = db.User.Where(x => !x.IsDelete & x.Name.Contains(toUserName)).Select(x => x.ID).ToList(); if (userIdList != null && userIdList.Count > 0) { query = query.Where(x => userIdList.Contains(x.UserID) || userIdList.Contains(x.RelationUserID)); } } if (createdTimeStart != null) { query = query.Where(x => x.LastTime >= createdTimeStart); } if (createdTimeEnd != null) { createdTimeEnd = createdTimeEnd.Value.AddDays(1); query = query.Where(x => x.LastTime < createdTimeEnd); } query = query.OrderByDescending(x => x.CreatedTime).Skip((pageIndex - 1) * pageSize).Take(pageSize); var pageList = CreatePageList(query, pageIndex, pageSize); return(pageList); } }
public void SetSelectListItems() { var repo = new DbRepository(); var styles = repo.GetAllStyles(); foreach (var style in styles) { StyleItems.Add(new SelectListItem { Text = style.Name, Value = style.StyleId.ToString() }); } var series = repo.GetAllSeries(); foreach (var s in series) { StyleItems.Add(new SelectListItem { Text = s.Name, Value = s.SeriesId.ToString() }); } var collabs = repo.GetAllCollaborators(); foreach (var collab in collabs) { StyleItems.Add(new SelectListItem { Text = collab.Name, Value = collab.CollaboratorId.ToString() }); } }
/// <summary> /// 兑奖 /// </summary> /// <param name="unid"></param> /// <returns></returns> public string Cash(string unid) { if (!unid.IsNotNullOrEmpty()) { return("数据为空"); } using (DbRepository entities = new DbRepository()) { var userJoinCounter = entities.UserJoinCounter.Find(unid); if (userJoinCounter == null) { return("数据为空"); } if (userJoinCounter.IsPrize != 1) { return("该记录未中奖"); } userJoinCounter.IsCach = 1; userJoinCounter.CachTime = DateTime.Now; return(entities.SaveChanges() > 0 ? "" : "保存出错"); } }
public async Task Create_ReturnsId_NewId() { // Arrange var mockSet = new Mock<DbSet<StoredUser>>(); var mockContext = new Mock<IAutoSysContext>(); mockContext.Setup(m => m.Users).Returns(mockSet.Object); var user = new StoredUser {Name = "Steven", MetaData = "Validator"}; // Act var service = new DbRepository<StoredUser>(mockContext.Object); var id = await service.Create(user); // Assert Assert.AreEqual(user.Id, id); // True for EF but not for interface }
public async Task Create_SavesUserInContext() { // Arrange var mockSet = new Mock<DbSet<StoredUser>>(); var mockContext = new Mock<IAutoSysContext>(); mockContext.Setup(m => m.Users).Returns(mockSet.Object); // Act var service = new DbRepository<StoredUser>(mockContext.Object); var id = await service.Create(new StoredUser()); // Assert // mockSet.Verify(m => m.Add(It.IsAny<StoredUser>()), Times.Once()); mockContext.Verify(m => m.SaveChangesAsync(), Times.Once()); }
public async Task CreateThreeLevelHierarchy() { var rootCollection = new ApiCollection { Items = new RxList<ApiItem>(), Title = "Root" }; await repository.AddItem(rootCollection); await repository.WaitForIdle(); var childCollection = new ApiCollection { Items = new RxList<ApiItem>(), Title = "Child" }; rootCollection.Items.Add(childCollection); await repository.WaitForIdle(); var leaf = new Api { Title = "Leaf" }; childCollection.Items.Add(leaf); await repository.WaitForIdle(); var newRepository = new DbRepository(db); await newRepository.Load(); var loadedRootCollection = (ApiCollection)newRepository.Items.Single(); Assert.AreEqual(rootCollection.Title, loadedRootCollection.Title); var loadedChildCollection = (ApiCollection)loadedRootCollection.Items.Single(); Assert.AreEqual(childCollection.Title, loadedChildCollection.Title); var loadedLeaf = (Api)loadedChildCollection.Items.Single(); Assert.AreEqual(leaf.Title, loadedLeaf.Title); }
public void TestDbRetrieval() { IRepository repo = new DbRepository(); var list = repo.GetDailyHistory(); Assert.That(list.Count.Equals(4)); }