Пример #1
0
        private static void InsertGenesisStudent(FullStudent fullStudent, IDatabaseConnector dbConnector)
        {
            // no record returned, add the genesis block
            // generate previous node hash for genesis student
            // generate genesis student hash, and salthash and combined hash

            BasicStudent genesisStudent = StudentMapper.GenesisStudentNode();

            // SHA512 hash of 512 for the previous for genesisStudent
            string hashForGenesisStudentPrevious = Hash.GetHashString("Test");// Hash.GetBCryptHashAutoSalt("Test");

            string genesisStudentSerialized = JsonConvert.SerializeObject(genesisStudent);
            string genesisStudentHash       = Hash.GetHashString(genesisStudentSerialized);

            Console.WriteLine($"Genesis studnet");
            Console.WriteLine(genesisStudentSerialized);

            string[] genesissaltAndSaltHashArray = Hash.GetRandomSaltWithHash();

            string genesissalt     = genesissaltAndSaltHashArray[0];
            string genesissaltHash = genesissaltAndSaltHashArray[1];

            string genesisstudentHashPlusSaltHash = Hash.GetHashString(genesisStudentHash + genesissaltHash);

            fullStudent = StudentMapper.Map(genesisStudent, hashForGenesisStudentPrevious, genesisstudentHashPlusSaltHash, genesissalt);

            // add the full hash of the previous student

            fullStudent.PreviousFullRecordHash = hashForGenesisStudentPrevious;

            HttpStatusCode genesisrecordInsertedStatusCode = dbConnector.InsertStudentRecord(fullStudent);
        }
Пример #2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CustomQuery{TResultType}"/> class.
 /// </summary>
 /// <param name="connector">The database connector.</param>
 /// <param name="query">The query.</param>
 public CustomQuery(IDatabaseConnector connector, string query)
 {
     this.Connector   = connector;
     this.Descriptor  = DescriptorCache.Instance.GetCustomTypeDescriptor(typeof(TResultType));
     this.CommandText = query;
     this.Mapper      = new DatabaseReaderMapper <TResultType>(connector, this.Descriptor);
 }
Пример #3
0
        private IDatabase GetDatabase(IDatabaseConnector databaseConnector, out IDatabaseLoader databaseLoader, List <SchemaData> tablesToFetch)
        {
            databaseLoader = null;
            _progress.SetCurrentState("Loading Database From Connection String in NHibernate Config File", ProgressState.Normal);

            databaseLoader = DatabaseLoaderFacade.GetDatabaseLoader(databaseConnector);
            databaseLoader.DatabaseObjectsToFetch = tablesToFetch;

            IDatabase database = null;
            bool      success  = false;

            while (success == false)
            {
                try
                {
                    database = databaseLoader.LoadDatabase(databaseLoader.DatabaseObjectsToFetch, null);
                    new DatabaseProcessor().CreateRelationships(database);
                    success = true;
                }
                catch (DatabaseLoaderException e)
                {
                    var loader = _userInteractor.GetDatabaseLoader(databaseConnector);
                    if (loader == null)
                    {
                        throw new NHibernateConfigException("Could not load the database specified in your config file.", e);
                    }
                    databaseLoader = loader;
                    _progress.SetCurrentState("Loading Database From Connection Information Given", ProgressState.Normal);
                }
            }
            return(database);
        }
Пример #4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Query{TResultType}"/> class.
 /// </summary>
 /// <param name="connector">The database connector.</param>
 /// <param name="descriptor">The table type descriptor.</param>
 public Query(IDatabaseConnector connector, ITableTypeDescriptor descriptor)
 {
     this.Connector            = connector;
     this.Descriptor           = descriptor;
     this.SelectCommandBuilder = connector.GetCommandBuilderFactory().CreateSelectCommandBuilder(descriptor);
     this.Mapper = new DatabaseReaderMapper <TResultType>(connector, descriptor);
 }
