public void Can_Create_Blog_With_Mapper()
        {
            var connectionString = ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString;
            using (var connection = new SqlConnection(connectionString))
            { 
                connection.Open();
                using (var transaction = connection.BeginTransaction())
                { 
                    var metaDataStore = new MetaDataStore();
                    metaDataStore.BuildTableInfoFor<Blog>();
                    var identityMap = new IdentityMap();
                    var hydrater = new EntityHydrater(metaDataStore, identityMap);
                    BlogMapper blogMapper = new BlogMapper(connection, transaction, metaDataStore, hydrater, identityMap);

                    Blog blog = new Blog { Name = "PROMPT", Description = "Módulo 5 - Plataformas e modelos de acesso a dados" };
                    blog = blogMapper.Insert(blog);

                    Assert.IsNotNull(blog);
                    Assert.IsTrue(blog.Id > 0);
                    Assert.AreEqual("PROMPT", blog.Name);
                    Assert.AreEqual("Módulo 5 - Plataformas e modelos de acesso a dados", blog.Description);

                    transaction.Commit();
                }
            }
        }
        public void TestInitializer()
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
            builder.DataSource = @".\SQLEXPRESS";
            builder.IntegratedSecurity = true;
            builder.InitialCatalog = "DBBlogs";
            SqlConnection connection1 = new SqlConnection(builder.ConnectionString);
            connection1.Open();
            _currentTransaction1 = connection1.BeginTransaction();
            SqlConnection connection2 = new SqlConnection(builder.ConnectionString);
            connection2.Open();
            _currentTransaction2 = connection2.BeginTransaction();

            MetaDataStore metaDataStore = new MetaDataStore();
            metaDataStore.BuildTableInfoFor<Blog>();

            var identityMap1 = new IdentityMap();
            var identityMap2 = new IdentityMap();

            _blogMapper1 = new BlogMapper(connection1,
                _currentTransaction1,
                metaDataStore,
                new EntityHydrater(metaDataStore, identityMap1),
                identityMap1);
            _blogMapper2 = new BlogMapper(connection2,
                _currentTransaction2,
                metaDataStore,
                new EntityHydrater(metaDataStore, identityMap2),
                identityMap2);
        }
 public ColumnInfo(MetaDataStore store, string name, Type dotNetType, DbType dbType, PropertyInfo propertyInfo)
     : base(store)
 {
     Name = name;
     DotNetType = dotNetType;
     DbType = dbType;
     PropertyInfo = propertyInfo;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="InitializeProxyAction"/> class.
 /// </summary>
 /// <param name="connection">The connection.</param>
 /// <param name="transaction">The transaction.</param>
 /// <param name="metaDataStore">The meta data store.</param>
 /// <param name="hydrater">The entity hydrater.</param>
 /// <param name="sessionLevelCache">The session level cache.</param>
 public InitializeProxyAction(
     IDbConnection connection,
     IDbTransaction transaction,
     MetaDataStore metaDataStore,
     EntityHydrater hydrater,
     SessionLevelCache sessionLevelCache)
     : base(connection, transaction, metaDataStore, hydrater, sessionLevelCache)
 {
 }
Example #5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ReferenceInfo"/> class.
 /// </summary>
 /// <param name="store">The store.</param>
 /// <param name="name">The name.</param>
 /// <param name="referenceType">Type of the reference.</param>
 /// <param name="propertyInfo">The property info.</param>
 public ReferenceInfo(MetaDataStore store, string name, Type referenceType, PropertyInfo propertyInfo)
     : base(store,
         name,
         store.GetTableInfoFor(referenceType).PrimaryKey.DotNetType,
         store.GetTableInfoFor(referenceType).PrimaryKey.DbType,
         propertyInfo)
 {
     this.referenceType = referenceType;
 }
 protected DatabaseAction(SqlConnection connection, SqlTransaction transaction, MetaDataStore metaDataStore,
                          EntityHydrater hydrater, SessionLevelCache sessionLevelCache)
 {
     Connection = connection;
     Transaction = transaction;
     MetaDataStore = metaDataStore;
     Hydrater = hydrater;
     SessionLevelCache = sessionLevelCache;
 }
        public void Can_FindAll_Blogs_With_Mapper()
        {
            // Prepare
            var connectionString = ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString;
            using (var connection = new SqlConnection(connectionString))
            { 
                connection.Open();
                using (var transaction = connection.BeginTransaction())
                { 
                    var metaDataStore = new MetaDataStore();
                    metaDataStore.BuildTableInfoFor<Blog>();
                    var identityMap = new IdentityMap();
                    var hydrater = new EntityHydrater(metaDataStore, identityMap);
                    BlogMapper blogMapper = new BlogMapper(connection, transaction, metaDataStore, hydrater, identityMap);

                    for (int i = 0; i < 10; i++)
                    {
                        Blog blog = new Blog { Name = "PROMPT " + i, Description = "Módulo " + i + " - Plataformas e modelos de acesso a dados" };
                        blogMapper.Insert(blog);
                    }
                    transaction.Commit();
                }
            }

            // Test with whole new references
            using (var connection = new SqlConnection(connectionString))
            { 
                connection.Open();
                using (var transaction = connection.BeginTransaction())
                { 
                    var metaDataStore = new MetaDataStore();
                    metaDataStore.BuildTableInfoFor<Blog>();
                    var identityMap = new IdentityMap();
                    var hydrater = new EntityHydrater(metaDataStore, identityMap);
                    BlogMapper blogMapper = new BlogMapper(connection, transaction, metaDataStore, hydrater, identityMap);
                    
                    var allBlogs = blogMapper.FindAll();
                    
                    Assert.AreEqual(10, allBlogs.Count());
                    for (int i = 0; i < 10; i++)
                    {
                        int blogi = i;
                        var blog = allBlogs.SingleOrDefault(b => b.Name == "PROMPT " + blogi);
                        Assert.IsNotNull(blog);
                    }

                    transaction.Commit();
                }
            }
        }
Example #8
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Before public void setup() throws java.io.IOException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
            public virtual void Setup()
            {
                FileSystem     = FileSystemRule.get();
                DatabaseLayout = TestDirectory.databaseLayout();
                // doesn't matter which version we pick we are changing it to the wrong one...
                MigrationTestUtils.FindFormatStoreDirectoryForVersion(StandardV2_3.STORE_VERSION, DatabaseLayout.databaseDirectory());
                changeVersionNumber(FileSystem, DatabaseLayout.file(NEOSTORE_FILENAME), Version);
                File      metadataStore = DatabaseLayout.metadataStore();
                PageCache pageCache     = PageCacheRule.getPageCache(FileSystem);

                MetaDataStore.setRecord(pageCache, metadataStore, STORE_VERSION, MetaDataStore.versionStringToLong(Version));
                VersionAwareLogEntryReader <ReadableClosablePositionAwareChannel> logEntryReader = new VersionAwareLogEntryReader <ReadableClosablePositionAwareChannel>();
                LogFiles logFiles = LogFilesBuilder.logFilesBasedOnlyBuilder(DatabaseLayout.databaseDirectory(), FileSystem).build();

                TailScanner = new LogTailScanner(logFiles, logEntryReader, new Monitors());
            }
Example #9
0
        private static void Main(string[] args)
        {
            // Traverse through every single EDS and save a snapshot of it
            //SaveSnapshot();

            // Create dictionary of latest snapshot, argument is a list of relevant EDSs to include
            Dictionary <string, DatabaseMetaChange> databaseMetaChanges = MetaDataStore.GetLatestChanges(SettingsStore.EDSSettings);

            foreach (var databaseMetaChange in databaseMetaChanges.Values)
            {
                Console.WriteLine(databaseMetaChange);
            }

            Console.WriteLine("Done...");
            Console.Read();
        }
Example #10
0
        public TEntity Update <TEntity>(TEntity entity)
        {
            using (var command = CreateCommand())
            {
                var tableInfo = MetaDataStore.GetTableInfoFor <TEntity>();

                command.CommandText = tableInfo.GetUpdateStatement();

                foreach (var parameterInfo in tableInfo.GetParametersForUpdate(entity))
                {
                    command.CreateAndAddInputParameter(parameterInfo.DbType, parameterInfo.Name, parameterInfo.Value);
                }

                command.ExecuteNonQuery();
                return(entity);
            }
        }
Example #11
0
 internal TransactionRecordState(NeoStores neoStores, IntegrityValidator integrityValidator, RecordChangeSet recordChangeSet, long lastCommittedTxWhenTransactionStarted, ResourceLocker locks, RelationshipCreator relationshipCreator, RelationshipDeleter relationshipDeleter, PropertyCreator propertyCreator, PropertyDeleter propertyDeleter)
 {
     this._neoStores              = neoStores;
     this._nodeStore              = neoStores.NodeStore;
     this._relationshipStore      = neoStores.RelationshipStore;
     this._propertyStore          = neoStores.PropertyStore;
     this._relationshipGroupStore = neoStores.RelationshipGroupStore;
     this._metaDataStore          = neoStores.MetaDataStore;
     this._schemaStore            = neoStores.SchemaStore;
     this._integrityValidator     = integrityValidator;
     this._recordChangeSet        = recordChangeSet;
     this._lastCommittedTxWhenTransactionStarted = lastCommittedTxWhenTransactionStarted;
     this._locks = locks;
     this._relationshipCreator = relationshipCreator;
     this._relationshipDeleter = relationshipDeleter;
     this._propertyCreator     = propertyCreator;
     this._propertyDeleter     = propertyDeleter;
 }
Example #12
0
        public TEntity Insert <TEntity>(TEntity entity)
        {
            using (var command = CreateCommand())
            {
                var tableInfo = MetaDataStore.GetTableInfoFor <TEntity>();

                command.CommandText = tableInfo.GetInsertStatement();

                foreach (var parameterInfo in tableInfo.GetParametersForInsert(entity))
                {
                    command.CreateAndAddInputParameter(parameterInfo.DbType, parameterInfo.Name, parameterInfo.Value);
                }

                object id = Convert.ChangeType(command.ExecuteScalar(), tableInfo.PrimaryKey.DotNetType);
                tableInfo.PrimaryKey.PropertyInfo.SetValue(entity, id, null);
                SessionLevelCache.Store(typeof(TEntity), id, entity);
                return(entity);
            }
        }
Example #13
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void updateOrAddNeoStoreFieldsAsPartOfMigration(org.neo4j.io.layout.DatabaseLayout migrationStructure, org.neo4j.io.layout.DatabaseLayout sourceDirectoryStructure, String versionToMigrateTo, org.neo4j.kernel.impl.transaction.log.LogPosition lastClosedTxLogPosition) throws java.io.IOException
        private void UpdateOrAddNeoStoreFieldsAsPartOfMigration(DatabaseLayout migrationStructure, DatabaseLayout sourceDirectoryStructure, string versionToMigrateTo, LogPosition lastClosedTxLogPosition)
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.io.File storeDirNeoStore = sourceDirectoryStructure.metadataStore();
            File storeDirNeoStore = sourceDirectoryStructure.MetadataStore();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.io.File migrationDirNeoStore = migrationStructure.metadataStore();
            File migrationDirNeoStore = migrationStructure.MetadataStore();

            fileOperation(COPY, _fileSystem, sourceDirectoryStructure, migrationStructure, Iterables.iterable(DatabaseFile.METADATA_STORE), true, ExistingTargetStrategy.SKIP);

            MetaDataStore.setRecord(_pageCache, migrationDirNeoStore, MetaDataStore.Position.UPGRADE_TRANSACTION_ID, MetaDataStore.getRecord(_pageCache, storeDirNeoStore, MetaDataStore.Position.LAST_TRANSACTION_ID));
            MetaDataStore.setRecord(_pageCache, migrationDirNeoStore, MetaDataStore.Position.UPGRADE_TIME, DateTimeHelper.CurrentUnixTimeMillis());

            // Store the checksum of the transaction id the upgrade is at right now. Store it both as
            // LAST_TRANSACTION_CHECKSUM and UPGRADE_TRANSACTION_CHECKSUM. Initially the last transaction and the
            // upgrade transaction will be the same, but imagine this scenario:
            //  - legacy store is migrated on instance A at transaction T
            //  - upgraded store is copied, via backup or HA or whatever to instance B
            //  - instance A performs a transaction
            //  - instance B would like to communicate with A where B's last transaction checksum
            //    is verified on A. A, at this point not having logs from pre-migration era, will need to
            //    know the checksum of transaction T to accommodate for this request from B. A will be able
            //    to look up checksums for transactions succeeding T by looking at its transaction logs,
            //    but T needs to be stored in neostore to be accessible. Obviously this scenario is only
            //    problematic as long as we don't migrate and translate old logs.
            TransactionId lastTxInfo = ReadLastTxInformation(migrationStructure);

            MetaDataStore.setRecord(_pageCache, migrationDirNeoStore, MetaDataStore.Position.LAST_TRANSACTION_CHECKSUM, lastTxInfo.Checksum());
            MetaDataStore.setRecord(_pageCache, migrationDirNeoStore, MetaDataStore.Position.UPGRADE_TRANSACTION_CHECKSUM, lastTxInfo.Checksum());
            MetaDataStore.setRecord(_pageCache, migrationDirNeoStore, MetaDataStore.Position.LAST_TRANSACTION_COMMIT_TIMESTAMP, lastTxInfo.CommitTimestamp());
            MetaDataStore.setRecord(_pageCache, migrationDirNeoStore, MetaDataStore.Position.UPGRADE_TRANSACTION_COMMIT_TIMESTAMP, lastTxInfo.CommitTimestamp());

            // add LAST_CLOSED_TRANSACTION_LOG_VERSION and LAST_CLOSED_TRANSACTION_LOG_BYTE_OFFSET to the migrated
            // NeoStore
            MetaDataStore.setRecord(_pageCache, migrationDirNeoStore, MetaDataStore.Position.LAST_CLOSED_TRANSACTION_LOG_VERSION, lastClosedTxLogPosition.LogVersion);
            MetaDataStore.setRecord(_pageCache, migrationDirNeoStore, MetaDataStore.Position.LAST_CLOSED_TRANSACTION_LOG_BYTE_OFFSET, lastClosedTxLogPosition.ByteOffset);

            // Upgrade version in NeoStore
            MetaDataStore.setRecord(_pageCache, migrationDirNeoStore, MetaDataStore.Position.STORE_VERSION, MetaDataStore.versionStringToLong(versionToMigrateTo));
        }
