public async Task Get_By_Id()
        {
            //Given
            var       repo     = new SqliteRepository <TestTable, int>(_tempDbPath);
            TestTable expected = TestTable.Generate();

            //When
            TestTable actual = null;

            using (var conn = await repo.OpenAsync(CancellationToken.None))
            {
                await TestTable.CreateTableAsync(conn);

                await expected.InsertAsync(conn);

                actual = await repo.GetAsync(expected.Id);

                await TestTable.DropAsync(conn);
            }

            //Then
            Assert.NotNull(actual);
            Assert.Equal(expected.Id, actual.Id);
            Assert.Equal(expected.Message, actual.Message);
        }
        public async Task Query()
        {
            //Given
            var       repo      = new SqliteRepository <TestTable, int>(_tempDbPath);
            TestTable expected1 = TestTable.Generate();
            TestTable expected2 = TestTable.Generate();

            //When
            TestTableCountQueryResponse actual = null;

            using (var conn = await repo.OpenAsync(CancellationToken.None))
            {
                await TestTable.CreateTableAsync(conn);

                await expected1.InsertAsync(conn);

                await expected2.InsertAsync(conn);

                var list = await repo.QueryAsync <TestTableCountQueryResponse>(new TestTableCountQuery());

                actual = list.SingleOrDefault();

                await TestTable.DropAsync(conn);
            }

            //Then
            Assert.NotNull(actual);
            Assert.Equal(2, actual.Count);
        }
        public async Task Ctor_Null_Opens_InMemory()
        {
            //Given
            var       repo     = new SqliteRepository <TestTable, int>(null);
            TestTable expected = TestTable.Generate();

            //When
            TestTable actual = null;

            using (var conn = await repo.OpenAsync(CancellationToken.None))
            {
                await TestTable.CreateTableAsync(conn);

                await expected.InsertAsync(conn);

                actual = await conn.QuerySingleOrDefaultAsync <TestTable>(
                    $"SELECT * FROM {nameof(TestTable)} WHERE Id = @id",
                    new { id = expected.Id });

                await TestTable.DropAsync(conn);
            }

            //Then
            Assert.NotNull(actual);
            Assert.Equal(expected.Id, actual.Id);
            Assert.Equal(expected.Message, actual.Message);
        }
        public async Task Get_All()
        {
            //Given
            var       repo      = new SqliteRepository <TestTable, int>(_tempDbPath);
            TestTable expected1 = TestTable.Generate();
            TestTable expected2 = TestTable.Generate();

            //When
            TestTable actual1 = null;
            TestTable actual2 = null;

            using (var conn = await repo.OpenAsync(CancellationToken.None))
            {
                await TestTable.CreateTableAsync(conn);

                await expected1.InsertAsync(conn);

                await expected2.InsertAsync(conn);

                var actual = await repo.GetAllAsync();

                actual1 = actual.SingleOrDefault(x => x.Id == expected1.Id);
                actual2 = actual.SingleOrDefault(x => x.Id == expected2.Id);

                await TestTable.DropAsync(conn);
            }

            //Then
            Assert.NotNull(actual1);
            Assert.NotNull(actual2);
            Assert.Equal(expected1.Id, actual1.Id);
            Assert.Equal(expected1.Message, actual1.Message);
            Assert.Equal(expected2.Id, actual2.Id);
            Assert.Equal(expected2.Message, actual2.Message);
        }