Пример #5
0
        /// <summary>
        /// Populates the command parameters.
        /// </summary>
        /// <typeparam name="TParameters">The type of the parameters.</typeparam>
        /// <param name="connector">Reference to a database connector.</param>
        /// <param name="command">The command.</param>
        /// <param name="descriptor">The routine type descriptor.</param>
        /// <param name="parameters">The parameters.</param>
        /// <param name="ignoreProperties">The ignore properties.</param>
        /// <exception cref="System.ArgumentNullException">descriptor - descriptor</exception>
        private static void PopulateCommandParameters <TParameters>(IDatabaseConnector connector, IDatabaseCommand command, IRoutineTypeDescriptor descriptor, TParameters parameters, string[] ignoreProperties)
        {
            if (descriptor == null)
            {
                throw new ArgumentNullException(nameof(descriptor), $"{nameof(descriptor)} can not be null.");
            }

            var formatProvider = connector.GetCommandFormatProvider();

            foreach (var parameter in descriptor.Parameters)
            {
                if (ignoreProperties != null && ignoreProperties.Contains(parameter.ParameterName))
                {
                    continue;
                }

                var commandParameter = command.AddParameter(formatProvider.GetParameterName(parameter.ParameterName), DbTypeConverter.FromType(parameter.Type));
                commandParameter.Direction = parameter.IsInput ? ParameterDirection.Input : ParameterDirection.Output;

                if (parameters == null || parameters.Equals(default(TParameters)))
                {
                    continue;
                }

                var value = parameter.PropertyInfo.GetValue(parameters);
                commandParameter.Value = value ?? DBNull.Value;
            }
        }
Пример #6
0
 public TelegramService(IDatabase database, TelegramSettings settings, IMemoryCache cache, IDatabaseConnector <TelegramDatabaseCredentials> databaseConnector)
 {
     _database          = database;
     _settings          = settings;
     _cache             = cache;
     _databaseConnector = databaseConnector;
 }
Пример #7
0
 public override void Execute(CommandPipelineContext context,
                              IDatabaseConnector connector,
                              IEnumerable <ScriptAccessor> scripts)
 {
     // Need to sort scripts out that have run before...
     base.Execute(context, connector, scripts);
 }
Пример #8
0
 /// <summary>
 /// Opens my SQL connection when its closed.
 /// </summary>
 /// <param name="connector">The database connector.</param>
 private static void OpenMySqlConnectionWhenClose(this IDatabaseConnector connector)
 {
     if (!connector.IsOpen())
     {
         connector.Open();
     }
 }
Пример #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StoredProcedureBase{TParameters}"/> class.
        /// </summary>
        /// <param name="serviceProvider">The service provider.</param>
        /// <param name="connector">The database connector.</param>
        private StoredProcedureBase(IServiceProvider serviceProvider, IDatabaseConnector connector)
        {
            this.ServiceProvider = serviceProvider;
            this.Connector       = connector;

            this.Initialize();
        }
Пример #10
0
        public IDatabaseFormFiller GetFormFillerFor(IDatabaseConnector connector)
        {
            if (connector is ISQLServer2005DatabaseConnector)
                return new SQLServer2005DatabaseFormFiller(connector as ISQLServer2005DatabaseConnector);

            if (connector is ISQLCEDatabaseConnector)
                return new SQLServerCEDatabaseFormFiller(connector as ISQLCEDatabaseConnector);

            if (connector is ISQLServerExpressDatabaseConnector)
                return new SQLServerExpressDatabaseFormFiller(connector as ISQLServerExpressDatabaseConnector);

            if (connector is IOracleDatabaseConnector)
                return new OracleDatabaseFormFiller(connector as IOracleDatabaseConnector);

            if (connector is IPostgreSQLDatabaseConnector)
                return new PostgreSQLDatabaseFormFiller(connector as IPostgreSQLDatabaseConnector);

            if (connector is IMySQLDatabaseConnector)
                return new MySQLDatabaseFormFiller(connector as IMySQLDatabaseConnector);

            if (connector is IFirebirdDatabaseConnector)
                return new FirebirdDatabaseFormFiller(connector as IFirebirdDatabaseConnector);

            if (connector is ISQLiteDatabaseConnector)
                return new SQLiteDatabaseFormFiller(connector as ISQLiteDatabaseConnector);

            throw new ArgumentException("DatabaseFormFillerFactory does not support " + connector.GetType() + " connectors yet.");
        }
Пример #11
0
        /// <summary>
        /// Gets called when loading an existing VS project.
        /// </summary>
        /// <param name="connector"></param>
        /// <returns></returns>
        public static IDatabaseLoader GetDatabaseLoader(IDatabaseConnector connector)
        {
            if (connector is ISQLCEDatabaseConnector)
            {
                return(new SQLCEDatabaseLoader(connector as ISQLCEDatabaseConnector));
            }

            if (connector is ISQLServer2005DatabaseConnector)
            {
                return(new SQLServer2005DatabaseLoader(connector as ISQLServer2005DatabaseConnector));
            }

            if (connector is IMySQLDatabaseConnector)
            {
                return(new MySQLDatabaseLoader(connector as IMySQLDatabaseConnector));
            }

            if (connector is IOracleDatabaseConnector)
            {
                return(new OracleDatabaseLoader(connector as IOracleDatabaseConnector));
            }

            if (connector is IPostgreSQLDatabaseConnector)
            {
                return(new PostgreSQLDatabaseLoader(connector as IPostgreSQLDatabaseConnector));
            }

            if (connector is IFirebirdDatabaseConnector)
            {
                return(new FirebirdDatabaseLoader(connector as IFirebirdDatabaseConnector));
            }

            throw new Exception("DatabaseLoaderFacade does not know how to deal with a connector of type " + connector.GetType());
        }
