public void TestMethod1() { Core.Init(); this.vasa = new TestClass("Vasilii", 1, Guid.NewGuid()); this.kristina = new TestClass("Kristina", 2, Guid.NewGuid()); this.vitja = new TestClass("Vitja", 3, Guid.NewGuid()); SQLiteStorage storage = (SQLiteStorage)Core.GetStorage(typeof(TestClass)); TestClass vasa2 = (TestClass)storage.Items[vasa.ID]; Assert.AreSame(vasa, vasa2); Assert.AreEqual(vasa.StringValue, "Vasilii"); Assert.AreEqual(vasa.ShortValue, 1); Assert.AreEqual(vasa.IntValue, short.MaxValue); Assert.AreEqual(vasa.LongValue, int.MaxValue); Assert.AreEqual(vasa.DecimalValue, decimal.One); Assert.AreEqual(vasa.DoubleValue, 2.3); Assert.AreEqual(vasa.FloatValue, 2.3F); Assert.AreNotEqual(vasa.GuidValue, null); storage.SaveToDisk(); storage.LoadFromDisk(); Assert.AreEqual(storage.Items.Count, 3); Core.Close(); }
public void Ctor_CanCreateSqlServerStorage_WithExistingConnection() { var connection = ConnectionUtils.CreateConnection(); var storage = new SQLiteStorage(connection); Assert.NotNull(storage); }
public void CouldOpenCloseStorage() { var path = TestUtils.GetPath(clear: true); var storage = new SQLiteStorage($@"Filename={Path.Combine(path, "metadatastorage.db")}"); storage.Dispose(); }
private async Task Application_StartupAsync() { // This frees up the Ctrl-I input binding for italics AvalonEditCommands.IndentSelection.InputGestures.Clear(); AppPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); Local = new SQLiteStorage(); await Local.Initialize(); string username = Local.GetUsername().Result; Cloud = new GoogleDriveStorage(username); if (String.IsNullOrWhiteSpace(username)) { App.Current.Dispatcher.Invoke(() => ShowLoginDialog(true)); } else { if (!Cloud.IsInternetConnected() || await Cloud.Connect()) { App.Current.Dispatcher.Invoke(() => ShowMainWindow()); } else { App.Current.Dispatcher.Invoke(() => ShowLoginDialog(false, "Timeout attempting to login. Please try again.")); } } }
public void TestTaskCreation() { SQLiteStorage storage = new SQLiteStorage(inMemory: true); storage.AddModel <User>(); storage.AddModel <Project>(); storage.AddModel <Task>(); User user = new User(storage) { name = "Test User" }; Project project = new Project(storage) { name = "Test Project" }; Task task = new Task(project, user, storage); task.Save(); Task loaded = Task.GetById(storage, task.Id); Assert.IsTrue(task.IsSaved()); Assert.IsTrue(loaded.IsSaved()); Assert.IsTrue(user.IsSaved()); Assert.IsTrue(project.IsSaved()); Assert.AreEqual(loaded.Project.name, "Test Project"); Assert.AreEqual(loaded.Performer.name, "Test User"); task.Description = "Updated description"; task.Save(); }
public void CouldIncrementCounter() { var path = TestUtils.GetPath(clear: true); var storage = new SQLiteStorage($@"Filename={Path.Combine(path, "metadatastorage.db")}"); var md1 = new MetadataRecord() { PK = "test1:/md1", Metadata = new Metadata("md1"), RepoId = 2, ContainerId = 1 }; var insertResult = storage.InsertMetadataRow(md1); Assert.IsTrue(insertResult); var result = storage.IncrementCounter("test1:/md1"); var result1 = storage.IncrementCounter("test1:/md1"); Assert.AreEqual(result1, result + 1); var mdExact = storage.GetExactMetadata("test1:/md1"); Assert.AreEqual(result1, mdExact.Counter); storage.Dispose(); }
public static void Upload(string _dbName) { var serverSideAs = new List<UplodableObject> { new UplodableObject((int) ETestKind.A) {new UValue<int>("IVAL", 1)}, new UplodableObject((int) ETestKind.A) {new UValue<int>("IVAL", 2)}, }; var serverSideBs = new List<UplodableObject> { new UplodableObject((int) ETestKind.B) {new UValue<string>("SVAL", "B1")}, new UplodableObject((int) ETestKind.B) {new UValue<string>("SVAL", "B2")}, }; var parents = new List<UplodableObject> { new UplodableObject((int) ETestKind.PARENT) {new UValue<string>("NAME", "P1")}, new UplodableObject((int) ETestKind.PARENT) {new UValue<string>("NAME", "P2")}, }; var childs = new List<UplodableObject> { new UplodableObject((int) ETestKind.CHILD) {new UValue<double>("CVAL", 3.3)}, new UplodableObject((int) ETestKind.CHILD) {new UValue<double>("CVAL", 4.4)}, new UplodableObject((int) ETestKind.CHILD) {new UValue<double>("CVAL", 5.0)} }; var serverSideRefs = new List<UplodableObject> { new UplodableObject((int) ETestKind.REF) {new UValue<Guid>("RVAL", serverSideAs[0].Uid), new UValue<Guid>("CHILD_REF", childs[1].Uid)}, new UplodableObject((int) ETestKind.REF) {new UValue<Guid>("RVAL", serverSideAs[1].Uid), new UValue<Guid>("CHILD_REF", childs[2].Uid)}, }; using (var st = new SQLiteStorage(_dbName)) { using (st.CreateTransaction()) { foreach (var currency in serverSideAs) { st.InsertMain(currency); } foreach (var pair in serverSideBs) { st.InsertMain(pair); } st.InsertMain(childs[0], parents[0].Uid, "LIST".GetHashCode()); st.InsertMain(childs[1], parents[0].Uid, "LIST".GetHashCode()); st.InsertMain(childs[2], parents[1].Uid, "LIST".GetHashCode()); foreach (var index in serverSideRefs) { st.InsertMain(index); } foreach (var prt in parents) { st.InsertMain(prt); } } } }
public SQLiteFetchedJob( [NotNull] SQLiteStorage storage, int id, string jobId, string queue) { if (storage == null) { throw new ArgumentNullException("storage"); } if (jobId == null) { throw new ArgumentNullException("jobId"); } if (queue == null) { throw new ArgumentNullException("queue"); } _storage = storage; Id = id; JobId = jobId; Queue = queue; }
public async Task InvokeAsync(HttpContext context) { var tenant = (AppTenant)context.Items["_tenant"]; var connectionString = tenant.GetConnectionString("HangfireConnection") ?? (_configuration.GetSection("ConnectionStrings").GetChildren().Any(x => x.Key == "HangfireConnection") ? _configuration.GetConnectionString("HangfireConnection") : null); if (connectionString != null) { JobStorage storage; if (string.IsNullOrWhiteSpace(connectionString)) { storage = new MemoryStorage(); } if (ConnectionStringHelper.IsSQLite(connectionString)) { storage = new SQLiteStorage(connectionString); } else { storage = new SqlServerStorage(connectionString); } var options = new DashboardOptions { Authorization = new[] { new HangfireAuthorizationfilter() }, AppPath = _route.Replace("/hangfire", "") }; var middleware = new AspNetCoreDashboardMiddleware(_next, storage, options, _routes); await middleware.Invoke(context); } context.Response.StatusCode = (int)HttpStatusCode.NotFound; }
internal Transaction(StorageQueries queries, SQLiteStorage storage, bool concurrent = false) { _queries = queries; _storage = storage; _commited = false; _concurrent = concurrent; }
public ExpirationManagerFacts() { _storage = ConnectionUtils.CreateStorage(); _queueProviders = _storage.QueueProviders; _token = new CancellationToken(true); }
public ExpirationManager(SQLiteStorage storage, TimeSpan checkInterval) { if (storage == null) { throw new ArgumentNullException("storage"); } _storage = storage; _checkInterval = checkInterval; }
public void GetConnection_ReturnsExistingConnection_WhenStorageUsesIt() { var connection = ConnectionUtils.CreateConnection(); var storage = new SQLiteStorage(connection); using (var storageConnection = (SQLiteConnection)storage.GetConnection()) { Assert.Same(connection, storageConnection.Connection); Assert.False(storageConnection.OwnsConnection); } }
public void TestMethod4() { SQLiteStorage storage = (SQLiteStorage)Core.GetStorage(typeof(User)); // Kung fu in C# int columns = ((Dictionary <DBMemberInfo, DBColumnInfo>)(typeof(SQLiteStorage).GetField("ColumnBindings", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(storage))).Count; Assert.AreEqual(columns, 3); // Core.Close(); }
public void TestGetAll() { SQLiteStorage storage = new SQLiteStorage(inMemory: true); storage.AddModel <User>(); Utils.FillUsers(storage, 20); User[] users = User.GetAll(storage); Assert.AreEqual(users.Length, 20); }
static void TestInternal (int loopCount) { var db = new SQLiteStorage<MockObjectGen.MockUser> (filename); db.Clear (); db.Shrink (); ServiceStack.Text.JsConfig.DateHandler = ServiceStack.Text.JsonDateHandler.ISO8601; logger.Info (String.Format ("Initializing {0} items", loopCount)); var list = MockObjectGen.GetTestUserDefinition (loopCount, "group name test", true).ToList (); int len = loopCount / 50; int start = list.Count - (len + 1); if (start < 0) start = 0; len = start + len; if (len > list.Count) len = list.Count - start; using (Benchmark.Start ("Insertion test {0}", list.Count)) { foreach (var i1 in list) db.Set (i1.Login, i1); } using (Benchmark.Start ("Get All with index {0}", list.Count)) { foreach (var i in list) db.Get (i.Login).Count (); } using (Benchmark.Start ("Get All with linq filter {0} x {1}", (len - start), loopCount)) { for (int i = start; i < len; i++) db.Get ().Where (u => u.Login == list[i].Login).Count (); } using (Benchmark.Start ("Parallel Set And Get Test for some keys ({0})", loopCount / 10)) { var forRes = System.Threading.Tasks.Parallel.ForEach (list.Skip (loopCount / 10).Take (loopCount / 10), u => { db.Set (u.Login, u); db.Get (u.Login).First (); db.Get (u.Login).Count (); }); if (!forRes.IsCompleted) throw new Exception ("Parallel execution error!"); }; db.Clear (); db.Shrink (); }
public MainWindow() { InitializeComponent(); storage = new SQLiteStorage(); storage.AddModel <User>(); storage.AddModel <Project>(); storage.AddModel <Task>(); UpdateProjectBox(); UpdatePerformerBox(); UpdateTable(); }
public static async Task DeleteAllAsync <T>() where T : ISQLiteData, new() { try { using (var con = new SQLiteStorage <T>()) { await con.DeleteAllAsync(); } } catch (Exception ex) { await UserDialogs.Instance.AlertAsync(ex.Message); } }
public static SQLiteStorage GetSqliteStorage(string connectionString) { Log.Information("HangfireSqlite: {ConnectionString}", connectionString); connectionString.EnsureDirectory(); var options = new SQLiteStorageOptions() { QueuePollInterval = TimeSpan.FromSeconds(10) }; var storage = new SQLiteStorage(connectionString, options); return(storage); }
public static SQLiteStorage GetSqliteStorage() { var connectionString = BotSettings.HangfireSqliteDb; Log.Information($"HangfireSqlite: {connectionString}"); var options = new SQLiteStorageOptions() { QueuePollInterval = TimeSpan.FromSeconds(10) }; var storage = new SQLiteStorage(connectionString, options); return(storage); }
public static async Task <T> FindAsync <T>(int pk) where T : ISQLiteData, new() { try { using (var con = new SQLiteStorage <T>()) { return(await con.SelectAsync(pk)); } } catch (Exception ex) { await UserDialogs.Instance.AlertAsync(ex.Message); } return(default);
public void CouldInsertAndSelectMetadata() { var path = TestUtils.GetPath(clear: true); var storage = new SQLiteStorage($@"Filename={Path.Combine(path, "metadatastorage.db")}"); var md1 = new MetadataRecord() { PK = "test1:/md1", Metadata = new Metadata("md1"), RepoId = 2, ContainerId = 1 }; var md2 = new MetadataRecord() { PK = "test1:/md2", Metadata = new Metadata("md2"), RepoId = 2, ContainerId = 2 }; var txn = storage.BeginConcurrent(); var result = storage.InsertMetadataRow(md1); Assert.IsTrue(result); result = storage.InsertMetadataRow(md2); Assert.IsTrue(result); result = storage.InsertMetadataRow(md2); Assert.IsFalse(result); txn.RawCommit(); var mdList = storage.FindMetadata("test1:/md"); Assert.AreEqual(2, mdList.Count); Assert.AreEqual("md1", mdList[0].Metadata.Description); Assert.AreEqual(2, mdList[0].RepoId); Assert.AreEqual(1, mdList[0].ContainerId); var mdExact = storage.GetExactMetadata("test1:/md2"); Assert.AreEqual("md2", mdExact.Metadata.Description); storage.Dispose(); }
public static (BackgroundJobServer server, IRecurringJobManager recurringJobManager, IBackgroundJobClient backgroundJobClient) StartHangfireServer( BackgroundJobServerOptions options, string connectionString, IApplicationLifetime applicationLifetime, IJobFilterProvider jobFilters, JobActivator jobActivator, IBackgroundJobFactory backgroundJobFactory, IBackgroundJobPerformer backgroundJobPerformer, IBackgroundJobStateChanger backgroundJobStateChanger, IBackgroundProcess[] additionalProcesses ) { JobStorage storage; if (string.IsNullOrWhiteSpace(connectionString)) { storage = new MemoryStorage(); } else if (ConnectionStringHelper.IsSQLite(connectionString)) { storage = new SQLiteStorage(connectionString); } else { storage = new SqlServerStorage(connectionString); } var server = new BackgroundJobServer(options, storage, additionalProcesses, options.FilterProvider ?? jobFilters, options.Activator ?? jobActivator, backgroundJobFactory, backgroundJobPerformer, backgroundJobStateChanger); applicationLifetime.ApplicationStopping.Register(() => server.SendStop()); applicationLifetime.ApplicationStopped.Register(() => server.Dispose()); var recurringJobManager = new RecurringJobManager(storage, backgroundJobFactory); var backgroundJobClient = new BackgroundJobClient(storage, backgroundJobFactory, backgroundJobStateChanger); return(server, recurringJobManager, backgroundJobClient); }
public void TestMethod3() { Core.Init(); SQLiteStorage storage = (SQLiteStorage)Core.GetStorage(typeof(TestClass)); List <SQLiteStorageItem> toDelete = new List <SQLiteStorageItem>(); foreach (SQLiteStorageItem item in storage.Items.Values) { toDelete.Add(item); } foreach (var item in toDelete) { item.Delete(); } storage.SaveToDisk(); storage.LoadFromDisk(); Assert.AreEqual(storage.Items.Count, 0); }
public void TestGetUnexistingId() { SQLiteStorage storage = new SQLiteStorage(inMemory: true); storage.AddModel <User>(); Utils.IsThrows(() => User.GetById(storage, 10), "Getting from empty storage must throw"); User user = new User(storage); user.Save(); Utils.IsNotThrows(() => User.GetById(storage, 0), "Getting valid id must not throw"); user.Remove(); Utils.IsThrows(() => User.GetById(storage, 0), "Getting removed id must throw"); }
public TestBackgroundJobServer(IFileSystem fileSystem, ServiceHost serviceHost, int startupDelay = 10000) { _memberName = "QueueHangfireIntegrationTests"; _fileSystem = fileSystem; _serviceHost = serviceHost; // CleanupDatabase(); var builder = new ContainerBuilder(); builder.RegisterType <HangFireTestService>().As <IHangFireTestService>().InstancePerLifetimeScope(); JobStorage = new SQLiteStorage(GetConnectionString()); GlobalConfiguration.Configuration.UseStorage(JobStorage); GlobalConfiguration.Configuration.UseAutofacActivator(builder.Build()); BackgroundJobServer = new BackgroundJobServer(JobStorage); BackgroundJobServer.Should().NotBeNull(); Task.Delay(startupDelay).Wait(); }
public void TestMethod2() { Core.Init(); TestClass x = new TestClass(default(string), default(short), default(Guid), default(int), default(long), default(decimal), default(double), default(float)); SQLiteStorage storage = (SQLiteStorage)Core.GetStorage(typeof(TestClass)); storage.SaveToDisk(); storage.LoadFromDisk(); Assert.AreEqual(x.StringValue, default(string)); Assert.AreEqual(x.ShortValue, default(short)); Assert.AreEqual(x.IntValue, default(int)); Assert.AreEqual(x.LongValue, default(long)); Assert.AreEqual(x.DecimalValue, default(decimal)); Assert.AreEqual(x.DoubleValue, default(double)); Assert.AreEqual(x.FloatValue, default(float)); Assert.AreNotEqual(x.GuidValue, null); Core.Close(); }
public void TestMethod1() { Core.Init(); // SQLiteStorage storage = (SQLiteStorage)Core.GetStorage(typeof(User)); User user1, user2, user3; if (storage.Items.Count < 3) { user1 = new User("User1"); user2 = new User("User2"); user3 = new User("User3"); user1.RelatedUser = user2; user2.RelatedUser = user3; user3.RelatedUser = user1; Assert.AreEqual(user1.RelatedUser.Name, "User2"); Assert.AreEqual(user2.RelatedUser.Name, "User3"); Assert.AreEqual(user3.RelatedUser.Name, "User1"); } }
public static (BackgroundJobServer server, IRecurringJobManager recurringJobManager, IBackgroundJobClient backgroundJobClient) StartHangfireServer(BackgroundJobServerOptions options, string connectionString) { JobStorage storage; if (string.IsNullOrWhiteSpace(connectionString)) { storage = new MemoryStorage(); } else if (ConnectionStringHelper.IsSQLite(connectionString)) { storage = new SQLiteStorage(connectionString); } else { storage = new SqlServerStorage(connectionString); } var filterProvider = JobFilterProviders.Providers; var activator = JobActivator.Current; var backgroundJobFactory = new BackgroundJobFactory(filterProvider); var performer = new BackgroundJobPerformer(filterProvider, activator); var backgroundJobStateChanger = new BackgroundJobStateChanger(filterProvider); IEnumerable <IBackgroundProcess> additionalProcesses = null; var server = new BackgroundJobServer(options, storage, additionalProcesses, options.FilterProvider ?? filterProvider, options.Activator ?? activator, backgroundJobFactory, performer, backgroundJobStateChanger); var recurringJobManager = new RecurringJobManager(storage, backgroundJobFactory); var backgroundJobClient = new BackgroundJobClient(storage, backgroundJobFactory, backgroundJobStateChanger); return(server, recurringJobManager, backgroundJobClient); }
public static async Task InsertOrUpdateAsync <T>(T model) where T : ISQLiteData, new() { try { using (var con = new SQLiteStorage <T>()) { var foundRecord = await con.SelectAsync(model.Id); if (foundRecord != null) { await con.UpdateAsync(model); } else { await con.InsertAsync(model); } } } catch (Exception ex) { await UserDialogs.Instance.AlertAsync(ex.Message); } }
public void TestRemove() { SQLiteStorage storage = new SQLiteStorage(inMemory: true); storage.AddModel <User>(); Utils.FillUsers(storage, 20); User[] users = User.GetAll(storage); Assert.AreEqual(users.Length, 20); users[5].Remove(); users[10].Remove(); users[15].Remove(); users = User.GetAll(storage); Assert.AreEqual(users.Length, 17); Utils.IsThrows(() => User.GetById(storage, 10), "Getting removed id must throw"); Utils.IsNotThrows(() => User.GetById(storage, 11), "Getting existing id must not throw"); }
public async Task QueueHangfire_BackgroundServer_Run() { var builder = new ContainerBuilder(); builder.RegisterType <HangFireTestService>().As <IHangFireTestService>().InstancePerLifetimeScope(); GlobalConfiguration.Configuration.UseAutofacActivator(builder.Build()); var storage = new SQLiteStorage(GetConnectionString(FileSystem, ServiceHost.HangfireTest)); GlobalConfiguration.Configuration.UseStorage(storage); using (var server = new BackgroundJobServer()) { server.Should().NotBeNull(); var monitoringApi = storage.GetMonitoringApi(); monitoringApi.Should().NotBeNull().And.Subject.Should().BeAssignableTo <IMonitoringApi>(); const string testValue = "TestValue"; var hangFireJob = new HangfireJob(testValue); var jobIdString = BackgroundJob.Enqueue <IHangFireTestService>(service => service.ExecuteHangfireTestJobAsync(hangFireJob)); jobIdString.Should().NotBeNull(); int.TryParse(jobIdString, out var jobId).Should().BeTrue(); jobId.Should().BeGreaterThan(0); var jobStatus = await JobQueueClient.WaitForJobToComplete(monitoringApi, jobIdString, 30 * 1000, CancellationToken.None); jobStatus.State.Should().Be(JobState.Succeeded); } }
public SQLiteStorageTest () { Common.Logging.LogManager.GetCurrentClassLogger ().Info ("Initialize"); logDb = new SQLiteStorage<string> (filename, "Log", SQLiteStorageOptions.KeepItemsHistory ()); }
public SQLiteStorageTest () { logger.Info ("Initialize"); logDb = new SQLiteStorage<string> (filename, "Log", SQLiteStorageOptions.KeepItemsHistory ()); }
private ExpirationManager CreateManager(IDbConnection connection) { var storage = new SQLiteStorage(connection); return new ExpirationManager(storage, TimeSpan.Zero); }
public static void Upload(string _dbName) { const string NAME = "NAME"; var currencies = new List<UplodableObject> { new UplodableObject((int) EAlphaKind.CURRENCY) {new UValue<string>(NAME, "United States Dollar"), new UValue<string>("CODE", "USD")}, new UplodableObject((int) EAlphaKind.CURRENCY) {new UValue<string>(NAME, "Great Britain Pound"), new UValue<string>("CODE", "GBP")}, new UplodableObject((int) EAlphaKind.CURRENCY) {new UValue<string>(NAME, "Hong Kong Dollar"), new UValue<string>("CODE", "HKD")}, }; var pairs = new List<UplodableObject> { new UplodableObject((int) EAlphaKind.CURRENCY_PAIR) {new UValue<Guid>("LEFT_CURRENCY", currencies[0].Uid), new UValue<Guid>("RIGHT_CURRENCY", currencies[1].Uid)}, new UplodableObject((int) EAlphaKind.CURRENCY_PAIR) {new UValue<Guid>("LEFT_CURRENCY", currencies[0].Uid), new UValue<Guid>("RIGHT_CURRENCY", currencies[2].Uid)}, new UplodableObject((int) EAlphaKind.CURRENCY_PAIR) {new UValue<Guid>("LEFT_CURRENCY", currencies[1].Uid), new UValue<Guid>("RIGHT_CURRENCY", currencies[2].Uid)}, }; var indexes = new List<UplodableObject> { new UplodableObject((int) EAlphaKind.INDEX) {new UValue<string>(NAME, "S&P 500 Index"), new UValue<Guid>("CURRENCY", currencies[0].Uid)}, new UplodableObject((int) EAlphaKind.INDEX) {new UValue<string>(NAME, "NASDAQ 100 Index"), new UValue<Guid>("CURRENCY", currencies[1].Uid)}, new UplodableObject((int) EAlphaKind.INDEX) {new UValue<string>(NAME, "Hang Seng Index"), new UValue<Guid>("CURRENCY", currencies[2].Uid)}, }; var bonds = new List<UplodableObject> { new UplodableObject((int) EAlphaKind.BOND) {new UValue<string>(NAME, "Sweden Govt Bond 10Y Benchmark Yield"), new UValue<Guid>("CURRENCY", currencies[0].Uid)}, new UplodableObject((int) EAlphaKind.BOND) {new UValue<string>(NAME, "Aus 10yr Treasury Bond"), new UValue<Guid>("CURRENCY", currencies[0].Uid)}, new UplodableObject((int) EAlphaKind.BOND) {new UValue<string>(NAME, "US Long Bond"), new UValue<Guid>("CURRENCY", currencies[0].Uid)}, }; var derivatives = new List<UplodableObject>(); using (var st = new SQLiteStorage(_dbName)) { using (st.CreateTransaction()) { foreach (var currency in currencies) { st.InsertMain(currency); } foreach (var pair in pairs) { st.InsertMain(pair); derivatives.Add(new UplodableObject((int)EAlphaKind.FORWARD) { new UValue<Guid>("ASSET", pair.Uid) }); } foreach (var index in indexes) { st.InsertMain(index); derivatives.Add(new UplodableObject((int)EAlphaKind.FUTURES) { new UValue<Guid>("ASSET", index.Uid) }); } foreach (var bond in bonds) { st.InsertMain(bond); derivatives.Add(new UplodableObject((int)EAlphaKind.FUTURES) { new UValue<Guid>("ASSET", bond.Uid) }); } foreach (var derivative in derivatives) { st.InsertMain(derivative); } for (var i = 0; i < 3; ++i) { var prt = new UplodableObject((int)EAlphaKind.PORTFOLIO) { new UValue<string>(NAME, "Portfolio" + i), new UValue<Guid>("BASE_CURRENCY", currencies[i].Uid), new UValue<decimal>("NOTIONAL_AMOUNT", i*1000000) }; st.InsertMain(prt); for (var index = i; index < derivatives.Count; index += 3) { var pi = new UplodableObject((int)EAlphaKind.PORTFOLIO_INSTRUMENT) { new UValue<Guid>("DERIVATIVE", derivatives[index].Uid), }; st.InsertMain(pi, prt.Uid, "INSTRUMENTS".GetHashCode()); } } } } }
public void SQLiteStorageTest_SimpleTest () { var db = new SQLiteStorage<Item1> (filename); db.Clear (); db.Set ("2", new Item1 { name = "luis", counter = 2, address = "raphael" }); db.Set ("1", new Item1 { name = "xpto", counter = 1, address = "xpto"}); db.Set ("3", new Item1 { name = "xpto", counter = 1, address = "xpto" }); db.Set ("12", new Item1 { name = "name1", counter = 12, address = "address" }); var obj = db.Find (new { counter = 1, name = "xpto" }).FirstOrDefault (); // db.Get ("1"); Assert.IsNotNull (obj, "item not found!"); Assert.IsTrue (obj.name == "xpto", "wrong item!"); Assert.IsTrue (obj.counter == 1, "wrong item!"); var obj2 = db.Get ("1").Where (i => i.counter == 1 && i.name == "xpto").First (); Assert.IsNotNull (obj2, "item not found!"); Assert.IsTrue (obj2.name == "xpto", "wrong item!"); Assert.IsTrue (obj2.counter == 1, "wrong item!"); Assert.IsTrue (db.Get ("1").Count () == 1, "wrong item count!"); Assert.IsTrue (db.Get (new string[] { "1", "2" }).Count () == 2, "wrong item count!"); var details = db.GetDetails ("1").First (); Assert.IsTrue (details.Date.Hour == DateTime.UtcNow.Hour, "wrong date format!"); db.Clear (); db.Set ("1", new Item1 { name = "luis", counter = 1, address = "raphael" }); db.Set ("2", new Item1 { name = "xpto", counter = 1, address = "xpto" }); db.Set ("3", new Item1 { name = "xpto", counter = 1, address = "xpto" }); db.Set ("4", new Item1 { name = "name1", counter = 1, address = "address" }); var list1 = db.Get ().ToList (); var list2 = db.GetAndModify (i => { i.counter = 2; return true; }).ToList (); var list3 = db.Get ().ToList (); Assert.IsTrue (list2.Count == 4, "wrong item count!"); Assert.IsTrue (list2.Sum (i => i.counter) == 8, "wrong item counter (1)!"); Assert.IsTrue (list3.Sum (i => i.counter) == list2.Sum (i => i.counter), "wrong item counter (2)!"); db.GetAndModify (i => { i.counter = 0; return true; }).ToList (); db.GetAndModify ("1", i => { i.counter = 4; return true; }).Count (); db.GetAndModify ("4", i => { i.counter = 5; return true; }).Count (); Assert.IsTrue (db.Get ().Sum (i => i.counter) == 9, "wrong item counter (3)!"); db = new SQLiteStorage<Item1> (filename, SQLiteStorageOptions.KeepItemsHistory ()); db.Clear (); db.Set ("1", new Item1 { name = "xpto", counter = 1, address = "xpto" }); db.Set ("1", new Item1 { name = "xpto", counter = 1, address = "xpto" }); db.Set ("1", new Item1 { name = "xpto", counter = 1, address = "xpto" }); db.Set ("1", new Item1 { name = "xpto", counter = 1, address = "xpto" }); db.GetAndModify ("1", i => { return true; }).Count (); Assert.IsTrue (db.Get ().Sum (i => i.counter) == 8, "wrong item count (4)!"); // parallel tests db = new SQLiteStorage<Item1> (filename, SQLiteStorageOptions.UniqueKeys ()); db.Clear (); // populate db for (int i = 0; i < 100; i++) { db.Set (i.ToString (), new Item1 { name = i.ToString (), counter = 1, address = "xpto" }); } // parallel changes int loopUpperBound = 10; var expectedTotal = db.Get ().Count (); var expectedValue = db.Get ().Sum (i => i.counter) + loopUpperBound; // thread warmup System.Threading.Tasks.Parallel.For (0, loopUpperBound, i => System.Threading.Thread.Sleep (0)); // execute parallel operation var pr = System.Threading.Tasks.Parallel.For (0, loopUpperBound, i => db.GetAndModify ("10", m => { m.counter += 1; return true; }).Count ()); Assert.IsTrue (pr.IsCompleted, "parallel error"); // check results var total = db.Get ().Count (); var newSum = db.Get ().Sum (i => i.counter); var item = db.Get ("10").FirstOrDefault (); Assert.IsTrue (total == expectedTotal, "wrong item expectedTotal (Parallel)!"); Assert.IsTrue (newSum == expectedValue, "wrong item expectedValue (Parallel)! {0} != {1}", newSum, expectedValue); Assert.IsTrue (item.counter == (loopUpperBound + 1), "wrong item counter (Parallel)!{0} != {1}", item.counter, (loopUpperBound + 1)); // final cleanup db.Clear (); db.Shrink (); }
public void Initialize () { System.Diagnostics.Debug.WriteLine ("SQLiteStorageTest.Initialize"); logDb = new SQLiteStorage<string> (filename, "Log", SQLiteStorageOptions.KeepItemsHistory ()); }
public void SQLiteStoragePerformance_SimpleTest () { int loopCounter = 10000; var db = new SQLiteStorage<FFUser> (filename); db.Clear (); uniqueCounter = 0; var list = GetTestUserDefinition (loopCounter, "xpto", true).ToList (); int len = loopCounter / 50; int start = list.Count - (len + 1); if (start < 0) start = 0; len = start + len; if (len > list.Count) len = list.Count - start; Time ("Set Test (" + loopCounter + ")", () => { db.Set (list.Select (u => new KeyValuePair<string, FFUser> (u.Login, u))); }); Time ("Get Test All (" + loopCounter + ")", () => { db.Get ().ToList (); }); Time ("Get Test All Descending (" + loopCounter + ")", () => { db.Get (true).ToList (); }); Time ("Parallel Get Test ForEach Key (" + loopCounter + ")", () => { System.Threading.Tasks.Parallel.ForEach (list, u => db.Get (u.Login).First ()); }); Time ("Get Test ForEach Key (" + loopCounter + ")", () => { foreach (var u in list) db.Get (u.Login).First (); }); Time ("Find Test ForEach Key (" + (len - start) + ")", () => { for (int i = start; i < len; i++) db.Find (new { Login = list[i].Login }).Count (); }); Time ("In-memory Linq Test ForEach Key (" + (len - start) + " x " + loopCounter + ")", () => { for (int i = start; i < len; i++) db.Get().Where (u => u.Login == list[i].Login).Count (); }); Time ("GetAndModify Test ForEach Key (" + loopCounter + ")", () => { foreach (var u in list) db.GetAndModify (u.Login, i => { return true; }).First (); }); db.Clear (); Time ("Set single insert Test (" + (loopCounter / 10) + ")", () => { foreach (var u in list.Take (loopCounter / 10)) db.Set (u.Login, u); }); db.Clear (); Time ("Parallel Set And Get Test for some keys (" + (loopCounter / 8) + ")", () => { Assert.IsTrue (System.Threading.Tasks.Parallel.ForEach (list.Skip (loopCounter / 10).Take (loopCounter / 8), u => { db.Set (u.Login, u); Assert.IsTrue (db.Get (u.Login).Select (i => { Assert.IsTrue (i.Login == u.Login, "Error Parallel Set And Get Test for some keys (wrong item)"); return i; }).Count () == 1, "parallel fail"); }).IsCompleted, "error in Parallel Set And Get Test for some keys "); }); Time ("Vaccum", () => { db.Shrink (); }); }