Example #14
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void transactionsStartedBeforeAConstraintWasCreatedAreDisallowed()
		 public virtual void TransactionsStartedBeforeAConstraintWasCreatedAreDisallowed()
		 {
			  // Given
			  NeoStores store = mock( typeof( NeoStores ) );
			  MetaDataStore metaDataStore = mock( typeof( MetaDataStore ) );
			  when( store.MetaDataStore ).thenReturn( metaDataStore );
			  IndexingService indexes = mock( typeof( IndexingService ) );
			  when( metaDataStore.LatestConstraintIntroducingTx ).thenReturn( 10L );
			  IntegrityValidator validator = new IntegrityValidator( store, indexes );

			  // When
			  try
			  {
					validator.ValidateTransactionStartKnowledge( 1 );
					fail( "Should have thrown integrity error." );
			  }
			  catch ( Exception )
			  {
					// good
			  }
		 }
Example #15
0
        public TEntity Get <TEntity>(object id)
        {
            var cachedEntity = SessionLevelCache.TryToFind(typeof(TEntity), id);

            if (cachedEntity != null)
            {
                return((TEntity)cachedEntity);
            }

            using (var command = CreateCommand())
            {
                var tableInfo = MetaDataStore.GetTableInfoFor <TEntity>();

                var query = tableInfo.GetSelectStatementForAllFields();
                tableInfo.AddWhereByIdClause(query);

                command.CommandText = query.ToString();
                command.CreateAndAddInputParameter(tableInfo.PrimaryKey.DbType, tableInfo.GetPrimaryKeyParameterName(), id);
                return(Hydrater.HydrateEntity <TEntity>(command));
            }
        }
