Esempio n. 1
0
 public ICodeDomain GetDomain(string domainName)
 {
     string connectionString = SQLiteHelpers.ConnectionStringBuilder(_databaseName);
     using (SQLiteConnection connection = new SQLiteConnection(connectionString))
     {
         connection.Open();
         using (SQLiteCommand command =
             new SQLiteCommand(
                 "select ZDZ,ZDSM,SFQS from vg_dictionary where ZDMC='" + domainName + "' Order by PX,ZDZ",
                 connection))
         {
             ICodeDomain codeDomain = new CodeDomain() {Name = domainName};
             using (SQLiteDataReader reader = command.ExecuteReader())
             {
                 while (reader.Read())
                 {
                     ICodeDomainValue codeDomainValue =
                         new CodeDomainValue(reader.GetString(0), reader.GetString(1), reader.GetBoolean(2));
                     codeDomain.Values.Add(codeDomainValue);
                     if (codeDomainValue.IsDefault)
                     {
                         codeDomain.DefaultValue = codeDomainValue;
                     }
                 }
             }
             return codeDomain;
         }
     }
 }
Esempio n. 2
0
        static public void Configure(IServiceCollection serviceCollection)
        {
            //TODO: add interfaces for some of these
            serviceCollection.AddSingleton <SuspendAndResumeService>();
            serviceCollection.AddSingleton <CommandLineActivationHandler>();

            serviceCollection.AddHttpClient(Options.DefaultName, (client) => { client.BaseAddress = new Uri(Secrets.ServerUrl); });

            serviceCollection.AddSingleton <HttpClient>((provider) => provider.GetService <IHttpClientFactory>().CreateClient());

            serviceCollection.AddSingleton <ILogger>((_) => LoggingFactory.BuildLogger());

            // Only ever have one player in the application
            serviceCollection.AddSingleton <PlayerViewModel>();

            serviceCollection.AddSingleton <ServerCaller>();

            //serviceCollection.AddSingleton((provider) => new ServerCaller(provider.GetService<IHttpClientFactory>().CreateClient()));

            string dbPath = FileHelper.GetLibraryDbPath();

            serviceCollection.AddSingleton <SqliteConnection>((_) => SQLiteHelpers.CreateFileDb(dbPath));

            serviceCollection.AddSingleton <Library>();

            //serviceCollection.AddSingleton((provider) => new Library(Environment.MachineName, SQLiteHelpers.CreateFileDb(dbPath),
            //    provider.GetService<ServerCaller>(), provider.GetService<ILogger>()));

            //serviceCollection.AddScoped<ICommonServices, CommonServices>();
            //serviceCollection.AddTransient<LoginViewModel>();

            _rootServiceProvider = serviceCollection.BuildServiceProvider();
        }
Esempio n. 3
0
        public async Task Integration_BasicItemSync()
        {
            Library client1 = new Library("machine1", SQLiteHelpers.CreateInMemoryDb(), _serverCaller, Logger.None);
            Library client2 = new Library("machine2", SQLiteHelpers.CreateInMemoryDb(), _serverCaller, Logger.None);

            // create item on server, pull to 1
            await _serverCaller.CreateNewLibraryItemAsync("foo/bar.mp3");

            await client1.PullFromServer();

            // modify item to generate a bunch of events
            LibraryItem item = client1.Items.Single();

            item.IncrementPlayCount();
            item.IncrementPlayCount();
            item.Name     = "GIMIX set";
            item.FilePath = "bar.mp3";
            item.Artist   = "The Avalanches";
            item.Album    = "Mixes";
            item.AddBookmark(TimeSpan.FromSeconds(30));
            item.AddBookmark(TimeSpan.FromSeconds(40));

            // sync from 1 to 2
            await client1.PushToServer();

            await client2.PullFromServer();

            AssertLibrariesHaveSameItems(client1, client2);

            // Delete a bookmark
            client2.Items.Single().Bookmarks.Count.Should().Be(2);
            client2.Items.Single().DeleteBookmark(item.Bookmarks.First().ID);
            client2.Items.Single().Bookmarks.Count.Should().Be(1);

            // Set bookmark emoji
            LibraryItem client2Item       = client2.Items.Single();
            Bookmark    remainingBookmark = client2Item.Bookmarks.Single();

            client2.Items.Single().SetBookmarkEmoji(remainingBookmark.ID, "🎶");
            client2.Items.Single().Bookmarks.Single().Emoji.Should().Be("🎶");

            client2.Items.Single().IncrementPlayCount();

            await client2.PushToServer();

            await client1.PullFromServer();

            AssertLibrariesHaveSameItems(client1, client2);

            // delete and make sure the delete propagates
            client1.Delete(client1.Items.Single());

            client1.Items.Count.Should().Be(0);

            await client1.PushToServer();

            await client2.PullFromServer();

            AssertLibrariesHaveSameItems(client1, client2);
        }
