Exemplo n.º 1
0
        ///
        /// <param name="description">Description of dataset from module 1</param>
        public ICollectionDescription RepackToCollectionDescription(IDescription description)
        {
            int     id      = description.ID;
            Dataset dataset = description.Dataset;

            logger.LogNewInfo(string.Format("Repacking description with dataset {0} and id {1} to Collection description.", dataset, id));
            List <IModule2Property> properties       = new List <IModule2Property>();
            List <SignalCode>       processedSignals = new List <SignalCode>();

            foreach (IModule1Property property in description.Properties)
            {
                if (processedSignals.Contains(property.Code))
                {
                    logger.LogNewWarning("Two signals of the same type in one description");
                    throw new ArgumentException("ERROR Two signals of the same type in one description");
                }
                if (DatasetRepository.GetDataset(property.Code) != dataset)
                {
                    logger.LogNewWarning(string.Format("Received dataset {0} does not match dataset for signal {1}", dataset, property.Code));
                    throw new ArgumentException("Data set does not match signal.");
                }

                processedSignals.Add(property.Code);
                properties.Add(RepackToModule2Property(property));
            }

            HistoricalCollection  historicalCollection = new HistoricalCollection(properties);
            CollectionDescription repackedData         = new CollectionDescription(id, dataset, historicalCollection);

            logger.LogNewInfo("Data repacked to collection description successfully");
            return(repackedData);
        }
Exemplo n.º 2
0
        /// 
        /// <param name="property">Module2Property to be written</param>
        /// <param name="timestamp">Time when data arrived to module</param>
        public void WriteProperty(IModule2Property property)
        {
            logger.LogNewInfo("Writing new property to database.");
            Dataset set = DatasetRepository.GetDataset(property.Code);
            string tableName = DatabaseTableNamesRepository.GetTableNameByDataset(set);

            string signalCode = property.Code.ToString();
            double value = property.Value;
            string query = @"INSERT INTO " + tableName + "(signalCode, signalValue) VALUES (@code, @value)";

            using (SQLiteCommand command = new SQLiteCommand(query, databaseConnection))
            {
                command.Parameters.AddWithValue("@code", signalCode);
                command.Parameters.AddWithValue("@value", value);

                if (command.ExecuteNonQuery() == 0)
                {
                    logger.LogNewWarning("Could not write to database.");
                }
                else
                {
                    logger.LogNewInfo("Property written successfully.");
                }
            }
                
        }
        public async Task AddDataset()
        {
            try
            {
                _context.Database.EnsureCreated();

                var repository = new DatasetRepository(_context);
                await repository.AddDatasetAsync("dataset name", new List <string>() { "1 0", "1 2" });

                Assert.Equal(1, _context.Datasets.Count());
                Assert.Equal(2, _context.Datasets.Select(c => c.Friendships).Single().Count());
                Assert.Equal("dataset name", _context.Datasets.Single().Name);
                var data = new Tuple <string, string>[] {
                    new Tuple <string, string>("1", "0"),
                    new Tuple <string, string>("1", "2")
                };
                Assert.Equal(
                    data,
                    _context
                    .Datasets
                    .Select(c => c.Friendships)
                    .Single()
                    .Select(c => new Tuple <string, string>(c.UserOne, c.UserTwo))
                    .ToArray()
                    );
            }
            finally
            {
                _context.Database.EnsureDeleted();
            }
        }
        ///
        /// <param name="property">Module 1 property</param>
        public void WriteProperty(IModule1Property property)
        {
            logger.LogNewInfo(string.Format("Trying to write property with signal code {0} and value {1} to database", property.Code, property.Module1Value));
            Dataset set       = DatasetRepository.GetDataset(property.Code);
            string  tableName = DatabaseTableNamesRepository.GetTableNameByDataset(set);

            string signalCode = property.Code.ToString();
            double value      = property.Module1Value;
            string query      = @"DELETE FROM " + tableName + " WHERE signalCode=@codeToDelete; INSERT INTO " + tableName + " (signalCode, signalValue) VALUES(@codeToInsert, @value)";

            using (SQLiteCommand command = new SQLiteCommand(query, databaseConnection))
            {
                command.Parameters.AddWithValue("@codeToDelete", signalCode);
                command.Parameters.AddWithValue("@codeToInsert", signalCode);
                command.Parameters.AddWithValue("@value", value);

                if (command.ExecuteNonQuery() == 0)
                {
                    logger.LogNewWarning("Could not write to database.");
                }
                else
                {
                    logger.LogNewInfo("Property written successfully.");
                }
            }
        }