Beispiel #5
0
        public void AggregateTest()
        {
            var entities = new List <ResultEntity>();
            var r        = new Random(DateTime.Now.Millisecond);

            for (var i = 0; i < 100; i++)
            {
                entities.Add(new ResultEntity {
                    Sweep  = i + 1,
                    Seed   = i % 3,
                    Signal = i % 2 == 0 ? "A" : "B",
                    Time   = i % 2,
                    Value  = r.Next()
                });
            }

            var tmp    = Path.Combine(Path.GetTempPath(), "Ptolemy.Lib.RepositoryTest_AggregateTest");
            var sqlite = Path.Combine(tmp, "sqlite.db");

            Directory.CreateDirectory(tmp);


            using var repo = new SqliteRepository(sqlite);
            repo.BulkUpsert(entities);

            var ds = new List <Func <Map <string, decimal>, bool> > {
                m => m[LibraRequest.GetKey("A", 1)] <= r.Next(),
                m => m[LibraRequest.GetKey("B", 0)] >= r.Next(),
                m => m[LibraRequest.GetKey("A", 1)] > r.Next(),
                m => m[LibraRequest.GetKey("B", 0)] < r.Next()
            };

            var filtered = entities.Where(s => s.Signal == "A" || s.Signal == "B")
                           .Where(s => 1 <= s.Seed && s.Seed <= 2)
                           .Where(s => 20 <= s.Sweep && s.Sweep <= 50)
                           .AsEnumerable()
                           .GroupBy(x => new { x.Sweep, x.Seed })
                           .Select(g => g.ToMap(k => LibraRequest.GetKey(k.Signal, k.Time), v => v.Value))
                           .ToList();


            var expect = new long[ds.Count];

            foreach (var item in ds.Select((d, i) => new { d, i }))
            {
                expect[item.i] = filtered.Count(item.d);
            }

            var actual = repo.Aggregate(new List <string> {
                "A", "B"
            }, (1, 2), (20, 50), ds, LibraRequest.GetKey,
                                        CancellationToken.None);

            Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.AreEquivalent(
                expect, actual
                );

            Directory.Delete(tmp, true);
        }
Beispiel #6
0
        public void GetAppDurations()
        {
            var conn = new SQLiteConnection("Data Source=dat2.db").OpenAndReturn();
            var repo = new SqliteRepository(conn, new SqliteMigrator(conn));
            var o    = repo.GetAppDurations();
            var durs = new List <(App, TimeSpan)>(o.ToEnumerable().OrderByDescending(x => x.Duration));

            Assert.Contains("chrome", durs.First().Item1.Path);
        }
        public async Task CreateTest()
        {
            using var file = new TemporaryFile();
            var target = new SqliteRepository();

            await target.Create(file.Fullname);

            Assert.True(File.Exists(file.Fullname));
        }
Beispiel #8
0
        public void TestGetAppsIncludingTags()
        {
            var conn    = new SQLiteConnection("Data Source=dat2.db").OpenAndReturn();
            var repo    = new SqliteRepository(conn, new SqliteMigrator(conn));
            var o       = repo.GetApps();
            var appList = new List <List <Tag> >(o.Select(x => new List <Tag>(x.Tags.ToEnumerable())).ToEnumerable());

            Assert.Equal(3, appList.Max(t => t.Count));
        }
Beispiel #9
0
        public App(string databaseLocation)
        {
            InitializeComponent();

            MainPage = new NavigationPage(new MainPage());

            IStorage storage = new SqliteRepository(databaseLocation);

            PenCollectorAdapter = new PenCollectorAdapter(storage);
        }
Beispiel #10
0
        public void SaveItems(List <Item> newItems)
        {
            // There may be zero items, so only call this once to avoid 300+ select queries when the cache is empty.
            List <Item> allItems = Repository.Default.ListItems().ToList();

            using (SqliteConnection connection = new SqliteConnection(Repository.Default.ItemsConnectionString))
            {
                connection.Open();

                SqliteRepository repository = (SqliteRepository)Repository.Default;

                // Perform the inserts inside a transaction to avoid the journal file being constantly opened + closed.
                using (SqliteTransaction transaction = connection.BeginTransaction())
                {
                    SqliteCommand command = new SqliteCommand(connection);
                    command.Transaction = transaction;

                    List <Item> addItems = new List <Item>();
                    bool        hasItems = allItems.Count > 0;

                    foreach (Item item in newItems)
                    {
//						if (hasItems)
//						{
//
//						}
//						else
//						{
//
//						}
                        // Check for duplicates in memory
                        if (!addItems.Any(i => i.Equals(item)) && !allItems.Any(i => i.Equals(item)))
                        {
                            repository.SaveItemForTransaction(command, item);
                            addItems.Add(item);
                        }

                        OnFeedSaved(EventArgs.Empty);
                    }

                    try
                    {
                        transaction.Commit();

                        ItemCache.Current.Clear();
                        Settings.Current.LastUpdate = DateTime.Now;
                    }
                    catch (SqliteException e)
                    {
                        Logger.Warn("An error occured committing the save transaction on new items:{0}", e);
                        transaction.Rollback();
                    }
                }
            }
        }