Esempio n. 4
0
        public async Task Integration_BasicItemSync()
        {
            NeverIncreasingClock clock = new NeverIncreasingClock();
            Library client1            = new Library("machine1", SQLiteHelpers.CreateInMemoryDb(), _serverCaller, Logger.None, clock);
            Library client2            = new Library("machine2", SQLiteHelpers.CreateInMemoryDb(), _serverCaller, Logger.None, clock);

            // create item on server, pull to 1
            await _serverCaller.CreateNewLibraryItemAsync("foo/bar.mp3");

            await client1.PullFromServer();

            // modify item to generate a bunch of events with the same time but increasing ID
            LibraryItem item = client1.Items.Single();

            item.IncrementPlayCount();
            item.IncrementPlayCount();
            item.Name = "foo";
            item.Name = "foo";
            item.Name = "foo";
            item.Name = "foo";
            item.Name = "bar";

            // sync from 1 to 2
            await client1.PushToServer();

            await client2.PullFromServer();

            AssertLibrariesHaveSameItems(client1, client2);
        }
Esempio n. 5
0
        public void UpdateNoteTags_RemovingExistingNoteTags()
        {
            var options = SQLiteHelpers.CreateOptions();

            // SEEDING
            using (var context = new NexusContext(options))
            {
                context.Database.EnsureCreated(); // Creates the in-memory SQLite database

                var note = DataProvider.CreateNote().AssignNoteTags(DataProvider.GetAlphabeticalTags());
                context.Notes.Add(note);

                context.SaveChanges();
            }

            using (var context = new NexusContext(options))
            {
                var repo = new NoteRepository(context);

                repo.UpdateNoteTags(1, new List <string>());
                repo.UnitOfWork.SaveChanges();
            }

            using (var context = new NexusContext(options))
            {
                var note = context.Notes.Include(n => n.NoteTags).First();

                Assert.False(note.NoteTags.Any());
            }
        }
        private void WriteToDatabase(IEnumerable <Report> reports, string filename)
        {
            using (var conn = SQLiteHelpers.CreateConnection(filename))
            {
                conn.Open();
                var command = new SQLiteCommand(conn);
                command.CommandText =
                    "CREATE TABLE IF NOT EXISTS reports (id INTEGER PRIMARY KEY, class TEXT NULL, method TEXT NULL, timeInMs INTEGER NULL);";
                command.ExecuteNonQuery();
                command.CommandText = "DELETE FROM reports;";
                command.ExecuteNonQuery();
                command.Dispose();
                foreach (var report in reports)
                {
                    using (command = new SQLiteCommand(conn))
                    {
                        command.CommandText = $"INSERT INTO reports (class, method, timeInMs) VALUES (@Param1, @Param2, @Param3);";
                        command.Parameters.AddWithValue("@Param1", report.ClassName);
                        command.Parameters.AddWithValue("@Param2", report.MethodName);
                        command.Parameters.AddWithValue("@Param3", report.Time.TotalMilliseconds);
                        command.ExecuteNonQuery();
                    }
                }

                conn.Close();
            }
        }