Exemplo n.º 5
0
 public DatasetsController()
 {
     db = new ApplicationDbContext();
     datasetRepository        = new DatasetRepository(db);
     discretizationRepository = new DiscretizationRepository(db);
     datasetService           = new DatasetService(datasetRepository);
     securityService          = new SecurityService(datasetRepository, db);
     id = datasetRepository.GetNextId();
 }
Exemplo n.º 6
0
 public KarmaLegoController()
 {
     db = new ApplicationDbContext();
     datasetRepository     = new DatasetRepository(db);
     klRepository          = new KLRepository(db);
     discretizationService = new DiscretizationService();
     karmaLegoService      = new KarmaLegoService();
     datasetService        = new DatasetService(datasetRepository);
     securityService       = new SecurityService(datasetRepository, db);
 }
        /// <summary>
        /// Creates the initial dbcontext, services and repositories
        /// </summary>
        /// <param name="dbName">Database name for the in memory database</param>
        /// <returns>DbContext, Userservice, UserRepository, DatasetRepository, DatasetService</returns>
        private static (DataContext, UserService, UserRepository, DatasetRepository, DatasetService) InitDb(string dbName)
        {
            DataContext    dbContext   = new DataContext(DataContextFactory.GetInMemoryDb(dbName));
            UserRepository userRep     = new UserRepository(dbContext);
            UserService    userService = new UserService(userRep);

            DatasetRepository datasetRepository = new DatasetRepository(dbContext);
            DatasetService    datasetService    = new DatasetService(datasetRepository);

            return(dbContext, userService, userRep, datasetRepository, datasetService);
        }
Exemplo n.º 8
0
        public DatasetTests()
        {
            var dbOptions = new DbContextOptionsBuilder <SocNetContext>().UseSqlite("Data Source=tests.db").Options;

            this.db = new SocNetContext(dbOptions);
            this.db.Database.EnsureCreated();

            var repository = new DatasetRepository(this.db, new DbConfiguration());

            this.datasetService = new DatasetService(repository);
        }
Exemplo n.º 9
0
        /// 
        /// <param name="periodStart">Beginning of the search period</param>
        /// <param name="periodEnd">End of the search period</param>
        public List<IModule2Property> ReadPropertiesByTimeframe(DateTime periodStart, DateTime periodEnd, SignalCode code)
        {
            List<IModule2Property> returnList = new List<IModule2Property>();
            logger.LogNewInfo(string.Format("Reading properties for code {0} with starting date {1}, end date {2}", code, periodEnd, periodEnd));
            Dataset set = DatasetRepository.GetDataset(code);
            string tableName = DatabaseTableNamesRepository.GetTableNameByDataset(set);

            string signalCode = code.ToString();
            string dateStart= periodStart.ToUniversalTime().ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ss");
            string dateEnd = periodEnd.ToUniversalTime().ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ss");
            string query = @"SELECT signalCode, signalValue FROM " + tableName + " WHERE signalCode=@code AND " + 
                            "strftime('%s', timestamp) BETWEEN strftime('%s', @startDate) AND strftime('%s', @endDate) " + 
                            "ORDER BY timestamp DESC ";

            using (SQLiteCommand command = new SQLiteCommand(query, databaseConnection))
            {
                command.Parameters.AddWithValue("@code", signalCode);
                command.Parameters.AddWithValue("@startDate", dateStart);
                command.Parameters.AddWithValue("@endDate", dateEnd);
                try
                {
                    SQLiteDataReader reader = command.ExecuteReader();

                    while (reader.Read())
                    {
                        string retrievedSignal = reader["signalCode"].ToString();
                        string value = reader["signalValue"].ToString();
                    
                        SignalCode retrievedCode = (SignalCode)Enum.Parse(typeof(SignalCode), retrievedSignal);
                        double valueRetrieved = double.Parse(value);
                        Module2Property property = new Module2Property(retrievedCode, valueRetrieved);
                        returnList.Add(property);
                    }

                }
                catch (Exception ex)
                {
                    logger.LogNewWarning(string.Format("ERROR occured reading database. MESSAGE: {0}", ex.Message));
                    return returnList;
                }
            }
            logger.LogNewInfo(string.Format("Found {0} properties within the requested timeframe", returnList.Count));   
            return returnList;

        }