Example #16
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void migrate(org.neo4j.io.layout.DatabaseLayout directoryLayout, org.neo4j.io.layout.DatabaseLayout migrationLayout, org.neo4j.kernel.impl.util.monitoring.ProgressReporter progressMonitor, String versionToMigrateFrom, String versionToMigrateTo) throws java.io.IOException
		 public override void Migrate( DatabaseLayout directoryLayout, DatabaseLayout migrationLayout, ProgressReporter progressMonitor, string versionToMigrateFrom, string versionToMigrateTo )
		 {
			  if ( CountStoreRebuildRequired( versionToMigrateFrom ) )
			  {
					// create counters from scratch
					fileOperation( DELETE, _fileSystem, migrationLayout, migrationLayout, _countsStoreFiles, true, null );
					File neoStore = directoryLayout.MetadataStore();
					long lastTxId = MetaDataStore.getRecord( _pageCache, neoStore, MetaDataStore.Position.LAST_TRANSACTION_ID );
					try
					{
						 RebuildCountsFromScratch( directoryLayout, migrationLayout, lastTxId, progressMonitor, versionToMigrateTo, _pageCache, NullLogProvider.Instance );
					}
					catch ( StoreFailureException )
					{
						 //This means that we did not perform a full migration, as the formats had the same capabilities. Thus
						 // we should use the store directory for information when rebuilding the count store. Note that we
						 // still put the new count store in the migration directory.
						 RebuildCountsFromScratch( directoryLayout, migrationLayout, lastTxId, progressMonitor, versionToMigrateFrom, _pageCache, NullLogProvider.Instance );
					}
					_migrated = true;
			  }
		 }