Esempio n. 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddSingleton <ISerializedEventRepository, SQLiteEventRepository>(
                _ => new SQLiteEventRepository(SQLiteHelpers.CreateFileDb(Paths.LibraryDbPath)));

            services.AddTransient <IClock, Clock>();

            services.AddTransient <LibraryItemEventFactory>();
        }
        private static List <Data> RetrieveData(StatisticalTableOptions options)
        {
            var         metric = GetMetric(options.Metric);
            List <Data> data   = new List <Data>();

            using (var connection = SQLiteHelpers.CreateConnection(options.DatabaseFile))
            {
                connection.Open();
                var secondaries = string.Join(",", options.Secondaries);
                //string cText = $"SELECT {options.Main} as _main, {metric}({options.Value}) as _value, _machine, {secondaries}{GetMainGroup(options)} FROM {GetUnion(options.DatabaseTable)} group by _machine, {options.Main}, {secondaries}";
                string cText =
                    $"SELECT {options.Main} as _main, _value, _machine, {secondaries}{GetMainGroup(options)} FROM {GetUnion(options.DatabaseTable, options.Main, secondaries, metric, options.Value)}";

                if (options.Verbose)
                {
                    Console.WriteLine("Command Text: " + cText);
                }
                using (var command = new SQLiteCommand(connection)
                {
                    CommandText = cText
                })
                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var d = new Data
                            {
                                Main        = TypeHelpers.GetAsString(reader["_main"]),
                                Value       = TypeHelpers.GetAsDouble(reader["_value"]),
                                Secondaries = options.Secondaries.Select(name => TypeHelpers.GetAsInt(reader[name]))
                                              .ToArray(),
                                Machine = TypeHelpers.GetAsInt(reader["_machine"])
                            };
                            if (!string.IsNullOrEmpty(options.MainGroup))
                            {
                                d.MainGroup = TypeHelpers.GetAsString(reader[options.MainGroup]);
                            }

                            data.Add(d);
                        }

                        reader.Close();
                    }

                connection.Close();
            }

            return(data);
        }
Esempio n. 9
0
 public bool InitREDatabase(int epsgCode, ProjectLoadingView loadingForm, out string errorMsg)
 {
     errorMsg = "";
     if (string.IsNullOrEmpty(_databaseName))
     {
         errorMsg = "没有设置数据库!";
         return false;
     }
     _epsgCode = epsgCode;
     FileInfo info = new FileInfo(_databaseName);
     if (!info.Exists)
     {
         loadingForm.ShowProgress(60,"创建数据库");
         System.IO.FileInfo tmpFileInfo = SQLiteHelpers.GetTemplateDBInfo();
         tmpFileInfo.CopyTo(_databaseName);
     }
     using (SQLiteConnection connection =
         new SQLiteConnection(SQLiteHelpers.ConnectionStringBuilder(_databaseName)))
     {
         connection.Open();
         SpatialiteSharp.SpatialiteLoader.Load(connection);
         loadingForm.ShowProgress(70, "创建系统表");
         CreateRESystemTables(connection);
         loadingForm.ShowProgress(70, "创建数据字典");
         ImportDictionary(connection);
         loadingForm.ShowProgress(80, "创建地籍表");
         CreateREZDTables(connection);
         loadingForm.ShowProgress(90, "创建居民地底图表");
         CreateREBasemapTables(connection,"JMD");
         loadingForm.ShowProgress(92, "创建道路底图表");
         CreateREBasemapTables(connection, "DL");
         loadingForm.ShowProgress(93, "创建水系底图表");
         CreateREBasemapTables(connection, "SX");
         loadingForm.ShowProgress(94, "创建地貌底图表");
         CreateREBasemapTables(connection, "DMTZ");
         loadingForm.ShowProgress(95, "创建独立地物底图表");
         CreateREBasemapTables(connection, "DLDW");
         loadingForm.ShowProgress(96, "创建其他底图表");
         CreateREBasemapTables(connection, "QT");
         loadingForm.ShowProgress(97, "创建注记底图表");
         CreateREBasemapTables(connection, "ZJ",true,true,false,true);
         loadingForm.ShowProgress(90, "创建临时表");
         CreateRECADTempTables(connection);
     }
     return true;
 }