Beispiel #11
0
 protected override IRepository <T> CreateRepository <T>()
 {
     lock (SyncRoot)
     {
         var repo = new SqliteRepository <T>((ISqliteDbAccessOptions)Options);
         if (Context == null)
         {
             Context = repo.Context;
         }
         return(repo);
     }
 }
        public async Task ReadRecordsTest()
        {
            using var file = new TemporaryFile();
            var target = new SqliteRepository();
            await target.Create(file.Fullname);

            await target.AddRecordAsync(file.Fullname, "Test");

            var records = await target.ReadRecordsAsync(file.Fullname).ToArrayAsync();

            Assert.AreEqual(records, new[] { "Test" });
        }
        public async Task IsEmptyTest()
        {
            using var file = new TemporaryFile();
            var target = new SqliteRepository();
            await target.Create(file.Fullname);

            var initial = await target.IsEmpty(file.Fullname);

            await target.AddRecordAsync(file.Fullname, "Test");

            var subsequent = await target.IsEmpty(file.Fullname);

            Assert.IsTrue(initial);
            Assert.IsFalse(subsequent);
        }
        public async Task CreatesEventsFile()
        {
            var repository   = new SqliteRepository();
            var fileProvider = new WindowsFileProvider();
            var eventStore   = new EventSource(repository, fileProvider);

            using var fileWatcher = new WindowsFileSystemWatcher(fileProvider);
            using var file        = new TemporaryFile();

            file.Append("InitialText");
            using var target = new SourceControl(fileProvider, eventStore, fileWatcher);
            await target.Add(file.Fullname);

            Assert.IsTrue(fileProvider.Exists($"{file.Fullname}.events"));
            Assert.IsFalse(fileProvider.IsEmpty($"{file.Fullname}.events"));
        }
Beispiel #15
0
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            // Set the repository type
            _sqliteRepository = new SqliteRepository();
            Repository.SetInstance(_sqliteRepository);
            Repository.Default.CreateDatabase();

            // Get the settings
            Settings.Read();

            _rootController = new RootController();

            _window = new UIWindow(UIScreen.MainScreen.Bounds);
            _window.Add(_rootController.View);
            _window.MakeKeyAndVisible();

            return(true);
        }
        public async Task AppendsEvents()
        {
            var repository   = new SqliteRepository();
            var fileProvider = new WindowsFileProvider();
            var eventStore   = new EventSource(repository, fileProvider);

            using var fileWatcher = new WindowsFileSystemWatcher(fileProvider);
            using var file        = new TemporaryFile();

            file.Append("InitialText");
            using var target = new SourceControl(fileProvider, eventStore, fileWatcher);
            await target.Add(file.Fullname);

            file.Append("AdditionalText");

            await Task.Delay(10000);

            var lines = await repository.ReadRecordsAsync($"{file.Fullname}.events").CountAsync();

            Assert.AreEqual(2, lines);
        }
Beispiel #17
0
        public void InitializeDatabase()
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            // Sqlite
            string itemsDbFilePath = string.Format("{0}/{1}", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), Settings.Current.ItemsDatabaseFilename);
            string feedsDbFilePath = string.Format("{0}/Assets/Feeds.db", Environment.CurrentDirectory);

            string itemsConnection = string.Format("Data Source={0};Version=3;", itemsDbFilePath);
            string feedsConnection = string.Format("Data Source={0};Version=3;", feedsDbFilePath);

            // The order of these calls is important - the connection strings are needed first.
            SqliteRepository sqliteRepository = new SqliteRepository(itemsDbFilePath);

            Settings.Current.RepositoryInstance = sqliteRepository;
            Repository.SetInstance(Settings.Current.RepositoryInstance, feedsConnection, itemsConnection);

            sqliteRepository.CreateDatabase();

            stopwatch.Stop();
            Logger.Info("StartupLoader.InitializeDatabase took {0}ms", stopwatch.ElapsedMilliseconds);
        }