Example #17
0
        /// <summary>
        /// Initiate static objects
        /// </summary>
        static Program()
        {
            // If debugger attached, then locate folders in solution folder.
            if (System.Diagnostics.Debugger.IsAttached)
            {
                ProjectPathFolder = Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory()));
                TestDataFolder    = Path.GetFullPath(Path.Combine(ProjectPathFolder, "..\\", "Data"));
                TestOutputFolder  = Path.GetFullPath(Path.Combine(ProjectPathFolder, "..\\", "Output"));
            }
            else // Else locate in same folder as .exe file
            {
                ProjectPathFolder = AppDomain.CurrentDomain.BaseDirectory;
                TestDataFolder    = Path.GetFullPath(Path.Combine(ProjectPathFolder, "Data"));
                TestOutputFolder  = Path.GetFullPath(Path.Combine(ProjectPathFolder, "Output"));
            }

            SettingsStore.Init(
                new JsonSettingsProvider(TestDataFolder),
                new JsonEDSProvider()
                );

            MetaDataStore.Init(new JSONSnapshotProvider());
        }
Example #18
0
            internal virtual BranchedStoreInfo ParseBranchedStore(File branchedDatabase)
            {
                try
                {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.io.File neoStoreFile = org.neo4j.io.layout.DatabaseLayout.of(branchedDatabase).metadataStore();
                    File neoStoreFile = DatabaseLayout.of(branchedDatabase).metadataStore();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final long txId = org.neo4j.kernel.impl.store.MetaDataStore.getRecord(pageCache, neoStoreFile, org.neo4j.kernel.impl.store.MetaDataStore.Position.LAST_TRANSACTION_ID);
                    long txId = MetaDataStore.getRecord(PageCache, neoStoreFile, MetaDataStore.Position.LAST_TRANSACTION_ID);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final long timestamp = long.Parse(branchedDatabase.getName());
                    long timestamp = long.Parse(branchedDatabase.Name);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final long branchedStoreSize = org.neo4j.io.fs.FileUtils.size(fileSystem, branchedDatabase);
                    long branchedStoreSize = FileUtils.size(FileSystem, branchedDatabase);

                    return(new BranchedStoreInfo(branchedDatabase.Name, txId, timestamp, branchedStoreSize));
                }
                catch (IOException e)
                {
                    throw new System.InvalidOperationException("Cannot read branched neostore", e);
                }
            }