Esempio n. 10
0
        public IntegrationTests_NormalClock()
        {
            _factory = new WebApplicationFactory <Startup>().WithWebHostBuilder(builder => {
                builder.ConfigureTestServices(services => {
                    services.AddSingleton <ISerializedEventRepository, SQLiteEventRepository>(
                        _ => new SQLiteEventRepository(SQLiteHelpers.CreateInMemoryDb()));
                });
            });

            ServiceCollection services = new ServiceCollection();

            services.AddSingleton <HttpClient>((_) => _factory.CreateClient());
            services.AddSingleton <ILogger>((_) => Logger.None);
            services.AddSingleton <ServerCaller>();

            _serviceProvider = services.BuildServiceProvider();

            _serverCaller = _serviceProvider.GetService <ServerCaller>();
        }
Esempio n. 11
0
        public void UpdateNoteTags_NoteHasTags_AddingNewANDExistingTag()
        {
            var options = SQLiteHelpers.CreateOptions();

            using (var context = new NexusContext(options))
            {
                context.Database.EnsureCreated();

                context.Notes.Add(DataProvider.CreateNote().AssignNoteTags(DataProvider.GetAlphabeticalTags()));
                context.Tags.Add(new Tag()
                {
                    Title = "D"
                });
                context.SaveChanges();
            }

            using (var context = new NexusContext(options))
            {
                var repo = new NoteRepository(context);
                var note = repo.GetAll().First();

                repo.UpdateNoteTags(note.Id, new List <string>()
                {
                    "A", "B", "X", "D"
                });
                repo.UnitOfWork.SaveChanges();
            }

            using (var context = new NexusContext(options))
            {
                var note = context.Notes.Include(n => n.NoteTags).ThenInclude(nt => nt.Tag).First();

                Assert.True(note.NoteTags.Count == 4);

                Assert.Contains(note.NoteTags, nt => nt.Tag.Title == "A");
                Assert.Contains(note.NoteTags, nt => nt.Tag.Title == "B");
                Assert.Contains(note.NoteTags, nt => nt.Tag.Title == "X");
                Assert.Contains(note.NoteTags, nt => nt.Tag.Title == "D");

                int totalTagCount = context.Tags.Count();
                Assert.True(totalTagCount == 5);
            }
        }
Esempio n. 12
0
        public List<IObjectClass> GetClasses(bool IsRecursion = true)
        {
            List<IObjectClass> _datasets = new List<IObjectClass>();


            string connectionString = SQLiteHelpers.ConnectionStringBuilder(_databaseName);
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                connection.Open();
                using (SQLiteCommand command =
                    new SQLiteCommand(
                        "select MC,ZWMC,DXLX,XHZDMC,TXZDMC,TXLX,FBMC from vg_objectclasses Order by ParentName",
                        connection))
                {
                    using (SQLiteDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            IObjectClass objectClass = new ObjectClass(reader);
                            objectClass.DatabaseName = _databaseName;
                            _datasets.Add(objectClass);
                        }
                    }
                }
            }
            if (IsRecursion == false)
                return _datasets;
            else
            {
                List<IObjectClass> list = _datasets.FindAll(c => c.ParentName == "");
                List<IObjectClass> newList = new List<IObjectClass>(list);
                foreach (IObjectClass objectClass in newList)
                {
                    List<IObjectClass> children = FindChildClasses(_datasets, objectClass.Name);
                    if (children != null && children.Count > 0)
                    {
                        objectClass.SubClasses = children;
                    }
                }
                return newList;
            }
        }
        public override int ExecuteCommand(SqlPlotToolsHackOptions options)
        {
            var input = FileService.ReadLinesLazily(options.InputFile);

            using (var connection = SQLiteHelpers.CreateConnection(options.DatabaseFile))
            {
                connection.Open();
                foreach (var block in GetBlocks(input.Where(IsResultLine).Select(GetValue), blockSize: 1000))
                {
                    using (var command = new SQLiteCommand(connection))
                    {
                        command.CommandText = $"INSERT INTO {options.DatabaseTable} VALUES {block};";
                        command.ExecuteNonQuery();
                    }
                }

                connection.Close();
            }
            return(0);
        }