Пример #12
0
 /// <summary>
 /// Opens my SQL connection when close asynchronous.
 /// </summary>
 /// <param name="connector">The database connector.</param>
 /// <returns></returns>
 private static async Task OpenMySqlConnectionWhenCloseAsync(this IDatabaseConnector connector)
 {
     if (!connector.IsOpen())
     {
         await connector.OpenAsync();
     }
 }
Пример #13
0
        public CreateConnection()
        {
            _settings = new DatabaseCommanderSettings(
                new List <DatabaseCommandNamespaceSetting>
            {
                new DatabaseCommandNamespaceSetting(
                    typeof(DatabaseCommandNamespaceSetting).Namespace,
                    new List <DatabaseCommandTypeSetting>
                {
                    new DatabaseCommandTypeSetting(
                        typeof(DatabaseCommandTypeSetting).FullName,
                        new Dictionary <string, DatabaseCommandSetting>
                    {
                        ["Retrieve"] =
                            new DatabaseCommandSetting("test.alias", "select 'Readers.Test.Settings'")
                    })
                })
            }
                , new List <ConnectionStringSetting>
            {
                new ConnectionStringSetting("test.alias", "Data Source=(LocalDb)\\mssqllocaldb;Initial Catalog=master;Integrated Security=true;")
            });

            _connector = new SqlServerDatabaseConnector(_settings);
        }
Пример #14
0
 public static MaterialComboBox CreateStreckenCbItems(IDatabaseConnector db, MaterialComboBox cb)
 {
     cb.DataSource    = db.ZeigeAlleStrecken();
     cb.DisplayMember = "Name";
     cb.ValueMember   = "StreckenID";
     return(cb);
 }