Example #19
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public synchronized void close() throws java.io.IOException
        public override void Close()
        {
            lock (this)
            {
                if (_asPartOfStoreCopy)
                {
                    /* A checkpoint which points to the beginning of all the log files, meaning that
                     * all the streamed transactions will be applied as part of recovery. */
                    long        logVersion         = _logFiles.LowestLogVersion;
                    LogPosition checkPointPosition = new LogPosition(logVersion, LOG_HEADER_SIZE);

                    _log.info("Writing checkpoint as part of store copy: " + checkPointPosition);
                    _writer.checkPoint(checkPointPosition);

                    // * comment copied from old StoreCopyClient *
                    // since we just create new log and put checkpoint into it with offset equals to
                    // LOG_HEADER_SIZE we need to update last transaction offset to be equal to this newly defined max
                    // offset otherwise next checkpoint that use last transaction offset will be created for non
                    // existing offset that is in most of the cases bigger than new log size.
                    // Recovery will treat that as last checkpoint and will not try to recover store till new
                    // last closed transaction offset will not overcome old one. Till that happens it will be
                    // impossible for recovery process to restore the store
                    File neoStore = _databaseLayout.metadataStore();
                    MetaDataStore.setRecord(_pageCache, neoStore, LAST_CLOSED_TRANSACTION_LOG_BYTE_OFFSET, checkPointPosition.ByteOffset);
                }

                _lifespan.close();

                if (_lastTxId != -1)
                {
                    File neoStoreFile = _databaseLayout.metadataStore();
                    MetaDataStore.setRecord(_pageCache, neoStoreFile, LAST_TRANSACTION_ID, _lastTxId);
                }
                _stores.close();
            }
        }