Exemplo n.º 10
0
        public void AddOrReplaceProperty(IModule1Property property)
        {
            logger.LogNewInfo("Trying to replace property in list description.");
            Dataset      dataset = DatasetRepository.GetDataset(property.Code);
            IDescription description;

            if (DoesDescriptionExist(dataset))
            {
                description = GetDescriptionByDataset(dataset);
            }
            else
            {
                description = new Description(dataset, logger);
            }

            description.AddOrReplaceProperty(property);
            AddOrReplaceDescription(description);
        }
Exemplo n.º 11
0
        ///
        /// <param name="value">Signal value</param>
        /// <param name="signalCode">Code for given signal</param>
        public bool UpdateDataset(double value, SignalCode signalCode)
        {
            logging.LogNewInfo(string.Format("Update dataset called for signal {0} and value {1}", signalCode, value));
            Dataset          dataset  = DatasetRepository.GetDataset(signalCode);
            IModule1Property property = dataAdapter.PackToModule1Property(signalCode, value);

            listDescription.AddOrReplaceProperty(property);

            if (listDescription.IsDatasetFull(dataset))
            {
                logging.LogNewInfo(string.Format("Dataset {0} is full, sending the whole list to module 2", dataset.ToString()));
                module2Proxy.UpdateDatabase(listDescription);
            }


            logging.LogNewInfo("Calling database manager to write new property..");
            databaseManager.WriteProperty(property);
            return(true);
        }
Exemplo n.º 12
0
        public async Task GetFriendships()
        {
            try
            {
                _context.Database.EnsureCreated();

                var repository = new DatasetRepository(_context);
                await repository.AddDatasetAsync("dataset 1", new List <string>() { "1 0", "1 2" });

                var datasets = await repository.GetDatasetsAsync();

                var friendships = await repository.GetFriendshipsAsync(datasets.Single().Id);

                Assert.Equal(2, friendships.Count());
            }
            finally
            {
                _context.Database.EnsureDeleted();
            }
        }
Exemplo n.º 13
0
        public async Task GetUsersAsync()
        {
            try
            {
                _context.Database.EnsureCreated();

                var repository = new DatasetRepository(_context);
                await repository.AddDatasetAsync("dataset 1", new List <string>() { "1 0", "1 2" });

                var datasets = await repository.GetDatasetsAsync();

                var users = await repository.GetUsersAsync(datasets.Single().Id);

                Assert.Equal(3, users.Count);
                Assert.Equal(new string[] { "0", "1", "2" }, users.Select(c => c.Id).ToArray());
            }
            finally
            {
                _context.Database.EnsureDeleted();
            }
        }
Exemplo n.º 14
0
        /// 
        /// <param name="code">Signal code</param>
        public IModule2Property ReadLastByCode(SignalCode code)
        {
            Dataset set = DatasetRepository.GetDataset(code);
            string tableName = DatabaseTableNamesRepository.GetTableNameByDataset(set);

            string signalCode = code.ToString();
            string query = "SELECT ID, signalCode, signalValue FROM " + tableName +  " WHERE(signalCode=@code) " +
                           "ORDER BY timestamp DESC LIMIT 1";

            using (SQLiteCommand command = new SQLiteCommand(query, databaseConnection))
            {
                command.Parameters.AddWithValue("@code", signalCode);
                try
                {
                    using (SQLiteDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            string retrievedSignal = reader["signalCode"].ToString();
                            string value = reader["signalValue"].ToString();

                            SignalCode retrievedCode = (SignalCode)Enum.Parse(typeof(SignalCode), retrievedSignal);
                            double valueRetrieved = double.Parse(value);
                            Module2Property property = new Module2Property(retrievedCode, valueRetrieved);
                            return property;
                        }

                        return null;
                    }          
                }catch(Exception ex)
                {
                    logger.LogNewWarning(string.Format("ERROR occured reading database. MESSAGE: {0}", ex.Message));
                    return null;
                }
            }
                          
            
                
        }
 public void SetUp()
 {
     _datasetRepository = new DatasetRepository(GraphRepository);
 }
 public DatasetsController()
 {
     _DatasetRepo = new DatasetRepository();
 }