Esempio n. 14
0
        private static List <Data> RetrieveData(TestOptions options)
        {
            var data = new List <Data>();

            using (var connection = SQLiteHelpers.CreateConnection(options.DatabaseFile))
            {
                connection.Open();
                string cText = $"SELECT s, a, average, _machine FROM {GetUnion(options)}";
                if (options.Verbose)
                {
                    Console.WriteLine("Command Text: " + cText);
                }
                using (var command = new SQLiteCommand(connection)
                {
                    CommandText = cText
                })
                    using (var reader = command.ExecuteReader())
                    {
                        var getMachine = GetMachine(options);
                        while (reader.Read())
                        {
                            var d = new Data
                            {
                                Sorter    = TypeHelpers.GetAsString(reader["s"]),
                                ArraySize = TypeHelpers.GetAsInt(reader["a"]),
                                Average   = TypeHelpers.GetAsDouble(reader["average"]),
                                Machine   = getMachine(TypeHelpers.GetAsInt(reader["_machine"]))
                            };
                            data.Add(d);
                        }

                        reader.Close();
                    }

                connection.Close();
            }

            return(data);
        }
        private List <Data> RetrieveData(StatisticalFunctionsOptions options)
        {
            List <Data> data = new List <Data>();

            Log.Info($"Reading data from '{options.DatabaseFile}'");
            using (var connection = SQLiteHelpers.CreateConnection(options.DatabaseFile))
            {
                connection.Open();
                var groups = string.Join(",", options.Groups);
                foreach (var table in options.DatabaseTable)
                {
                    var commandText = $"SELECT {options.Value} as _value, {groups} FROM {table}";
                    Log.Info($"Executing command '{commandText}'");
                    using (var command = new SQLiteCommand(connection)
                    {
                        CommandText = commandText
                    })
                        using (var reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                data.Add(new Data
                                {
                                    Value  = TypeHelpers.GetAsDouble(reader["_value"]),
                                    Groups = options.Groups.Select(g => TypeHelpers.GetAsString(reader[g])).ToArray()
                                });
                            }

                            reader.Close();
                        }
                }

                Log.Info("Closing Database");
                connection.Close();
            }

            return(data);
        }
Esempio n. 16
0
        public void UpdateNoteTags_ModifyingExistingNoteTagsByAddingAndRemovingTags()
        {
            var options = SQLiteHelpers.CreateOptions();

            // SEEDING
            using (var context = new NexusContext(options))
            {
                context.Database.EnsureCreated(); // Creates the in-memory SQLite database

                var note = DataProvider.CreateNote().AssignNoteTags(DataProvider.GetAlphabeticalTags());
                context.Notes.Add(note);

                context.SaveChanges();
            }

            using (var context = new NexusContext(options))
            {
                var repo = new NoteRepository(context);

                // Adding D, removing C
                repo.UpdateNoteTags(1, new [] { "A", "B", "D" });
                repo.UnitOfWork.SaveChanges();
            }

            using (var context = new NexusContext(options))
            {
                var note = context.Notes.Include(n => n.NoteTags).ThenInclude(nt => nt.Tag).First();

                var tagTitles = note.NoteTags.Select(nt => nt.Tag.Title).ToList();


                Assert.Contains("A", tagTitles);
                Assert.Contains("B", tagTitles);
                Assert.Contains("D", tagTitles);

                Assert.DoesNotContain("C", tagTitles);
            }
        }