Example #20
0
        public static object Extend(this object obj1, params object[] obj2)
        {
            IDictionary <string, object> obj_dict1 = new Dictionary <string, object>();
            var tableInfo1 = MetaDataStore.GetTableInfoFor(obj1.GetType());

            if (typeof(System.Dynamic.IDynamicMetaObjectProvider).IsAssignableFrom(obj1.GetType()))
            {
                // dynamic type
                if (obj1.GetType() == typeof(System.Dynamic.ExpandoObject))
                {
                    obj_dict1 = (IDictionary <string, object>)obj1;
                }
            }
            else if (typeof(IDictionary).IsAssignableFrom(obj1.GetType()))
            {
                // dictionary
                var p = obj1 as IDictionary;
                foreach (var item in p.Keys)
                {
                    obj_dict1.Add(item.ToString(), p[item]);
                }
            }
            else
            {
                foreach (PropertyInfo pi in obj1.GetType().GetProperties())
                {
                    // Check whether the property has any information
                    var key = pi.Name;
                    if (tableInfo1 != null)
                    {
                        var ci = tableInfo1.GetColumn(pi);
                        if (ci != null)
                        {
                            key = ci.Name;
                        }
                    }
                    obj_dict1.Add(key, pi.GetValue(obj1, null) ?? DBNull.Value);
                }
            }

            foreach (var obj in obj2)
            {
                IDictionary <string, object> obj_dict2 = new Dictionary <string, object>();
                var tableInfo2 = MetaDataStore.GetTableInfoFor(obj.GetType());
                if (typeof(System.Dynamic.IDynamicMetaObjectProvider).IsAssignableFrom(obj.GetType()))
                {
                    // dynamic type
                    if (obj.GetType() == typeof(System.Dynamic.ExpandoObject))
                    {
                        obj_dict2 = (IDictionary <string, object>)obj;
                    }
                }
                else if (typeof(IDictionary).IsAssignableFrom(obj.GetType()))
                {
                    // dictionary
                    var p = obj as IDictionary;
                    foreach (var item in p.Keys)
                    {
                        obj_dict2.Add(item.ToString(), p[item]);
                    }
                }
                else
                {
                    foreach (PropertyInfo pi in obj.GetType().GetProperties())
                    {
                        // Check whether the property has any information
                        var key = pi.Name;
                        if (tableInfo2 != null)
                        {
                            var ci = tableInfo2.GetColumn(pi);
                            if (ci != null)
                            {
                                key = ci.Name;
                            }
                        }
                        obj_dict2.Add(key, pi.GetValue(obj, null) ?? DBNull.Value);
                    }
                }
                // merge
                foreach (var key in obj_dict2.Keys)
                {
                    obj_dict1.Add(key, obj_dict2[key]);
                }
            }
            return(obj_dict1);
        }
Example #21
0
 public TableInfo(MetaDataStore store, string name, Type entityType)
     : base(store)
 {
     Name = name;
     EntityType = entityType;
 }