Пример #15
0
        public async Task <IModule> Load(IDatabaseConnector databaseConnector, Cida.Api.IFtpClient ftpClient, Cida.Api.Models.Filesystem.Directory moduleDirectory, IModuleLogger moduleLogger)
        {
            var instance = (IModule)Activator.CreateInstance(this.entryType);
            await instance.Load(databaseConnector, ftpClient, moduleDirectory, moduleLogger);

            return(instance);
        }
        private void setDatabases(IDatabaseConnector dbConnector)
        {
            if (dbConnector != null)
            {
                try
                {
                    databaseNames = dbConnector.GetDatabaseNames();
                }
                catch (SqlException e)
                {
                    databaseNames = new List <string>();
                    MessageBox.Show(e.Message, "SqlException", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
            else
            {
                databaseNames = new List <string>();
            }

            if (databaseNames.Count > 0 && dbConnector.GetDatabaseNames().Contains(selectedDatabase.Name))
            {
                SelectedDatabase = dbConnector.GetDatabase(selectedDatabase.Name);
            }
            else if (databaseNames.Count > 0)
            {
                SelectedDatabase = dbConnector.GetDatabase(databaseNames[0]);
            }
            else
            {
                SelectedDatabase = null;
            }

            NotifyPropertyChanged("DatabaseNames");
        }
Пример #17
0
 public override void Execute(CommandPipelineContext context,
                              IDatabaseConnector connector,
                              IEnumerable <ScriptAccessor> scripts)
 {
     //if (context.Options.Rollback)
     //    base.Execute(context, connector, scripts);
 }
        public DatabaseConnectionViewModel(
            IMessageBoxService messageBoxService,
            IDatabaseConnector dbConnector)
        {
            _messageBoxService = messageBoxService;
            _dbConnector       = dbConnector;

            if (SettingsStore.Instance?.MsSqlDatabaseConnectionSettings != null &&
                !string.IsNullOrWhiteSpace(SettingsStore.Instance.MsSqlDatabaseConnectionSettings.Server))
            {
                Server    = SettingsStore.Instance.MsSqlDatabaseConnectionSettings.Server;
                Database  = SettingsStore.Instance.MsSqlDatabaseConnectionSettings.Database;
                Username  = SettingsStore.Instance.MsSqlDatabaseConnectionSettings.Username;
                Password  = SettingsStore.Instance.MsSqlDatabaseConnectionSettings.Password;
                IsSqlAuth = SettingsStore.Instance.MsSqlDatabaseConnectionSettings.IsSqlAuthSelected;

                RememberConnection = true;
            }
            else
            {
                Server               =
                    Database         =
                        Username     =
                            Password = string.Empty;
                RememberConnection   = false;
            }

            TestConnectionCommand = new AsyncCommand(testConnection, () => IsValid);
        }
Пример #19
0
 /// <summary>
 /// Executes a query and return the results.
 /// </summary>
 /// <typeparam name="TResultType">The result type.</typeparam>
 /// <param name="connector">The database connector.</param>
 /// <param name="whereClause">A where filter clause. Do not add the "WHERE" keyword to it. If you need to pass parameters, pass using @1, @2, @3.</param>
 /// <param name="parameters">A list of parameter values.</param>
 /// <returns>A list of <see cref="TResultType"/></returns>
 /// <seealso cref="Querying.Query{TResultType}"/>
 public static async Task <List <TResultType> > QueryAsync <TResultType>(this IDatabaseConnector connector, string whereClause = null, params object[] parameters) where TResultType : class, new()
 {
     using (var query = new Query <TResultType>(connector))
     {
         return(await query.ExecuteAsync(whereClause, parameters));
     }
 }
Пример #20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ClassValueProvider"/> class.
 /// </summary>
 /// <param name="connector">A reference to a database connector.</param>
 /// <param name="entities">The entities.</param>
 /// <exception cref="ArgumentNullException">entities</exception>
 public ClassValueProvider(IDatabaseConnector connector, List <object> entities)
 {
     this.Connector      = connector ?? throw new ArgumentNullException(nameof(connector));
     this.Entities       = entities ?? throw new ArgumentNullException(nameof(entities));
     this.ValueConverter = this.Connector.GetValueConverter();
     this.CurrentIndex   = -1;
 }
Пример #21
0
            public Validator(IDatabaseConnector <JobDatabaseCredentials> database)
            {
                _database = database;

                RuleFor(x => x.PeerType).IsInEnum();
                RuleFor(x => x).CustomAsync(async(command, context, token) =>
                {
                    int queuedJobs = await _database.ExecuteAsync(conn =>
                    {
                        return(conn.ExecuteScalarAsync <int>($"SELECT COUNT(1) FROM {JobMap.Table} WHERE {JobMap.UserId} = @{JobMap.UserId} AND {JobMap.State} = {(int)JobState.Queued}", new { command.UserId }));
                    });

                    if (queuedJobs >= 5)
                    {
                        context.AddFailure("command", "Unable to queue another job");
                    }

                    bool isAlreadyProccessed = await _database.ExecuteAsync(conn =>
                    {
                        return(conn.ExecuteScalarAsync <bool>($@"
                        SELECT 1 FROM {JobMap.Table}
                        WHERE {JobMap.UserId} = @{JobMap.UserId}
                        AND {JobMap.PeerId} = @{JobMap.PeerId}
                        AND {JobMap.PeerType} = @{JobMap.PeerType}
                        AND {JobMap.State} IN ( {(int)JobState.Queued}, {(int)JobState.Fetching} )", new { command.UserId, command.PeerId, command.PeerType }));
                    });

                    if (isAlreadyProccessed)
                    {
                        context.AddFailure("command", "This peer is in a queue already or is beeing proccessed");
                    }
                });
            }
        public ScaffoldingWizardViewModel(
            IMessageBoxService messageBoxService,
            IDatabaseService dbService,
            IDatabaseConnector dbConnector,
            IScaffoldingService scaffoldingService,
            IReadOnlyCollection <Project> allSolutionProjects)
        {
            _messageBoxService  = messageBoxService;
            _dbService          = dbService;
            _dbConnector        = dbConnector;
            _scaffoldingService = scaffoldingService;

            DatabaseConnectionVM = new DatabaseConnectionViewModel(messageBoxService, dbConnector);
            DatabaseConnectionVM.PropertyChanged += onValidationStateChanged;
            TablesVM = new TablesViewModel(_messageBoxService);
            TablesVM.PropertyChanged       += onValidationStateChanged;
            OutputParamsVM                  = new OutputParamsViewModel(allSolutionProjects);
            OutputParamsVM.PropertyChanged += onValidationStateChanged;

            State = new WizardState(
                () => IsLoading,
                () => CurrentStepNumber,
                () => DatabaseConnectionVM.IsValid,
                () => TablesVM.IsValid,
                () => OutputParamsVM.IsValid
                );

            BackCommand = new Command(goBack);
            NextCommand = new AsyncCommand(goNext);
            OkCommand   = new AsyncCommand(okExecute);
        }
 public override void Execute(CommandPipelineContext context,
     IDatabaseConnector connector,
     IEnumerable<ScriptAccessor> scripts)
 {
     // Need to sort scripts out that have run before...
     base.Execute(context, connector, scripts);
 }
Пример #24
0
        public void Outputs_Nothing()
        {
            IDatabaseConnector connector = MockRepository.GenerateStub <IDatabaseConnector>();
            string             output    = new DatabaseSerialisationScheme().SerialiseConnectionInformation(connector);

            Assert.That(output, Is.Empty);
        }
Пример #25
0
 /// <summary>
 /// Initializes a new instance of the ReaderStoredProcedure.
 /// </summary>
 /// <param name="serviceProvider">The service provider.</param>
 /// <param name="connector">The database connector.</param>
 /// <param name="mapper">The result mapper.</param>
 public ReaderStoredProcedure(
     IServiceProvider serviceProvider,
     IDatabaseConnector connector,
     IDatabaseReaderMapper <TResult> mapper) : base(serviceProvider, connector)
 {
     this.Mapper = mapper;
 }
Пример #26
0
        public ModuleLoaderManager(
            string moduleDirectory,
            IGrpcRegistrar grpcRegistrar,
            Infrastructure.IFtpClient ftpClient,
            CidaContext databaseContext,
            IDatabaseConnector databaseConnector,
            ILogger logger,
            GlobalConfigurationService globalConfigurationService,
            IModuleFtpClientFactory moduleFtpClientFactory,
            IModuleLoggerFactory moduleLoggerFactory,
            IEnumerable <string> unpackedModuleDirectories = null)
        {
            this.moduleDirectory           = moduleDirectory;
            this.unpackedModuleDirectories = unpackedModuleDirectories ?? Array.Empty <string>();
            this.grpcRegistrar             = grpcRegistrar;
            this.ftpClient                  = ftpClient;
            this.databaseContext            = databaseContext;
            this.databaseConnector          = databaseConnector;
            this.logger                     = logger;
            this.globalConfigurationService = globalConfigurationService;
            this.moduleFtpClientFactory     = moduleFtpClientFactory;
            this.moduleLoggerFactory        = moduleLoggerFactory;
            this.modules                    = new ConcurrentDictionary <Guid, CidaModule>();
            this.unpackedModules            = new ConcurrentBag <Guid>();

            if (!Directory.Exists(moduleDirectory))
            {
                Directory.CreateDirectory(moduleDirectory);
            }
        }
Пример #27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CommandBatch"/> class.
 /// </summary>
 /// <param name="connector">The database connector.</param>
 public CommandBatch(IDatabaseConnector connector)
 {
     this.Connector      = connector;
     this.FormatProvider = connector.GetCommandFormatProvider();
     this.Command        = connector.CreateCommand();
     this.Steps          = new List <ICommandBatchStep>();
 }
Пример #28
0
 /// <summary>
 /// Executes a query and return the results.
 /// </summary>
 /// <typeparam name="TResultType">The result type.</typeparam>
 /// <param name="connector">The database connector.</param>
 /// <param name="query">A custom commandText string. The select columns should be mapped to the <see cref="TResultType"/></param>
 /// /// <param name="whereClause">A where filter clause. Do not add the "WHERE" keyword to it. If you need to pass parameters, pass using @1, @2, @3.</param>
 /// <param name="parameters">A list of parameter values.</param>
 /// <returns>A list of <see cref="TResultType"/></returns>
 /// <seealso cref="Querying.CustomQuery{TResultType}"/>
 public static List <TResultType> CustomQuery <TResultType>(this IDatabaseConnector connector, string query, string whereClause = null, params object[] parameters) where TResultType : class, new()
 {
     using (var customQuery = new CustomQuery <TResultType>(connector, query))
     {
         return(customQuery.Execute(whereClause, parameters));
     }
 }
Пример #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StoredProcedureBase{TParameters}"/> class.
 /// </summary>
 /// <param name="serviceProvider">The service provider.</param>
 /// <param name="connector">The database connector.</param>
 protected StoredProcedureBase(IServiceProvider serviceProvider, IDatabaseConnector connector)
 {
     this.ServiceProvider = serviceProvider;
     this.Connector       = connector;
     this.Descriptor      = DescriptorCache.Instance.GetRoutineTypeDescriptor(typeof(TParameters));
     this.FormatProvider  = this.Connector.GetCommandFormatProvider();
 }
 public override void Execute(CommandPipelineContext context,
     IDatabaseConnector connector,
     IEnumerable<ScriptAccessor> scripts)
 {
     //if (context.Options.Rollback)
     //    base.Execute(context, connector, scripts);
 }
 public ChooseDatabaseViewModel(IEventAggregator eventAggregator, IDatabaseManager databaseManager, IDatabaseConnector databaseConnector)
 {
     _databaseConnector = databaseConnector;
     _eventAggregator = eventAggregator;
     _databaseManager = databaseManager;
     AvailableItems = new ObservableCollection<string>(_databaseManager.GetAllPokerTellDatabases());
 }
Пример #32
0
        public IncentiveCampaignEntity Update(IncentiveCampaignEntity incentiveCampaign)
        {
            try
            {
                this.connector           = new DatabaseConnector();
                this.connector.Database  = DbNames.Database.BmbDigital;
                this.connector.Procedure = "spr_digit_upd_refac_campa_incen";

                this.connector.AddParameter("num_campa_incen", incentiveCampaign.Id);
                this.connector.AddParameter("nom_campa_incen", incentiveCampaign.Name);
                this.connector.AddParameter("dat_inici_vigen", incentiveCampaign.StartDate);
                this.connector.AddParameter("dat_final_vigen", incentiveCampaign.EndDate);
                this.connector.AddParameter("ind_ativo", incentiveCampaign.IsActive);
                //this.connector.AddParameter("dat_situa_regis", incentiveCampaign.CreationDate);
                //this.connector.AddParameter("cod_user", incentiveCampaign.UserName);
                this.connector.AddParameter("ind_neces_carta_acord", incentiveCampaign.AgreementLetterNeeded);

                this.connector.ExecuteReader();

                return(incentiveCampaign);
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                this.connector.Dispose();
            }
        }
Пример #33
0
        /// <summary>
        /// Creates a database command and populates the parameter values.
        /// </summary>
        /// <typeparam name="TParameters">The type of a class containing the parameters.</typeparam>
        /// <param name="connector">The database connector.</param>
        /// <param name="commandText">The command text.</param>
        /// <param name="commandType">Type of the command.</param>
        /// <param name="parameters">The parameter type instance.</param>
        /// <param name="ignoreProperties">A list with properties to ignore.</param>
        /// <returns>A database command.</returns>
        public static IDatabaseCommand CreateCommand <TParameters>(this IDatabaseConnector connector, string commandText, CommandType commandType, TParameters parameters, params string[] ignoreProperties)
        {
            var command = connector.CreateCommand(commandText);

            PopulateCommandParameters(connector, command, parameters, ignoreProperties);
            return(command);
        }
Пример #34
0
 public IDbObject AcquireDatabaseSchemaInformation(IDatabaseConnector dbConnector)
 {
     if (null == dbConnector)
     {
         throw new ArgumentNullException("dbConnector","Invalid IDatabaseConnector instance!");
     }
     return dbConnector.GetDatabaseInformation();
 }
        public DBLoadBackgroundWorker(string dbName, IDatabaseConnector dbConnector, ConnectionPageViewModel viewModel)
            : base()
        {
            this.viewModel = viewModel;
            this.dbName = dbName;
            this.dbConnector = dbConnector;

            this.DoWork += DBBackgroundWorker_DoWork;
            this.RunWorkerCompleted += DBBackgroundWorker_RunWorkerCompleted;
        }
Пример #36
0
        public static Database LoadDatabase(IDatabaseConnector connector, List<SchemaData> databaseObjectsToFetch)
        {
            var loader = GetDatabaseLoader(connector);

            Database database = loader.LoadDatabase(databaseObjectsToFetch, null);

            new DatabaseProcessor().CreateRelationships(database);

            return database;
        }
Пример #37
0
        public virtual void Execute(CommandPipelineContext context,
            IDatabaseConnector connector,
            IEnumerable<ScriptAccessor> scripts)
        {
            if (!scripts.Any()) return;
            var step = new Step {Scripts = scripts};

            Logger.InfoFormat("Executing scripts in folder '{0}'...", Folder);
            connector.Apply(step);
            Logger.InfoFormat("Scripts in folder '{0}' executed.", Folder);
        }
Пример #38
0
        public AdminViewModel()
        {
            dbHelper = new DatabaseHelper();
            Users = dbHelper.Get(_offset,UsersPerPage);

            CalcPagination();

            _addUserCommand = new RelayCommand(AddUser);
            _modifyUserCommand = new RelayCommand(ModifyUser);
            _deleteUserCommand = new RelayCommand(DeleteUser);
            _flipLeftCommand = new RelayCommand(FlipLeft);
            _flipRightCommand = new RelayCommand(FlipRight);
        }
Пример #39
0
        /// <summary>
        /// Gets called when loading an existing VS project.
        /// </summary>
        /// <param name="connector"></param>
        /// <returns></returns>
        public static IDatabaseLoader GetDatabaseLoader(IDatabaseConnector connector)
        {
            if (connector is ISQLCEDatabaseConnector)
                return new SQLCEDatabaseLoader(connector as ISQLCEDatabaseConnector);

            if (connector is ISQLServer2005DatabaseConnector)
                return new SQLServer2005DatabaseLoader(connector as ISQLServer2005DatabaseConnector);

            if (connector is IMySQLDatabaseConnector)
                return new MySQLDatabaseLoader(connector as IMySQLDatabaseConnector);

            if (connector is IOracleDatabaseConnector)
                return new OracleDatabaseLoader(connector as IOracleDatabaseConnector);

            if (connector is IPostgreSQLDatabaseConnector)
                return new PostgreSQLDatabaseLoader(connector as IPostgreSQLDatabaseConnector);

            if (connector is IFirebirdDatabaseConnector)
                return new FirebirdDatabaseLoader(connector as IFirebirdDatabaseConnector);

            throw new Exception("DatabaseLoaderFacade does not know how to deal with a connector of type " + connector.GetType());
        }
Пример #40
0
 public void FillFrom(IDatabaseConnector information)
 {
     new DatabaseFormFillerFactory()
         .GetFormFillerFor(information)
         .FillForm(ucDatabaseInformation1);
 }
Пример #41
0
        private IDatabase GetDatabase(IDatabaseConnector databaseConnector, out IDatabaseLoader databaseLoader, List<SchemaData> tablesToFetch)
        {
            databaseLoader = null;
            _progress.SetCurrentState("Loading Database From Connection String in NHibernate Config File", ProgressState.Normal);

            databaseLoader = DatabaseLoaderFacade.GetDatabaseLoader(databaseConnector);
            databaseLoader.DatabaseObjectsToFetch = tablesToFetch;

            IDatabase database = null;
            bool success = false;

            while (success == false)
            {
                try
                {
                    database = databaseLoader.LoadDatabase(databaseLoader.DatabaseObjectsToFetch, null);
                    new DatabaseProcessor().CreateRelationships(database);
                    success = true;
                }
                catch (DatabaseLoaderException e)
                {
                    var loader = _userInteractor.GetDatabaseLoader(databaseConnector);
                    if (loader == null)
                        throw new NHibernateConfigException("Could not load the database specified in your config file.", e);
                    databaseLoader = loader;
                    _progress.SetCurrentState("Loading Database From Connection Information Given", ProgressState.Normal);
                }
            }
            return database;
        }
 public ConnectionsUpdateAvailableEventArgs(IDatabaseConnector databaseConnector, DateTime updateTime)
 {
     DatabaseConnector = databaseConnector;
     UpdateTime = updateTime;
 }
Пример #43
0
 public IDatabaseLoader GetDatabaseLoader(IDatabaseConnector existingInformation)
 {
     return null;
 }
        private void setDatabases(IDatabaseConnector dbConnector)
        {
            if (dbConnector != null)
            {
                try
                {
                    databaseNames = dbConnector.GetDatabaseNames();
                }
                catch (SqlException e)
                {
                    databaseNames = new List<string>();
                    MessageBox.Show(e.Message, "SqlException", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
            else
            {
                databaseNames = new List<string>();
            }

            if (databaseNames.Count > 0 && dbConnector.GetDatabaseNames().Contains(selectedDatabase.Name))
            {
                SelectedDatabase = dbConnector.GetDatabase(selectedDatabase.Name);
            }
            else if (databaseNames.Count > 0)
            {
                SelectedDatabase = dbConnector.GetDatabase(databaseNames[0]);
            }
            else
            {
                SelectedDatabase = null;
            }

            NotifyPropertyChanged("DatabaseNames");
        }
 public string SerialiseConnectionInformation(IDatabaseConnector connector)
 {
     return Serialise(writer => SerialiseConnectionInformationInternal(connector, writer));
 }
 private void SerialiseConnectionInformationInternal(IDatabaseConnector connector, XmlWriter writer)
 {
     if (connector is ISQLServer2005DatabaseConnector)
     {
         new SQLServer2005ConnectorSerialiser().Serialise(connector as ISQLServer2005DatabaseConnector, writer);
     }
     else if (connector is ISQLCEDatabaseConnector)
     {
         new SQLCEConnectorSerialiser().Serialise(connector as ISQLCEDatabaseConnector, writer);
     }
     else if (connector is IMySQLDatabaseConnector)
     {
         new MySQLConnectorSerialiser().Serialise(connector as IMySQLDatabaseConnector, writer);
     }
     else if (connector is IOracleDatabaseConnector)
     {
         new OracleConnectorSerialiser().Serialise(connector as IOracleDatabaseConnector, writer);
     }
     else if (connector is IPostgreSQLDatabaseConnector)
     {
         new PostgreSQLConnectorSerialiser().Serialise(connector as IPostgreSQLDatabaseConnector, writer);
     }
     else if (connector is ISQLServerExpressDatabaseConnector)
     {
         new SQLServerExpressConnectorSerialiser().Serialise(connector as ISQLServerExpressDatabaseConnector, writer);
     }
     else if (connector is IFirebirdDatabaseConnector)
     {
         new FirebirdConnectorSerialiser().Serialise(connector as IFirebirdDatabaseConnector, writer);
     }
     else if (connector is ISQLiteDatabaseConnector)
     {
         new SQLiteConnectorSerialiser().Serialise(connector as ISQLiteDatabaseConnector, writer);
     }
     else
     {
         throw new NotImplementedException("Not coded for yet in SerialiseConnectionInformationInternal(): " + connector.GetType().Name);
     }
 }
Пример #47
0
        public void AttachToModel(IDatabase db)
        {
            if (!Detached) DetachFromModel();

            if (db == null) return;
            Database = db;
            if (db.Loader != null) DatabaseConnector = db.Loader.DatabaseConnector;
            Detached = false;
            SetupForm();
        }
Пример #48
0
 public override void DetachFromModel()
 {
     Database = null;
     DatabaseConnector = null;
     Detached = true;
     SetupForm();
 }
Пример #49
0
        private void RefreshSchema()
        {
            // Note: this is only ok because this method only runs on the UI thread.
            // Two instances of it will not run at once, so this is not a race condition.
            // The moment it can run from another thread, this assumption is false and the
            // code is incorrect.
            if (RefreshingSchema)
                return;

            databaseLock.WaitOne();

            RefreshingSchema = true;
            IDatabaseLoader loader = CreateDatabaseLoader(form);

            // Test connection first
            if (TestConnection(false) == false)
            {
                databaseLock.Set();
                return;
            }

            Thread thread = new Thread(
                () =>
                {
                    try
                    {
                        IDatabase newDb = loader.LoadDatabase(loader.DatabaseObjectsToFetch, null);
                        new DatabaseProcessor().CreateRelationships(newDb);

                        if (Database == null || Database.IsEmpty)
                        {
                            Database = newDb;
                            DatabaseConnector = loader.DatabaseConnector;
                            NewDatabaseCreated.RaiseEvent(this);
                            return;
                        }

                        var result = new DatabaseProcessor().MergeDatabases(Database, newDb);
                        if (result.AnyChanges)
                        {
                            mainPanel.ShowDatabaseRefreshResults(result, Database, newDb);
                            SchemaRefreshed.RaiseEvent(this);
                        }
                        else
                        {
                            form.SetDatabaseOperationResults(new DatabaseOperationResults("Schema Refresh", true, "No schema changes detected."));
                        }
                    }
                    finally
                    {
                        databaseLock.Set();
                        RefreshingSchema = false;
                    }
                });
            thread.Start();
        }
Пример #50
0
        /// <summary>
        /// Get IDbConnection depending on configuration file
        /// </summary>
        /// <returns>
        /// IDbConnection to the database
        /// </returns>
        /// <exception cref="DatabaseCouldNotBeDeterminedException">
        /// Database could not be determined (check config.xml)
        /// </exception>
        /// <exception cref="ConnectionStringErrorException">
        /// Connection could not be established (check config.xml)
        /// </exception>
        public static IDbConnection GetConnection()
        {
            IDbConnection conn = null;
            if (connector == null)
            {
                if (sqlType == "MySql")
                {
                    connector = new MySQLConnector(ConnectionStringMySql);
                }

                if (sqlType == "MsSql")
                {
                    connector = new MSSqlConnector(ConnectionStringMssql);
                }

                if (sqlType == "PostgreSQL")
                {
                    connector = new NpgsqlConnector(ConnectionStringPostGreSql);
                }
            }

            if (connector == null)
            {
                throw new DatabaseCouldNotBeDeterminedException("Could not determine your database");
            }

            conn = connector.GetConnection();

            if (conn == null)
            {
                throw new ConnectionStringErrorException("ConnectionString error");
            }

            conn.Open();
            return conn;
        }