Beispiel #18
0
        /// <summary>
        /// Start draco process
        /// </summary>
        public void Run()
        {
            Log.OnNext("Start Ptolemy.Draco");
            Log.OnNext($"InputFile: {request.InputFile}");
            Log.OnNext($"TargetDatabaseFile: {request.OutputFile}");

            string[] document;
            try {
                Log.OnNext("Reading InputFile");
                using var sr = new StreamReader(request.InputFile);
                document     = sr.ReadToEnd()
                               .Split("\n", StringSplitOptions.RemoveEmptyEntries)
                               .Skip(1)
                               .ToArray();
            }
            catch (FileNotFoundException) {
                throw new DracoException($"file not found: {request.InputFile}");
            }

            try {
                // input file's format
                //         signalA   signalB
                //    0.    value     value   ...
                //  ...


                // Get signal list
                var keys = document[0].Split(' ', StringSplitOptions.RemoveEmptyEntries);


                var writer = receiver.Buffer(request.BufferSize).Subscribe(
                    r => {
                    using var repo = new SqliteRepository(request.OutputFile);
                    repo.BulkUpsert(r);
                    WriteProgress.OnNext(Unit.Default);
                    Log.OnNext($"Write {r.Count} records");
                }, () => WriteProgress.OnCompleted());

                token.Register(writer.Dispose);


                foreach (var line in document.Skip(1).SelectMany(line => {
                    // Parse: time value value ....
                    var rt = ResultEntity.Parse(request.Seed, request.Sweep, line, keys);
                    ParseProgress.OnNext(Unit.Default);
                    Log.OnNext($"Parsed: {line}");
                    return(rt);
                }))
                {
                    token.ThrowIfCancellationRequested();
                    receiver.OnNext(line);
                }

                Log.OnNext($"Finished Parse");

                receiver.OnCompleted();
                ParseProgress.OnCompleted();
            }
            catch (IndexOutOfRangeException) {
                throw new DracoException($"invalid file format: {request.InputFile}");
            }
            catch (FormatException) {
                throw new DracoException($"データの数値に不正な値があります {request.InputFile}");
            }
            catch (OperationCanceledException) {
                throw new DracoException("Canceled by user");
            }
            catch (Exception e) {
                throw new DracoException($"Unknown error has occured\n\t-->{e}");
            }
        }
Beispiel #19
0
        public static int Main(string[] args)
        {
            var app = new CommandLineApplication()
            {
                Name        = "taxi",
                Description = "Predict taxi rides in NYC.",
            };

            app.Command("boroughs", (command) =>
            {
                var queryOption = command.Option <string>("-q|--query <QUERY>", "A query string to fuzzy search with", CommandOptionType.SingleOrNoValue);

                command.OnExecuteAsync(async(ct) =>
                {
                    try
                    {
                        var repo  = new SqliteRepository <TaxiZone, short>(DbPath);
                        var zones = await repo.GetAllAsync();

                        if (!string.IsNullOrEmpty(queryOption.ParsedValue))
                        {
                            zones = zones.Where(z => z.Borough.StartsWith(queryOption.ParsedValue));
                        }

                        foreach (var zone in zones)
                        {
                            System.Console.WriteLine($" [{zone.Id}]: {zone.Zone}, {zone.Borough}");
                        }

                        return(0);
                    }
                    catch (Exception e)
                    {
                        System.Console.Error.WriteLine(e.ToString());
                        return(-1);
                    }
                });
            });

            app.Command("predict", (command) =>
            {
                var pickUpArgument  = command.Argument <short>("[pick-up]", "Where you will be picked up from.");
                var dropOffArgument = command.Argument <short>("[drop-off]", "Where you will be dropped of at.");
                var vehicleOption   = command.Option <VehicleType>("-v|--vehicle <VEHICLE>", "The type of vehicle to take", CommandOptionType.SingleValue);

                command.OnExecuteAsync(async(ct) =>
                {
                    try
                    {
                        var repo  = new SqliteRepository <TaxiTrip, long>(DbPath);
                        var query = new TaxiTripMetricsQuery
                        {
                            PickUpLocationId  = pickUpArgument.ParsedValue,
                            DropOffLocationId = dropOffArgument.ParsedValue,
                            VehicleType       = vehicleOption.ParsedValue
                        };

                        IEnumerable <TaxiTripMetrics> results = await repo.QueryAsync <TaxiTripMetrics>(query, ct);
                        TaxiTripMetrics metrics = results.SingleOrDefault();

                        System.Console.WriteLine($"Estimated Cost =>     ${metrics.AverageCost:0.00}");
                        System.Console.WriteLine($"Estimated Duration =>  {TimeSpan.FromSeconds(metrics.AverageDurationSeconds)}");

                        return(0);
                    }
                    catch (Exception e)
                    {
                        System.Console.Error.WriteLine(e.ToString());
                        return(-1);
                    }
                });
            });

            return(app.Execute(args));
        }
Beispiel #20
0
 //these values are NOT shared amongst the tests, xunit creates the class again foreach test
 public AlertTests()
 {
     Connection = new SQLiteConnection($"Data Source={Database}").OpenAndReturn();
     Repo       = new SqliteRepository(Connection, new SqliteMigrator(Connection));
 }