Example #22
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void startTheDatabaseWithWrongVersionShouldFailWithUpgradeNotAllowed() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        internal virtual void StartTheDatabaseWithWrongVersionShouldFailWithUpgradeNotAllowed()
        {
            // given
            // create a store
            File databaseDir        = _testDirectory.databaseDir();
            GraphDatabaseService db = (new TestGraphDatabaseFactory()).newEmbeddedDatabase(databaseDir);

            using (Transaction tx = Db.beginTx())
            {
                Db.createNode();
                tx.Success();
            }
            Db.shutdown();

            // mess up the version in the metadatastore
            using (FileSystemAbstraction fileSystem = new DefaultFileSystemAbstraction(), ThreadPoolJobScheduler scheduler = new ThreadPoolJobScheduler(), PageCache pageCache = createPageCache(fileSystem, scheduler))
            {
                MetaDataStore.setRecord(pageCache, _testDirectory.databaseLayout().metadataStore(), MetaDataStore.Position.STORE_VERSION, MetaDataStore.versionStringToLong("bad"));
            }

            Exception exception = assertThrows(typeof(Exception), () => (new TestGraphDatabaseFactory()).newEmbeddedDatabase(databaseDir));

            assertTrue(exception.InnerException is LifecycleException);
            assertTrue(exception.InnerException.InnerException is System.ArgumentException);
            assertEquals("Unknown store version 'bad'", exception.InnerException.InnerException.Message);
        }
Example #23
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private static long getLastCommittedTx(org.neo4j.io.layout.DatabaseLayout databaseLayout, org.neo4j.io.pagecache.PageCache pageCache) throws java.io.IOException
        private static long GetLastCommittedTx(DatabaseLayout databaseLayout, PageCache pageCache)
        {
            File neoStore = databaseLayout.MetadataStore();

            return(MetaDataStore.getRecord(pageCache, neoStore, MetaDataStore.Position.LAST_TRANSACTION_ID));
        }
Example #24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MetaData"/> class.
 /// </summary>
 /// <param name="metaDataStore">The meta data store.</param>
 protected MetaData(MetaDataStore metaDataStore)
 {
     this.metaDataStore = metaDataStore;
 }
Example #25
0
        static void Main(string[] args)
        {
            string testDTSX = "LargeExample.dtsx";

            string path = Path.Combine(SSISFolder, testDTSX);
            // Traverse through every single EDS and save a snapshot of it
            //foreach (EDSSettings EDS in SettingsStore.EDSSettings.Where(e => e.Name != "Template"))
            //{
            //    MetaDataSnapshot metaDataSnapshot = new MetaDataSnapshot(EDS.ConnectionString);

            //    Console.WriteLine(metaDataSnapshot);

            //    MetaDataStore.Provider.SaveSnapshot(EDS, metaDataSnapshot);
            //}


            // Key = EDS connection string
            Dictionary <string, DatabaseMetaChange> latestChanges = MetaDataStore.GetLatestChanges(SettingsStore.EDSSettings);

            _databaseMetaChange = latestChanges.Values.First();   //TODO: change this later.

            // Print out changes
            Console.WriteLine(_databaseMetaChange);

            // Create a new application to host packages, and load a package within it
            Application application = new Application();
            Package     package     = application.LoadPackage(path, null);

            Graph g = new Graph(application, package, testDTSX, new Options.Options())
            {
                Options = new Options.Options()
            };

            // Print attributes, which is used in graph
            List <Dictionary <string, Attribute> > list = g.AttributeTable.Values.SelectMany(d => d.Values).ToList();
            List <Attribute> attributes = list.SelectMany(d => d.Values).ToList();
            string           s          = string.Join("\n", attributes.Select(a => $"  -{a.Id}/{a.AttributeRef?.ID}: {a.Name}"));

            Console.WriteLine(s);

            // Iterate through all meta changes
            foreach (TableMetaChange tableMetaChange in _databaseMetaChange.Tables.Values)
            {
                foreach (ColumnMetaChange columnMetaChange in tableMetaChange.Columns.Values.Where(c => c.ColumnChanges > 0))
                {
                    foreach (ColumnChanges change in columnMetaChange.ListChanges())
                    {
                        g.Alter(columnMetaChange, change);
                    }
                }
            }

            // Validate package before saving it
            package.Validate(package.Connections, package.Variables, new PackageValidateErrorEvent(), null);

            // Save package
            application.SaveToXml(Path.Combine(TestOutputFolder, "packages", testDTSX), package, null);

            Console.WriteLine("Done");
            Console.ReadKey();
        }