Esempio n. 17
0
        public void UpdateNoteTags_NoteHasTags_GivenTheSameNoteTagsToUpdateNotesTags()
        {
            var options = SQLiteHelpers.CreateOptions();

            using (var context = new NexusContext(options))
            {
                context.Database.EnsureCreated();

                var note = DataProvider.CreateNote();
                var tags = DataProvider.GetAlphabeticalTags();
                note.AssignNoteTags(tags);

                context.Notes.Add(note);
                context.SaveChanges();
            }

            using (var context = new NexusContext(options))
            {
                var noteRepo = new NoteRepository(context);

                var note = noteRepo.GetAll().Single();

                noteRepo.UpdateNoteTags(note.Id, DataProvider.GetAlphabeticalTags().Select(t => t.Title));
                noteRepo.UnitOfWork.SaveChanges();
            }

            using (var context = new NexusContext(options))
            {
                var note = context.Notes.Include(n => n.NoteTags).ThenInclude(nt => nt.Tag).First();

                Assert.Equal(3, note.NoteTags.Count);

                Assert.Contains(note.NoteTags, nt => nt.Tag.Title == "A");
                Assert.Contains(note.NoteTags, nt => nt.Tag.Title == "B");
                Assert.Contains(note.NoteTags, nt => nt.Tag.Title == "C");
            }
        }
Esempio n. 18
0
 public SqliteTests()
 {
     _conn = SQLiteHelpers.CreateInMemoryDb();
     _conn.CreateEventsTableIfNotExists();
 }
        public int ExecuteCommand(StatisticalFunctionsOptions options)
        {
            Log = new VerboseLogger(options);
            List <Data> data;

            try
            {
                data = RetrieveData(options);
            }
            catch (Exception exc)
            {
                Log.Error(exc, "Error while reading data from database");
                return(-1);
            }

            if (data == null || data.Count == 0)
            {
                Log.Error($"No data found in table {options.DatabaseTable}");
                return(1);
            }

            var funcs = options.Functions.ToArray();

            var results = new string[funcs.Length];

            Data[][] res = new Data[funcs.Length][];

            for (int i = 0; i < funcs.Length; i += 1)
            {
                switch (funcs[i])
                {
                case "average":
                    Log.Info("Calculating average");
                    res[i] = Calculate(data, d => d.Average(x => x.Value));
                    break;

                case "median":
                    Log.Info("Calculating median");
                    res[i] = Calculate(data, CalculateMedian);
                    break;

                case "variance":
                    Log.Info("Calculating variance");
                    res[i] = Calculate(data, CalculateVariance);
                    break;
                }
            }

            Log.Info($"Opening {options.DatabaseFile}");
            using (var connection = SQLiteHelpers.CreateConnection(options.DatabaseFile))
            {
                connection.Open();
                var command = new SQLiteCommand(connection)
                {
                    CommandText =
                        $"CREATE TABLE IF NOT EXISTS {options.DatabaseTableOut} ({GetColumns(options.Groups, "TEXT")}, {GetColumns(funcs, "REAL")});"
                };
                Log.Info($"Executing Command: {command.CommandText}");
                command.ExecuteNonQuery();

                List <string> valuesList = new List <string>();

                foreach (var d in res[0])
                {
                    var groups = string.Join(",", d.Groups.Select(g => $"'{g}'"));
                    var values = string.Join(",", FindValues(d, res));
                    valuesList.Add($"({groups}, {values})");
                }

                command.CommandText = $"INSERT INTO {options.DatabaseTableOut} VALUES {string.Join(",", valuesList)};";
                Log.Info($"Inserting Values into: {options.DatabaseTableOut}");
                command.ExecuteNonQuery();

                command.Dispose();
                Log.Info("Closing Database");
                connection.Close();
            }

            return(0);
        }