Example #26
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private static long lastTxChecksumOf(org.neo4j.io.layout.DatabaseLayout databaseLayout, org.neo4j.io.pagecache.PageCache pageCache) throws java.io.IOException
        private static long LastTxChecksumOf(DatabaseLayout databaseLayout, PageCache pageCache)
        {
            File neoStore = databaseLayout.MetadataStore();

            return(MetaDataStore.getRecord(pageCache, neoStore, MetaDataStore.Position.LAST_TRANSACTION_CHECKSUM));
        }
Example #27
0
 protected MetaData(MetaDataStore metaDataStore)
 {
     MetaDataStore = metaDataStore;
 }
Example #28
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void startTheDatabaseWithWrongVersionShouldFailAlsoWhenUpgradeIsAllowed() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        internal virtual void StartTheDatabaseWithWrongVersionShouldFailAlsoWhenUpgradeIsAllowed()
        {
            // given
            // create a store
            File databaseDirectory  = _testDirectory.databaseDir();
            GraphDatabaseService db = (new TestGraphDatabaseFactory()).newEmbeddedDatabase(databaseDirectory);

            using (Transaction tx = Db.beginTx())
            {
                Db.createNode();
                tx.Success();
            }
            Db.shutdown();

            // mess up the version in the metadatastore
            string badStoreVersion = "bad";

            using (FileSystemAbstraction fileSystem = new DefaultFileSystemAbstraction(), ThreadPoolJobScheduler scheduler = new ThreadPoolJobScheduler(), PageCache pageCache = createPageCache(fileSystem, scheduler))
            {
                MetaDataStore.setRecord(pageCache, _testDirectory.databaseLayout().metadataStore(), MetaDataStore.Position.STORE_VERSION, MetaDataStore.versionStringToLong(badStoreVersion));
            }

            Exception exception = assertThrows(typeof(Exception), () => (new TestGraphDatabaseFactory()).newEmbeddedDatabaseBuilder(databaseDirectory).setConfig(GraphDatabaseSettings.allow_upgrade, "true").newGraphDatabase());

            assertTrue(exception.InnerException is LifecycleException);
            assertTrue(exception.InnerException.InnerException is StoreUpgrader.UnexpectedUpgradingStoreVersionException);
        }
Example #29
0
 public void Given()
 {
     store = new MetaDataStore(null);
     store.BuildMetaDataFor(this.GetType().Assembly);
 }
 public ColumnInfo(MetaDataStore store, string name, Type dotNetType, PropertyInfo propertyInfo)
     : this(store, name, dotNetType, TypeConverter.ToDbType(dotNetType), propertyInfo)
 {
 }
Example #31
0
 public Query(SqlCommand command, MetaDataStore metaDataStore, EntityHydrater hydrater)
 {
     this.command       = command;
     this.metaDataStore = metaDataStore;
     this.hydrater      = hydrater;
 }
Example #32
0
 protected DatabaseAction(SqlConnection connection, SqlTransaction transaction, MetaDataStore metaDataStore,
                          EntityHydrater hydrater, SessionLevelCache sessionLevelCache)
 {
     Connection        = connection;
     Transaction       = transaction;
     MetaDataStore     = metaDataStore;
     Hydrater          = hydrater;
     SessionLevelCache = sessionLevelCache;
 }
Example #33
0
 public InsertAction(SqlConnection connection, SqlTransaction transaction, MetaDataStore metaDataStore,
                     EntityHydrater hydrater, SessionLevelCache sessionLevelCache)
     : base(connection, transaction, metaDataStore, hydrater, sessionLevelCache)
 {
 }
Example #34
0
 protected MetaData(MetaDataStore metaDataStore)
 {
     MetaDataStore = metaDataStore;
 }