public IDbContext ConnectionString(string connectionString, IDbProvider fluentDataProvider, string providerName = null)
		{
			if(string.IsNullOrEmpty(providerName))
				providerName = fluentDataProvider.ProviderName;
			var adoNetProvider = System.Data.Common.DbProviderFactories.GetFactory(providerName);
			return ConnectionString(connectionString, fluentDataProvider, adoNetProvider);
		}
示例#2
0
        public TwitterModule(IDbProvider dbProvider)
        {
            Get["/{slug}"] = p =>
                {
                    var mvp = dbProvider.GetDb()
                        .mvps.FindAllBySlug(p["slug"])
                        .WithLinks()
                        .FirstOrDefault()
                        ;

                    if (mvp == null)
                    {
                        return HttpStatusCode.NotFound;
                    }

                    TwitterJson model = TwitterJson.ParseSingle(mvp);

                    return Response.AsJson(model);
                };

            Get["/"] = _ =>
                {
                    var mvps = dbProvider.GetDb().mvps.WithLinks();

                    TwitterJson model = TwitterJson.ParseList(mvps);

                    return Response.AsJson(model);
                };
        }
示例#3
0
 public AbstractQuery(string connectionString, string providerName)
 {
     Check.Argument.IsNotEmpty(connectionString, "connectionString");
     Check.Argument.IsNotEmpty(providerName, "providerName");
     _connectionString = connectionString;
     _provider = DBProviderFactory.CreateProvider(providerName);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="DBSemaphore"/> class.
 /// </summary>
 /// <param name="tablePrefix">The table prefix.</param>
 /// <param name="sql">The SQL.</param>
 /// <param name="defaultSQL">The default SQL.</param>
 /// <param name="dbProvider">The db provider.</param>
 public DBSemaphore(string tablePrefix, string sql, string defaultSQL, IDbProvider dbProvider) {
     log = LogManager.GetLogger(GetType());
     this.sql = defaultSQL;
     this.tablePrefix = tablePrefix;
     SQL = sql;
     adoUtil = new AdoUtil(dbProvider);
 }
		/// <summary>
		/// Initializes a new instance of the <see cref="IDbCommandCreatorFactory"/> class.
        /// </summary>
	    public IDbCommandCreatorFactory(IDbProvider dbProvider, CommandType commandType, string sql, IDbParameters declaredParameters)
	    {
            this.dbProvider = dbProvider;
            this.sql = sql;	
		    this.commandType = commandType;
		    this.declaredParameters = declaredParameters;
	    }
示例#6
0
        /// <summary>
        /// Initializes a new instance of a DatabaseSchema.
        /// </summary>
        /// <param name="dbprovider"></param>
        public DatabaseSchema(IDbProvider dbprovider)
        {
            if (dbprovider == null)
                throw new ArgumentNullException("dbprovider");

            _dbprovider = dbprovider;
        }
        public void SetUpMocks()
        {
            provider = MockRepository.GenerateMock<IDbProvider>();
            IDbConnection connection = MockRepository.GenerateMock<IDbConnection>();

            provider.Stub(x => x.CreateConnection()).Return(connection).Repeat.Once();

            // Creating a query (setting DbProvider property)
            // will call new DbParameters(IDbProvider), which is a real pain to mock.
            // to store the declared parameters.

            command = MockRepository.GenerateMock<IDbCommand>();
            //This IDbCommand is used as a container for the underlying parameter collection.	
            provider.Stub(x => x.CreateCommand()).Return(command).Repeat.Once();

            //Create a real instance of IDbParameters to stored the declared parameters
            IDbProvider realDbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient");
            IDbParameters dbParameters = new DbParameters(realDbProvider);

            //Pass real instance into mock instance.
            command.Stub(x => x.Parameters).Return(dbParameters.DataParameterCollection).Repeat.Once();
            provider.Stub(x => x.CreateCommand()).Return(command).Repeat.Once();

            // done with init of DbParameters mock/stubbing
        }
示例#8
0
 public static DbParameter AddParam(this DbCommand cmd, IDbProvider provider, string name, object value)
 {
     var p = cmd.CreateParameter();
     provider.SetupParameter(p,name,value);
     cmd.Parameters.Add(p);
     return p;
 }
		public IDbContext ConnectionString(string connectionString, IDbProvider fluentDataProvider, System.Data.Common.DbProviderFactory adoNetProviderFactory)
		{
			Data.ConnectionString = connectionString;
			Data.FluentDataProvider = fluentDataProvider;
			Data.AdoNetProvider = adoNetProviderFactory;
			return this;
		}
示例#10
0
 /// <summary>
 /// Serializes the specified <see cref="IDbProvider"/> into an <see cred="IConfiguration" /> node.
 /// </summary>
 public static IConfiguration Serialize(IDbProvider dbProvider)
 {
     IConfiguration providerConfig = new MutableConfiguration("provider", dbProvider.Id, dbProvider.Id);
     providerConfig.Attributes[DataConstants.ATTRIBUTE_NAME] = dbProvider.Id;
     providerConfig.Attributes[DataConstants.ATTRIBUTE_ASSEMBLYNAME] = dbProvider.AssemblyName;
     providerConfig.Attributes[DataConstants.ATTRIBUTE_COMMANDBUILDERCLASS] = dbProvider.CommandBuilderClass;
     providerConfig.Attributes[DataConstants.ATTRIBUTE_COMMANDCLASS] = dbProvider.DbCommandClass;
     providerConfig.Attributes[DataConstants.ATTRIBUTE_CONNECTIONCLASS] = dbProvider.DbConnectionClass;
     providerConfig.Attributes[DataConstants.ATTRIBUTE_DESCRIPTION] = dbProvider.Description;
     providerConfig.Attributes[DataConstants.ATTRIBUTE_DEFAULT] = dbProvider.IsDefault.ToString().ToLower();
     providerConfig.Attributes[DataConstants.ATTRIBUTE_ENABLED] = dbProvider.IsEnabled.ToString().ToLower();
     providerConfig.Attributes[DataConstants.ATTRIBUTE_PARAMETERDBTYPECLASS] = dbProvider.ParameterDbTypeClass;
     providerConfig.Attributes[DataConstants.ATTRIBUTE_PARAMETERDBTYPEPROPERTY] = dbProvider.ParameterDbTypeProperty;
     providerConfig.Attributes[DataConstants.ATTRIBUTE_PARAMETERPREFIX] = dbProvider.ParameterPrefix;
     providerConfig.Attributes[DataConstants.ATTRIBUTE_PARAMETERPREFIX] = dbProvider.ParameterPrefix;
     providerConfig.Attributes[DataConstants.ATTRIBUTE_SETDBPARAMETERPRECISION] = dbProvider.SetDbParameterPrecision.ToString().ToLower();
     providerConfig.Attributes[DataConstants.ATTRIBUTE_SETDBPARAMETERSCALE] = dbProvider.SetDbParameterScale.ToString().ToLower();
     providerConfig.Attributes[DataConstants.ATTRIBUTE_SETDBPARAMETERSIZE] = dbProvider.SetDbParameterSize.ToString().ToLower();
     providerConfig.Attributes[DataConstants.ATTRIBUTE_USEDERIVEPARAMETERS] = dbProvider.UseDeriveParameters.ToString().ToLower();
     providerConfig.Attributes[DataConstants.ATTRIBUTE_USEPARAMETERPREFIXINPARAMETER] = dbProvider.UseParameterPrefixInParameter.ToString().ToLower();
     providerConfig.Attributes[DataConstants.ATTRIBUTE_USEPARAMETERPREFIXINSQL] = dbProvider.UseParameterPrefixInSql.ToString().ToLower();
     providerConfig.Attributes[DataConstants.ATTRIBUTE_USEPOSITIONALPARAMETERS] = dbProvider.UsePositionalParameters.ToString().ToLower();
     providerConfig.Attributes[DataConstants.ATTRIBUTE_ALLOWMARS] = dbProvider.AllowMARS.ToString().ToLower();
     return providerConfig;
 }
		public string GenerateSql(IDbProvider provider, string parameterPrefix, BuilderData data)
		{
			var setSql = "";
			foreach (var column in data.Columns)
			{
				if (setSql.Length > 0)
					setSql += ", ";

				setSql += string.Format("{0} = {1}{2}",
									provider.EscapeColumnName(column.ColumnName),
									parameterPrefix,
									column.ParameterName);
			}

			var whereSql = "";
			foreach (var column in data.Where)
			{
				if (whereSql.Length > 0)
					whereSql += " and ";

				whereSql += string.Format("{0} = {1}{2}",
									provider.EscapeColumnName(column.ColumnName),
									parameterPrefix,
									column.ParameterName);
			}

			var sql = string.Format("update {0} set {1} where {2}",
										data.ObjectName,
										setSql,
										whereSql);
			return sql;
		}
示例#12
0
 public PagedQueryBuilder(TableInfo info,IDbProvider provider)
 {
    
     _info = info;
     _provider = provider;
 
 }
示例#13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DBSemaphore"/> class.
 /// </summary>
 /// <param name="tablePrefix">The table prefix.</param>
 /// <param name="schedName">the scheduler name</param>
 /// <param name="defaultInsertSQL">The SQL.</param>
 /// <param name="defaultSQL">The default SQL.</param>
 /// <param name="dbProvider">The db provider.</param>
 public DBSemaphore(string tablePrefix, string schedName, string defaultSQL, string defaultInsertSQL, IDbProvider dbProvider)
 {
     this.schedName = schedName;
     this.tablePrefix = tablePrefix;
     SQL = defaultSQL;
     InsertSQL = defaultInsertSQL;
     adoUtil = new AdoUtil(dbProvider);
 }
示例#14
0
 public void CreateDbProvider()
 {
     IApplicationContext ctx =
         new XmlApplicationContext("assembly://Spring.Data.Integration.Tests/Spring.Data/adoTemplateTests.xml");
     Assert.IsNotNull(ctx);
     dbProvider = ctx["DbProvider"] as IDbProvider;
     Assert.IsNotNull(dbProvider);
 }
示例#15
0
        /*
		* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		* 
		* Constructors.
		* 
		* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		*/

        /// <summary>
        /// Create new StdAdoDelegate instance.
        /// </summary>
        /// <param name="logger">the logger to use during execution</param>
        /// <param name="tablePrefix">the prefix of all table names</param>
        /// <param name="instanceId">The instance id.</param>
        /// <param name="dbProvider">The db provider.</param>
        public StdAdoDelegate(ILog logger, string tablePrefix, string instanceId, IDbProvider dbProvider)
        {
            this.logger = logger;
            this.tablePrefix = tablePrefix;
            this.instanceId = instanceId;
            this.dbProvider = dbProvider;
            adoUtil = new AdoUtil(dbProvider);
        }
 public void Inject(IDbProvider dbProvider, IReadWriteLockManager lockManager)
 {
     Debug.Assert(dbProvider != null && lockManager != null);
     if (this.dbProvider != null || this.lockManager != null)
         throw new InvalidOperationException();
     this.dbProvider = dbProvider;
     this.lockManager = lockManager;
 }
示例#17
0
 public EmpProc(IDbProvider provider)
     : base(provider, "TEST.Get1CurOut")
 {
     //DeriveParameters();
     DeclaredParameters.AddOut("P_CURSOR1", OracleType.Cursor);
     AddRowMapper("employees", new EmployeeRowMapper());
     Compile();
 }
示例#18
0
 public SqlFuConnection(DbConnection cnx,IDbProvider provider)
 {
     cnx.MustNotBeNull();
     provider.MustNotBeNull();
     _conex = cnx;
     _provider = provider;
   
 }
示例#19
0
 public ActiveRecordScope(string connString)
 {
     _helper = new SqlDbHelper(connString);
     _provider = new SqlServerProvider(_helper);
     _cn = new SqlConnection(connString);
     _cn.Open();
     _tx = _cn.BeginTransaction();
 }
 public void SetUp()
 {
     ctx =
         new XmlApplicationContext("assembly://Spring.Data.Integration.Tests/Spring.Data/autoDeclarativeServices.xml");
     dbProvider = ctx["DbProvider"] as IDbProvider;
     transactionManager = ctx["adoTransactionManager"] as IPlatformTransactionManager;
     
 }
示例#21
0
 public InsertSqlBuilder(TableInfo info,object data,IDbProvider provider,InsertSqlOptions options)
 {
     _info = info;
     _data = data;
     _provider = provider;
     _options = options;      
     options.EnsureTableName(info);      
 }
示例#22
0
 private void Init(string cnxString, IDbProvider provider)
 {
     cnxString.MustNotBeEmpty();
     provider.MustNotBeNull();
     _provider = provider;
     _conex = _provider.CreateConnection();
     _conex.ConnectionString = cnxString;
  
 }
		public IDbContext ConnectionStringName(string connectionstringName, IDbProvider dbProvider)
		{
			var settings = ConfigurationManager.ConnectionStrings[connectionstringName];
			if(settings == null)
				throw new FluentDataException("A connectionstring with the specified name was not found in the .config file");
			
			ConnectionString(settings.ConnectionString, dbProvider, settings.ProviderName);
			return this;
		}
		/// <summary>
		///  Creates a DataReaderAdapter from a <see cref="IDataReader" />
		/// </summary>
		/// <param name="reader">The <see cref="IDataReader" /> which holds the records from the Database.</param>
		/// <param name="dbProvider">The databse provider <see cref="IDbProvider"/></param>
		public static IDataReader Transform(IDataReader reader, IDbProvider dbProvider)
		{
		    if (!dbProvider.AllowMARS && !(reader is InMemoryDataReader))
			{
				// The underlying reader will be closed.
				return new InMemoryDataReader(reader);
			}
		    return reader;
		}
示例#25
0
文件: Db.cs 项目: mehmetatas/DummyOrm
        public static IDbBuilder Setup(IDbProvider provider)
        {
            if (_defaultProvider == null)
            {
                _defaultProvider = provider;
            }

            return new DbBuilder(provider);
        }
        /// <summary>
        /// Deserialize a DataSource object
        /// </summary>
        /// <param name="dbProvider">The db provider.</param>
        /// <param name="commandTimeOut">The command time out.</param>
        /// <param name="config">The config.</param>
        /// <returns></returns>
        public static DataSource Deserialize(IDbProvider dbProvider, int commandTimeOut, IConfiguration config)
		{
            IConfiguration dataSourceConfig = config.Children.Find(DataConstants.ELEMENT_DATASOURCE)[0];

            string connectionString = dataSourceConfig.Attributes[DataConstants.ATTRIBUTE_CONNECTIONSTRING];
            string name = dataSourceConfig.Attributes[DataConstants.ATTRIBUTE_NAME];

            return new DataSource(name, connectionString, commandTimeOut, dbProvider);
		}
示例#27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DBSemaphore"/> class.
 /// </summary>
 /// <param name="tablePrefix">The table prefix.</param>
 /// <param name="defaultInsertSQL">The SQL.</param>
 /// <param name="defaultSQL">The default SQL.</param>
 /// <param name="dbProvider">The db provider.</param>
 public DBSemaphore(string tablePrefix, string schedName, string defaultSQL, string defaultInsertSQL, IDbProvider dbProvider)
 {
     log = LogManager.GetLogger(GetType());
     this.schedName = schedName;
     this.tablePrefix = tablePrefix;
     SQL = defaultSQL;
     InsertSQL = defaultInsertSQL;
     adoUtil = new AdoUtil(dbProvider);
 }
示例#28
0
 /// <summary>
 /// Initializes a new instance of the ColumnSchema
 /// </summary>
 /// <param name="dbprovider">The DbProvider used for interrogating the datastore.</param>
 /// <param name="table">The TableSchema that contains the column.</param>
 /// <param name="sqlType">SqlDbType.</param>
 /// <param name="dataType">.NET DataType</param>
 /// <param name="name">Name of the column.</param>
 /// <param name="props">Any extended properties.</param>
 /// <param name="length">Length of the column if supported.</param>
 public ColumnSchema(IDbProvider dbprovider, TableSchema table, SqlDbType sqlType, Type dataType, string name, int length, Dictionary<string, object> props)
 {
     _table = table;
     _props = props;
     _sqlType = sqlType;
     _dataType = dataType;
     _name = name;
     _length = length;
     _dbprovider = dbprovider;
 }
示例#29
0
        public MvpListModule(IDbProvider dbProvider)
        {
            Get["/"] = _ =>
                {
                    var mvps = dbProvider.GetDb().mvps.WithNominations();

                    var model = new MvpListModel(mvps);
                    return View["mvp-list", model];
                };
        }
示例#30
0
        public HistoryModule(IDbProvider dbProvider)
        {
            Get["/historia"] = _ =>
                {
                    var nominations = dbProvider.GetDb().nominations
                        .WithMvp()
                        .ToList();

                    return View["nominations", new NominationsListModel(nominations)];
                };
        }
示例#31
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="dbProvider">数据库连接</param>
 /// <param name="userInfo">用户信息</param>
 /// <param name="tableName">指定表名</param>
 public UserControlsLinkManager(IDbProvider dbProvider, UserInfo userInfo, string tableName) : this(dbProvider, userInfo)
 {
     base.CurrentTableName = tableName;
 }
示例#32
0
 public SessionHandler(IDbProvider databaseClient)
 {
     this.databaseClient = databaseClient;
     this.Playlist       = this.GetPlaylist();
     this.CurrentSong    = this.Playlist.Pop();
 }
示例#33
0
 public IksTestDataGenerator(IDbProvider <IksInDbContext> iksInDbContextProvider)
 {
     _IksInDbContextProvider = iksInDbContextProvider ?? throw new ArgumentNullException(nameof(iksInDbContextProvider));
 }
 public BaseUpdateBuilder(IDbProvider provider, IDbCommand command, string name)
 {
     Data    = new BuilderData(provider, command, name);
     Actions = new ActionsHandler(Data);
 }
示例#35
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="dbProvider">数据库连接</param>
 public UserControlsLinkManager(IDbProvider dbProvider) : this()
 {
     DBProvider = dbProvider;
 }
 public TransactionCommitTxCallback(ISessionFactory sessionFactory, IDbProvider provider)
 {
     sfProxy       = sessionFactory;
     this.provider = provider;
 }
        public void TransactionCommit()
        {
            IDbProvider     provider       = (IDbProvider)mocks.CreateMock(typeof(IDbProvider));
            IDbConnection   connection     = (IDbConnection)mocks.CreateMock(typeof(IDbConnection));
            ISessionFactory sessionFactory = (ISessionFactory)mocks.CreateMock(typeof(ISessionFactory));
            ISession        session        = (ISession)mocks.CreateMock(typeof(ISession));
            ITransaction    transaction    = (ITransaction)mocks.CreateMock(typeof(ITransaction));
            IQuery          query          = (IQuery)mocks.CreateMock(typeof(IQuery));

            IList list = new ArrayList();

            list.Add("test");
            using (mocks.Ordered())
            {
                Expect.Call(sessionFactory.OpenSession()).Return(session);
                Expect.Call(session.Connection).Return(connection);
                Expect.Call(session.BeginTransaction(IsolationLevel.Serializable)).Return(transaction);
                Expect.Call(session.IsOpen).Return(true);
                Expect.Call(session.CreateQuery("some query string")).Return(query);
                Expect.Call(query.List()).Return(list);
                transaction.Commit();
                LastCall.On(transaction).Repeat.Once();
                Expect.Call(session.Close()).Return(null);
            }

            mocks.ReplayAll();


            LocalSessionFactoryObjectStub lsfo = new LocalSessionFactoryObjectStub(sessionFactory);

            lsfo.AfterPropertiesSet();

            ISessionFactory sfProxy = lsfo.GetObject() as ISessionFactory;

            Assert.IsNotNull(sfProxy);

            HibernateTransactionManager tm = new HibernateTransactionManager();

            tm.AdoExceptionTranslator = new FallbackExceptionTranslator();
            tm.SessionFactory         = sfProxy;
            tm.DbProvider             = provider;
            TransactionTemplate tt = new TransactionTemplate(tm);

            tt.TransactionIsolationLevel = IsolationLevel.Serializable;

            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sfProxy), "Hasn't thread session");
            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(provider), "Hasn't thread db provider");
            Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active");
            Assert.IsTrue(!TransactionSynchronizationManager.ActualTransactionActive, "Actual transaction not active");

            object result = tt.Execute(new TransactionCommitTxCallback(sfProxy, provider));

            Assert.IsTrue(result == list, "Incorrect result list");

            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sfProxy), "Hasn't thread session");
            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(provider), "Hasn't thread db provider");
            Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active");
            Assert.IsTrue(!TransactionSynchronizationManager.ActualTransactionActive, "Actual transaction not active");


            mocks.VerifyAll();
        }
示例#38
0
 public StateReader(IDbProvider dbProvider, ILogManager logManager)
     : this(dbProvider.StateDb, dbProvider.CodeDb, logManager)
 {
 }
        public async Task InitializerTests_WithPruning()
        {
            IDbProvider dbProvider = await InitializeStandardDb(false, DbModeHint.Mem, "pruning", true);

            dbProvider.StateDb.Should().BeOfType <FullPruningDb>();
        }
示例#40
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AdoQuery"/> class.
 /// </summary>
 /// <param name="provider">The database provider.</param>
 /// <param name="sql">The SQL to execute</param>
 public AdoQuery(IDbProvider provider, string sql)
 {
     DbProvider = provider;
     Sql        = sql;
 }
 /// <summary>
 /// 设置DbProvider
 /// </summary>
 /// <param name="provider"></param>
 /// <returns></returns>
 public TransactionScopeUnitOfWorkFactory SetDbProvider(IDbProvider provider)
 {
     dbProvider = provider;
     return(this);
 }
示例#42
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="dbProvider">数据库连接</param>
 /// <param name="userInfo">用户信息</param>
 /// <param name="tableName">指定表名</param>
 public PiUserLogOnManager(IDbProvider dbProvider, UserInfo userInfo, string tableName) : this(dbProvider, userInfo)
 {
     base.CurrentTableName = tableName;
 }
示例#43
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="dbProvider">数据库连接</param>
 /// <param name="userInfo">用户信息</param>
 public UserControlsLinkManager(IDbProvider dbProvider, UserInfo userInfo) : this(dbProvider)
 {
     UserInfo = userInfo;
 }
示例#44
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="dbProvider">数据库连接</param>
 public PiUserLogOnManager(IDbProvider dbProvider) : this()
 {
     DBProvider = dbProvider;
 }
 public NullArg(IDbProvider provider)
     : base(provider, "takes_null")
 {
     DeclaredParameters.Add("ptest", DbType.String);
     Compile();
 }
示例#46
0
 public SchedulerCenter()
 {
     InitDriverDelegateType();
     dbProvider = new DbProvider(AppConfig.DbProviderName, AppConfig.ConnectionString);
 }
示例#47
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="dbProvider">数据库连接</param>
 /// <param name="userInfo">用户信息</param>
 public PiUserLogOnManager(IDbProvider dbProvider, UserInfo userInfo) : this(dbProvider)
 {
     UserInfo = userInfo;
 }
示例#48
0
        /// <summary>  </summary>
        private IScheduler Instantiate()
        {
            if (cfg == null)
            {
                Initialize();
            }

            if (initException != null)
            {
                throw initException;
            }

            ISchedulerExporter  exporter = null;
            IJobStore           js;
            IThreadPool         tp;
            QuartzScheduler     qs       = null;
            DBConnectionManager dbMgr    = null;
            Type instanceIdGeneratorType = null;
            NameValueCollection tProps;
            bool            autoId         = false;
            TimeSpan        idleWaitTime   = TimeSpan.Zero;
            TimeSpan        dbFailureRetry = TimeSpan.Zero;
            IThreadExecutor threadExecutor;

            SchedulerService schedRep = SchedulerService.Instance;

            // Get Scheduler Properties
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            string schedName   = cfg.GetStringProperty(PropertySchedulerInstanceName, "QuartzScheduler");
            string threadName  = cfg.GetStringProperty(PropertySchedulerThreadName, "{0}_QuartzSchedulerThread".FormatInvariant(schedName));
            string schedInstId = cfg.GetStringProperty(PropertySchedulerInstanceId, DefaultInstanceId);

            if (schedInstId.Equals(AutoGenerateInstanceId))
            {
                autoId = true;
                instanceIdGeneratorType = LoadType(cfg.GetStringProperty(PropertySchedulerInstanceIdGeneratorType)) ?? typeof(SimpleInstanceIdGenerator);
            }
            else if (schedInstId.Equals(SystemPropertyAsInstanceId))
            {
                autoId = true;
                instanceIdGeneratorType = typeof(SystemPropertyInstanceIdGenerator);
            }

            Type typeLoadHelperType = LoadType(cfg.GetStringProperty(PropertySchedulerTypeLoadHelperType));
            Type jobFactoryType     = LoadType(cfg.GetStringProperty(PropertySchedulerJobFactoryType, null));

            idleWaitTime = cfg.GetTimeSpanProperty(PropertySchedulerIdleWaitTime, idleWaitTime);
            if (idleWaitTime > TimeSpan.Zero && idleWaitTime < TimeSpan.FromMilliseconds(1000))
            {
                throw new SchedulerException("quartz.scheduler.idleWaitTime of less than 1000ms is not legal.");
            }

            dbFailureRetry = cfg.GetTimeSpanProperty(PropertySchedulerDbFailureRetryInterval, dbFailureRetry);
            bool makeSchedulerThreadDaemon = cfg.GetBooleanProperty(PropertySchedulerMakeSchedulerThreadDaemon);
            long batchTimeWindow           = cfg.GetLongProperty(PropertySchedulerBatchTimeWindow, 0L);
            int  maxBatchSize = cfg.GetIntProperty(PropertySchedulerMaxBatchSize, 1);

            bool interruptJobsOnShutdown         = cfg.GetBooleanProperty(PropertySchedulerInterruptJobsOnShutdown, false);
            bool interruptJobsOnShutdownWithWait = cfg.GetBooleanProperty(PropertySchedulerInterruptJobsOnShutdownWithWait, false);

            NameValueCollection schedCtxtProps = cfg.GetPropertyGroup(PropertySchedulerContextPrefix, true);

            bool proxyScheduler = cfg.GetBooleanProperty(PropertySchedulerProxy, false);


            // Create type load helper
            ITypeLoadHelper loadHelper;

            try
            {
                loadHelper = ObjectUtils.InstantiateType <ITypeLoadHelper>(typeLoadHelperType ?? typeof(SimpleTypeLoadHelper));
            }
            catch (Exception e)
            {
                throw new SchedulerConfigException("Unable to instantiate type load helper: {0}".FormatInvariant(e.Message), e);
            }
            loadHelper.Initialize();


            // If Proxying to remote scheduler, short-circuit here...
            // ~~~~~~~~~~~~~~~~~~
            if (proxyScheduler)
            {
                if (autoId)
                {
                    schedInstId = DefaultInstanceId;
                }

                Type proxyType = loadHelper.LoadType(cfg.GetStringProperty(PropertySchedulerProxyType)) ?? typeof(RemotingSchedulerProxyFactory);
                IRemotableSchedulerProxyFactory factory;
                try
                {
                    factory = ObjectUtils.InstantiateType <IRemotableSchedulerProxyFactory>(proxyType);
                    ObjectUtils.SetObjectProperties(factory, cfg.GetPropertyGroup(PropertySchedulerProxy, true));
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("Remotable proxy factory '{0}' could not be instantiated.".FormatInvariant(proxyType), e);
                    throw initException;
                }

                string uid = QuartzSchedulerResources.GetUniqueIdentifier(schedName, schedInstId);

                RemoteScheduler remoteScheduler = new RemoteScheduler(uid, factory);

                schedRep.Bind(remoteScheduler);

                return(remoteScheduler);
            }


            IJobFactory jobFactory = null;

            if (jobFactoryType != null)
            {
                try
                {
                    jobFactory = ObjectUtils.InstantiateType <IJobFactory>(jobFactoryType);
                }
                catch (Exception e)
                {
                    throw new SchedulerConfigException("Unable to Instantiate JobFactory: {0}".FormatInvariant(e.Message), e);
                }

                tProps = cfg.GetPropertyGroup(PropertySchedulerJobFactoryPrefix, true);
                try
                {
                    ObjectUtils.SetObjectProperties(jobFactory, tProps);
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("JobFactory of type '{0}' props could not be configured.".FormatInvariant(jobFactoryType), e);
                    throw initException;
                }
            }

            IInstanceIdGenerator instanceIdGenerator = null;

            if (instanceIdGeneratorType != null)
            {
                try
                {
                    instanceIdGenerator = ObjectUtils.InstantiateType <IInstanceIdGenerator>(instanceIdGeneratorType);
                }
                catch (Exception e)
                {
                    throw new SchedulerConfigException("Unable to Instantiate InstanceIdGenerator: {0}".FormatInvariant(e.Message), e);
                }
                tProps = cfg.GetPropertyGroup(PropertySchedulerInstanceIdGeneratorPrefix, true);
                try
                {
                    ObjectUtils.SetObjectProperties(instanceIdGenerator, tProps);
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("InstanceIdGenerator of type '{0}' props could not be configured.".FormatInvariant(instanceIdGeneratorType), e);
                    throw initException;
                }
            }

            // Get ThreadPool Properties
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            Type tpType = loadHelper.LoadType(cfg.GetStringProperty(PropertyThreadPoolType)) ?? typeof(SimpleThreadPool);

            try
            {
                tp = ObjectUtils.InstantiateType <IThreadPool>(tpType);
            }
            catch (Exception e)
            {
                initException = new SchedulerException("ThreadPool type '{0}' could not be instantiated.".FormatInvariant(tpType), e);
                throw initException;
            }
            tProps = cfg.GetPropertyGroup(PropertyThreadPoolPrefix, true);
            try
            {
                ObjectUtils.SetObjectProperties(tp, tProps);
            }
            catch (Exception e)
            {
                initException = new SchedulerException("ThreadPool type '{0}' props could not be configured.".FormatInvariant(tpType), e);
                throw initException;
            }

            // Set up any DataSources
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            string[] dsNames = cfg.GetPropertyGroups(PropertyDataSourcePrefix);
            for (int i = 0; i < dsNames.Length; i++)
            {
                string datasourceKey = "{0}.{1}".FormatInvariant(PropertyDataSourcePrefix, dsNames[i]);
                NameValueCollection propertyGroup = cfg.GetPropertyGroup(datasourceKey, true);
                PropertiesParser    pp            = new PropertiesParser(propertyGroup);

                Type cpType = loadHelper.LoadType(pp.GetStringProperty(PropertyDbProviderType, null));

                // custom connectionProvider...
                if (cpType != null)
                {
                    IDbProvider cp;
                    try
                    {
                        cp = ObjectUtils.InstantiateType <IDbProvider>(cpType);
                    }
                    catch (Exception e)
                    {
                        initException = new SchedulerException("ConnectionProvider of type '{0}' could not be instantiated.".FormatInvariant(cpType), e);
                        throw initException;
                    }

                    try
                    {
                        // remove the type name, so it isn't attempted to be set
                        pp.UnderlyingProperties.Remove(PropertyDbProviderType);

                        ObjectUtils.SetObjectProperties(cp, pp.UnderlyingProperties);
                    }
                    catch (Exception e)
                    {
                        initException = new SchedulerException("ConnectionProvider type '{0}' props could not be configured.".FormatInvariant(cpType), e);
                        throw initException;
                    }

                    dbMgr = DBConnectionManager.Instance;
                    dbMgr.AddConnectionProvider(dsNames[i], cp);
                }
                else
                {
                    string dsProvider             = pp.GetStringProperty(PropertyDataSourceProvider, null);
                    string dsConnectionString     = pp.GetStringProperty(PropertyDataSourceConnectionString, null);
                    string dsConnectionStringName = pp.GetStringProperty(PropertyDataSourceConnectionStringName, null);

                    if (dsConnectionString == null && !String.IsNullOrEmpty(dsConnectionStringName))
                    {
                        ConnectionStringSettings connectionStringSettings = ConfigurationManager.ConnectionStrings[dsConnectionStringName];
                        if (connectionStringSettings == null)
                        {
                            initException = new SchedulerException("Named connection string '{0}' not found for DataSource: {1}".FormatInvariant(dsConnectionStringName, dsNames[i]));
                            throw initException;
                        }
                        dsConnectionString = connectionStringSettings.ConnectionString;
                    }

                    if (dsProvider == null)
                    {
                        initException = new SchedulerException("Provider not specified for DataSource: {0}".FormatInvariant(dsNames[i]));
                        throw initException;
                    }
                    if (dsConnectionString == null)
                    {
                        initException = new SchedulerException("Connection string not specified for DataSource: {0}".FormatInvariant(dsNames[i]));
                        throw initException;
                    }
                    try
                    {
                        DbProvider dbp = new DbProvider(dsProvider, dsConnectionString);

                        dbMgr = DBConnectionManager.Instance;
                        dbMgr.AddConnectionProvider(dsNames[i], dbp);
                    }
                    catch (Exception exception)
                    {
                        initException = new SchedulerException("Could not Initialize DataSource: {0}".FormatInvariant(dsNames[i]), exception);
                        throw initException;
                    }
                }
            }

            // Get object serializer properties
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            IObjectSerializer objectSerializer;
            string            objectSerializerType = cfg.GetStringProperty("quartz.serializer.type");

            if (objectSerializerType != null)
            {
                tProps = cfg.GetPropertyGroup(PropertyObjectSerializer, true);
                try
                {
                    objectSerializer = ObjectUtils.InstantiateType <IObjectSerializer>(loadHelper.LoadType(objectSerializerType));

                    ObjectUtils.SetObjectProperties(objectSerializer, tProps);
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("Object serializer type '" + objectSerializerType + "' could not be instantiated.", e);
                    throw initException;
                }
            }
            else
            {
                objectSerializer = new DefaultObjectSerializer();
            }

            // Get JobStore Properties
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            Type jsType = loadHelper.LoadType(cfg.GetStringProperty(PropertyJobStoreType));

            try
            {
                js = ObjectUtils.InstantiateType <IJobStore>(jsType ?? typeof(RAMJobStore));
            }
            catch (Exception e)
            {
                initException = new SchedulerException("JobStore of type '{0}' could not be instantiated.".FormatInvariant(jsType), e);
                throw initException;
            }


            SchedulerDetailsSetter.SetDetails(js, schedName, schedInstId);

            tProps = cfg.GetPropertyGroup(PropertyJobStorePrefix, true, new string[] { PropertyJobStoreLockHandlerPrefix });

            try
            {
                ObjectUtils.SetObjectProperties(js, tProps);
            }
            catch (Exception e)
            {
                initException = new SchedulerException("JobStore type '{0}' props could not be configured.".FormatInvariant(jsType), e);
                throw initException;
            }

            if (js is JobStoreSupport)
            {
                // Install custom lock handler (Semaphore)
                Type lockHandlerType = loadHelper.LoadType(cfg.GetStringProperty(PropertyJobStoreLockHandlerType));
                if (lockHandlerType != null)
                {
                    try
                    {
                        ISemaphore      lockHandler;
                        ConstructorInfo cWithDbProvider = lockHandlerType.GetConstructor(new Type[] { typeof(DbProvider) });

                        if (cWithDbProvider != null)
                        {
                            // takes db provider
                            IDbProvider dbProvider = DBConnectionManager.Instance.GetDbProvider(((JobStoreSupport)js).DataSource);
                            lockHandler = (ISemaphore)cWithDbProvider.Invoke(new object[] { dbProvider });
                        }
                        else
                        {
                            lockHandler = ObjectUtils.InstantiateType <ISemaphore>(lockHandlerType);
                        }

                        tProps = cfg.GetPropertyGroup(PropertyJobStoreLockHandlerPrefix, true);

                        // If this lock handler requires the table prefix, add it to its properties.
                        if (lockHandler is ITablePrefixAware)
                        {
                            tProps[PropertyTablePrefix]   = ((JobStoreSupport)js).TablePrefix;
                            tProps[PropertySchedulerName] = schedName;
                        }

                        try
                        {
                            ObjectUtils.SetObjectProperties(lockHandler, tProps);
                        }
                        catch (Exception e)
                        {
                            initException = new SchedulerException("JobStore LockHandler type '{0}' props could not be configured.".FormatInvariant(lockHandlerType), e);
                            throw initException;
                        }

                        ((JobStoreSupport)js).LockHandler = lockHandler;
                    }
                    catch (Exception e)
                    {
                        initException = new SchedulerException("JobStore LockHandler type '{0}' could not be instantiated.".FormatInvariant(lockHandlerType), e);
                        throw initException;
                    }
                }
            }

            // Set up any SchedulerPlugins
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            string[]           pluginNames = cfg.GetPropertyGroups(PropertyPluginPrefix);
            ISchedulerPlugin[] plugins     = new ISchedulerPlugin[pluginNames.Length];
            for (int i = 0; i < pluginNames.Length; i++)
            {
                NameValueCollection pp = cfg.GetPropertyGroup("{0}.{1}".FormatInvariant(PropertyPluginPrefix, pluginNames[i]), true);

                string plugInType = pp[PropertyPluginType] ?? null;

                if (plugInType == null)
                {
                    initException = new SchedulerException("SchedulerPlugin type not specified for plugin '{0}'".FormatInvariant(pluginNames[i]));
                    throw initException;
                }
                ISchedulerPlugin plugin;
                try
                {
                    plugin = ObjectUtils.InstantiateType <ISchedulerPlugin>(LoadType(plugInType));
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("SchedulerPlugin of type '{0}' could not be instantiated.".FormatInvariant(plugInType), e);
                    throw initException;
                }
                try
                {
                    ObjectUtils.SetObjectProperties(plugin, pp);
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("JobStore SchedulerPlugin '{0}' props could not be configured.".FormatInvariant(plugInType), e);
                    throw initException;
                }
                plugins[i] = plugin;
            }

            // Set up any JobListeners
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            string[]       jobListenerNames = cfg.GetPropertyGroups(PropertyJobListenerPrefix);
            IJobListener[] jobListeners     = new IJobListener[jobListenerNames.Length];
            for (int i = 0; i < jobListenerNames.Length; i++)
            {
                NameValueCollection lp = cfg.GetPropertyGroup("{0}.{1}".FormatInvariant(PropertyJobListenerPrefix, jobListenerNames[i]), true);

                string listenerType = lp[PropertyListenerType];

                if (listenerType == null)
                {
                    initException = new SchedulerException("JobListener type not specified for listener '{0}'".FormatInvariant(jobListenerNames[i]));
                    throw initException;
                }
                IJobListener listener;
                try
                {
                    listener = ObjectUtils.InstantiateType <IJobListener>(loadHelper.LoadType(listenerType));
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("JobListener of type '{0}' could not be instantiated.".FormatInvariant(listenerType), e);
                    throw initException;
                }
                try
                {
                    PropertyInfo nameProperty = listener.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
                    if (nameProperty != null && nameProperty.CanWrite)
                    {
                        nameProperty.GetSetMethod().Invoke(listener, new object[] { jobListenerNames[i] });
                    }
                    ObjectUtils.SetObjectProperties(listener, lp);
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("JobListener '{0}' props could not be configured.".FormatInvariant(listenerType), e);
                    throw initException;
                }
                jobListeners[i] = listener;
            }

            // Set up any TriggerListeners
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            string[]           triggerListenerNames = cfg.GetPropertyGroups(PropertyTriggerListenerPrefix);
            ITriggerListener[] triggerListeners     = new ITriggerListener[triggerListenerNames.Length];
            for (int i = 0; i < triggerListenerNames.Length; i++)
            {
                NameValueCollection lp = cfg.GetPropertyGroup("{0}.{1}".FormatInvariant(PropertyTriggerListenerPrefix, triggerListenerNames[i]), true);

                string listenerType = lp[PropertyListenerType];

                if (listenerType == null)
                {
                    initException = new SchedulerException("TriggerListener type not specified for listener '{0}'".FormatInvariant(triggerListenerNames[i]));
                    throw initException;
                }
                ITriggerListener listener;
                try
                {
                    listener = ObjectUtils.InstantiateType <ITriggerListener>(loadHelper.LoadType(listenerType));
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("TriggerListener of type '{0}' could not be instantiated.".FormatInvariant(listenerType), e);
                    throw initException;
                }
                try
                {
                    PropertyInfo nameProperty = listener.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
                    if (nameProperty != null && nameProperty.CanWrite)
                    {
                        nameProperty.GetSetMethod().Invoke(listener, new object[] { triggerListenerNames[i] });
                    }
                    ObjectUtils.SetObjectProperties(listener, lp);
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("TriggerListener '{0}' props could not be configured.".FormatInvariant(listenerType), e);
                    throw initException;
                }
                triggerListeners[i] = listener;
            }

            // Get exporter
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            string exporterType = cfg.GetStringProperty(PropertySchedulerExporterType, null);

            if (exporterType != null)
            {
                try
                {
                    exporter = ObjectUtils.InstantiateType <ISchedulerExporter>(loadHelper.LoadType(exporterType));
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("Scheduler exporter of type '{0}' could not be instantiated.".FormatInvariant(exporterType), e);
                    throw initException;
                }

                tProps = cfg.GetPropertyGroup(PropertySchedulerExporterPrefix, true);

                try
                {
                    ObjectUtils.SetObjectProperties(exporter, tProps);
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("Scheduler exporter type '{0}' props could not be configured.".FormatInvariant(exporterType), e);
                    throw initException;
                }
            }

            bool tpInited = false;
            bool qsInited = false;


            // Get ThreadExecutor Properties
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            string threadExecutorClass = cfg.GetStringProperty(PropertyThreadExecutorType);

            if (threadExecutorClass != null)
            {
                tProps = cfg.GetPropertyGroup(PropertyThreadExecutor, true);
                try
                {
                    threadExecutor = ObjectUtils.InstantiateType <IThreadExecutor>(loadHelper.LoadType(threadExecutorClass));

                    ObjectUtils.SetObjectProperties(threadExecutor, tProps);
                }
                catch (Exception e)
                {
                    initException = new SchedulerException(
                        "ThreadExecutor class '" + threadExecutorClass + "' could not be instantiated.", e);
                    throw initException;
                }
            }
            else
            {
                threadExecutor = new DefaultThreadExecutor();
            }

            // Fire everything up
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            try
            {
                IJobRunShellFactory jrsf = new StdJobRunShellFactory();

                if (autoId)
                {
                    try
                    {
                        schedInstId = DefaultInstanceId;

                        if (js.Clustered)
                        {
                            schedInstId = instanceIdGenerator.GenerateInstanceId();
                        }
                    }
                    catch (Exception e)
                    {
                        throw new SystemException("Cannot run without an instance id.", e);
                    }
                }


                if (js is JobStoreSupport)
                {
                    JobStoreSupport jjs = (JobStoreSupport)js;
                    jjs.DbRetryInterval = dbFailureRetry;
                    jjs.ThreadExecutor  = threadExecutor;
                    // object serializer
                    jjs.ObjectSerializer = objectSerializer;
                }

                QuartzSchedulerResources rsrcs = new QuartzSchedulerResources();
                rsrcs.Name                            = schedName;
                rsrcs.ThreadName                      = threadName;
                rsrcs.InstanceId                      = schedInstId;
                rsrcs.JobRunShellFactory              = jrsf;
                rsrcs.MakeSchedulerThreadDaemon       = makeSchedulerThreadDaemon;
                rsrcs.BatchTimeWindow                 = TimeSpan.FromMilliseconds(batchTimeWindow);
                rsrcs.MaxBatchSize                    = maxBatchSize;
                rsrcs.InterruptJobsOnShutdown         = interruptJobsOnShutdown;
                rsrcs.InterruptJobsOnShutdownWithWait = interruptJobsOnShutdownWithWait;
                rsrcs.SchedulerExporter               = exporter;

                SchedulerDetailsSetter.SetDetails(tp, schedName, schedInstId);

                rsrcs.ThreadExecutor = threadExecutor;
                threadExecutor.Initialize();

                rsrcs.ThreadPool = tp;

                if (tp is SimpleThreadPool)
                {
                    ((SimpleThreadPool)tp).ThreadNamePrefix = schedName + "_Worker";
                }
                tp.Initialize();
                tpInited = true;

                rsrcs.JobStore = js;

                // add plugins
                for (int i = 0; i < plugins.Length; i++)
                {
                    rsrcs.AddSchedulerPlugin(plugins[i]);
                }

                qs       = new QuartzScheduler(rsrcs, idleWaitTime, dbFailureRetry);
                qsInited = true;

                // Create Scheduler ref...
                IScheduler sched = Instantiate(rsrcs, qs);

                // set job factory if specified
                if (jobFactory != null)
                {
                    qs.JobFactory = jobFactory;
                }

                // Initialize plugins now that we have a Scheduler instance.
                for (int i = 0; i < plugins.Length; i++)
                {
                    plugins[i].Initialize(pluginNames[i], sched);
                }

                // add listeners
                for (int i = 0; i < jobListeners.Length; i++)
                {
                    qs.ListenerManager.AddJobListener(jobListeners[i], EverythingMatcher <JobKey> .AllJobs());
                }
                for (int i = 0; i < triggerListeners.Length; i++)
                {
                    qs.ListenerManager.AddTriggerListener(triggerListeners[i], EverythingMatcher <TriggerKey> .AllTriggers());
                }

                // set scheduler context data...
                foreach (string key in schedCtxtProps)
                {
                    string val = schedCtxtProps.Get(key);
                    sched.Context.Put(key, val);
                }

                // fire up job store, and runshell factory

                js.InstanceId   = schedInstId;
                js.InstanceName = schedName;
                js.Initialize(loadHelper, qs.SchedulerSignaler);
                js.ThreadPoolSize = tp.PoolSize;

                jrsf.Initialize(sched);
                qs.Initialize();

                // prevents the service from being garbage collected
                qs.AddNoGCObject(schedRep);
                // prevents the db manager from being garbage collected
                if (dbMgr != null)
                {
                    qs.AddNoGCObject(dbMgr);
                }

                schedRep.Bind(sched);

                return(sched);
            }
            catch (SchedulerException)
            {
                if (qsInited)
                {
                    qs.Shutdown(false);
                }
                else if (tpInited)
                {
                    tp.Shutdown(false);
                }
                throw;
            }
            catch
            {
                if (qsInited)
                {
                    qs.Shutdown(false);
                }
                else if (tpInited)
                {
                    tp.Shutdown(false);
                }
                throw;
            }
        }
示例#49
0
 public ChainLevelInfoRepository(IDbProvider dbProvider)
     : this(dbProvider.BlockInfosDb)
 {
 }
示例#50
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MySqlSqlBuilder"/> class.
 /// </summary>
 /// <param name="dbProvider">The db provider.</param>
 /// <param name="dbOption">The db option.</param>
 /// <param name="visitProvider">The visit provider.</param>
 /// <param name="typeMap"></param>
 public MySqlSqlBuilder(IDbProvider dbProvider, DbOption dbOption, IVisitProvider visitProvider, TypeMap typeMap) : base(visitProvider, dbProvider, dbOption, typeMap)
 {
 }
示例#51
0
        private SyncTestContext CreateSyncManager(int index)
        {
            NoErrorLimboLogs   logManager = NoErrorLimboLogs.Instance;
            ConsoleAsyncLogger logger     = new(LogLevel.Debug, "PEER " + index + " ");
//            var logManager = new OneLoggerLogManager(logger);
            SingleReleaseSpecProvider specProvider =
                new(ConstantinopleFix.Instance, MainnetSpecProvider.Instance.ChainId);

            IDbProvider dbProvider  = TestMemDbProvider.Init();
            IDb         blockDb     = dbProvider.BlocksDb;
            IDb         headerDb    = dbProvider.HeadersDb;
            IDb         blockInfoDb = dbProvider.BlockInfosDb;
            IDb         codeDb      = dbProvider.CodeDb;
            IDb         stateDb     = dbProvider.StateDb;

            TrieStore     trieStore     = new(stateDb, LimboLogs.Instance);
            StateReader   stateReader   = new(trieStore, codeDb, logManager);
            StateProvider stateProvider = new(trieStore, codeDb, logManager);

            stateProvider.CreateAccount(TestItem.AddressA, 10000.Ether());
            stateProvider.Commit(specProvider.GenesisSpec);
            stateProvider.CommitTree(0);
            stateProvider.RecalculateStateRoot();

            StorageProvider        storageProvider = new(trieStore, stateProvider, logManager);
            InMemoryReceiptStorage receiptStorage  = new();

            EthereumEcdsa ecdsa = new(specProvider.ChainId, logManager);
            BlockTree     tree  = new(blockDb, headerDb, blockInfoDb, new ChainLevelInfoRepository(blockInfoDb),
                                      specProvider, NullBloomStorage.Instance, logManager);

            TxPool.TxPool txPool = new(new InMemoryTxStorage(), ecdsa, new ChainHeadSpecProvider(specProvider, tree),
                                       new TxPoolConfig(), stateProvider, new TxValidator(specProvider.ChainId), logManager);
            BlockhashProvider blockhashProvider = new(tree, LimboLogs.Instance);
            VirtualMachine    virtualMachine    =
                new(stateProvider, storageProvider, blockhashProvider, specProvider, logManager);

            Always          sealValidator   = Always.Valid;
            HeaderValidator headerValidator = new(tree, sealValidator, specProvider, logManager);
            Always          txValidator     = Always.Valid;
            OmmersValidator ommersValidator = new(tree, headerValidator, logManager);
            BlockValidator  blockValidator  =
                new(txValidator, headerValidator, ommersValidator, specProvider, logManager);

            ISyncConfig syncConfig = _synchronizerType == SynchronizerType.Fast
                ? SyncConfig.WithFastSync
                : SyncConfig.WithFullSyncOnly;

            RewardCalculator     rewardCalculator = new(specProvider);
            TransactionProcessor txProcessor      =
                new(specProvider, stateProvider, storageProvider, virtualMachine, logManager);

            BlockProcessor blockProcessor = new(
                specProvider,
                blockValidator,
                rewardCalculator,
                txProcessor,
                stateProvider,
                storageProvider,
                txPool,
                receiptStorage,
                NullWitnessCollector.Instance,
                logManager);

            RecoverSignatures   step      = new(ecdsa, txPool, specProvider, logManager);
            BlockchainProcessor processor = new(tree, blockProcessor, step, logManager,
                                                BlockchainProcessor.Options.Default);

            ITimerFactory    timerFactory     = Substitute.For <ITimerFactory>();
            NodeStatsManager nodeStatsManager = new(timerFactory, logManager);
            SyncPeerPool     syncPeerPool     = new(tree, nodeStatsManager, 25, logManager);

            StateProvider        devState       = new(trieStore, codeDb, logManager);
            StorageProvider      devStorage     = new(trieStore, devState, logManager);
            VirtualMachine       devEvm         = new(devState, devStorage, blockhashProvider, specProvider, logManager);
            TransactionProcessor devTxProcessor = new(specProvider, devState, devStorage, devEvm, logManager);

            BlockProcessor devBlockProcessor = new(
                specProvider,
                blockValidator,
                rewardCalculator,
                devTxProcessor,
                devState,
                devStorage,
                txPool,
                receiptStorage,
                NullWitnessCollector.Instance,
                logManager);

            BlockchainProcessor devChainProcessor = new(tree, devBlockProcessor, step, logManager,
                                                        BlockchainProcessor.Options.NoReceipts);
            TxPoolTxSource   transactionSelector = new(txPool, stateReader, logManager);
            DevBlockProducer producer            = new(
                transactionSelector,
                devChainProcessor,
                stateProvider, tree,
                processor,
                new BuildBlocksRegularly(TimeSpan.FromMilliseconds(50)).IfPoolIsNotEmpty(txPool),
                Timestamper.Default,
                specProvider,
                new MiningConfig(),
                logManager);

            SyncProgressResolver resolver = new(
                tree, receiptStorage, stateDb, new MemDb(), NullTrieNodeResolver.Instance, syncConfig, logManager);
            MultiSyncModeSelector selector     = new(resolver, syncPeerPool, syncConfig, logManager);
            Synchronizer          synchronizer = new(
                dbProvider,
                MainnetSpecProvider.Instance,
                tree,
                NullReceiptStorage.Instance,
                blockValidator,
                sealValidator,
                syncPeerPool,
                nodeStatsManager,
                StaticSelector.Full,
                syncConfig,
                logManager);
            SyncServer syncServer = new(
                stateDb,
                codeDb,
                tree,
                receiptStorage,
                Always.Valid,
                Always.Valid,
                syncPeerPool,
                selector,
                syncConfig,
                NullWitnessCollector.Instance,
                logManager);

            ManualResetEventSlim waitEvent = new();

            tree.NewHeadBlock += (_, _) => waitEvent.Set();

            if (index == 0)
            {
                _genesis = Build.A.Block.Genesis.WithStateRoot(stateProvider.StateRoot).TestObject;
                producer.Start();
            }

            syncPeerPool.Start();
            synchronizer.Start();
            processor.Start();
            tree.SuggestBlock(_genesis);

            if (!waitEvent.Wait(1000))
            {
                throw new Exception("No genesis");
            }

            SyncTestContext context = new();

            context.Ecdsa = ecdsa;
            context.BlockchainProcessor = processor;
            context.PeerPool            = syncPeerPool;
            context.StateProvider       = stateProvider;
            context.Synchronizer        = synchronizer;
            context.SyncServer          = syncServer;
            context.Tree          = tree;
            context.BlockProducer = producer;
            context.TxPool        = txPool;
            context.Logger        = logger;
            return(context);
        }
示例#52
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StdRowLockSemaphore"/> class.
 /// </summary>
 /// <param name="tablePrefix">The table prefix.</param>
 /// <param name="schedName">the scheduler name</param>
 /// <param name="selectWithLockSQL">The select with lock SQL.</param>
 /// <param name="dbProvider"></param>
 public StdRowLockSemaphore(string tablePrefix, string schedName, string selectWithLockSQL, IDbProvider dbProvider)
     : base(tablePrefix, schedName, selectWithLockSQL ?? SelectForLock, InsertLock, dbProvider)
 {
 }
 public UserTaskRepository(IDbProvider dataProvider) : base(dataProvider)
 {
 }
示例#54
0
 public DbFactory(IDbProvider dbProvider, IConnectionString connectionString)
 {
     DbProvider        = dbProvider;
     _connectionString = connectionString;
 }
 public ReadOnlyTxProcessorSource(IDbProvider dbProvider, IBlockTree blockTree, ISpecProvider specProvider, ILogManager logManager)
 {
     _environment = new ReadOnlyTxProcessingEnv(new ReadOnlyDbProvider(dbProvider, false), new ReadOnlyBlockTree(blockTree), specProvider, logManager);
 }
示例#56
0
        public virtual async Task <INdmCapabilityConnector> InitAsync(
            IConfigProvider configProvider,
            IDbProvider dbProvider,
            string baseDbPath,
            IBlockTree blockTree,
            ITxPool txPool,
            ISpecProvider specProvider,
            IReceiptStorage receiptStorage,
            IWallet wallet,
            IFilterStore filterStore,
            IFilterManager filterManager,
            ITimestamper timestamper,
            IEthereumEcdsa ecdsa,
            IRpcModuleProvider rpcModuleProvider,
            IKeyStore keyStore,
            IJsonSerializer jsonSerializer,
            ICryptoRandom cryptoRandom,
            IEnode enode,
            INdmConsumerChannelManager consumerChannelManager,
            INdmDataPublisher dataPublisher,
            IGrpcServer grpcServer,
            INodeStatsManager nodeStatsManager,
            IProtocolsManager protocolsManager,
            IProtocolValidator protocolValidator,
            IMessageSerializationService messageSerializationService,
            bool enableUnsecuredDevWallet,
            IWebSocketsManager webSocketsManager,
            ILogManager logManager,
            IBlockProcessor blockProcessor,
            IJsonRpcClientProxy?jsonRpcClientProxy,
            IEthJsonRpcClientProxy?ethJsonRpcClientProxy,
            IHttpClient httpClient,
            IMonitoringService monitoringService,
            IBloomStorage bloomStorage)
        {
            _logger = logManager?.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager));
            INdmConfig ndmConfig = configProvider.GetConfig <INdmConfig>();

            if (!ndmConfig.Enabled)
            {
                // can we not even call it here? // can be step and use the subsystems
                return(NullNdmCapabilityConnector.Instance);
            }

            (NdmConfig config, INdmServices services, INdmFaucet faucet, IEthRequestService ethRequestService, IAccountService accountService, IConsumerService consumerService, Address consumerAddress, Address providerAddress) = await PreInitAsync(
                configProvider,
                dbProvider,
                baseDbPath,
                blockTree,
                txPool,
                specProvider,
                receiptStorage,
                wallet,
                filterStore,
                filterManager,
                timestamper,
                ecdsa,
                rpcModuleProvider,
                keyStore,
                jsonSerializer,
                cryptoRandom,
                enode,
                consumerChannelManager,
                dataPublisher,
                grpcServer,
                enableUnsecuredDevWallet,
                webSocketsManager,
                logManager,
                blockProcessor,
                jsonRpcClientProxy,
                ethJsonRpcClientProxy,
                httpClient,
                monitoringService,
                bloomStorage);

            NdmSubprotocolFactory subprotocolFactory = new NdmSubprotocolFactory(messageSerializationService, nodeStatsManager,
                                                                                 logManager, accountService, consumerService, consumerChannelManager, ecdsa, wallet, faucet,
                                                                                 enode.PublicKey, providerAddress, consumerAddress, config.VerifyP2PSignature);
            ProtocolHandlerFactory protocolHandlerFactory = new ProtocolHandlerFactory(subprotocolFactory, protocolValidator,
                                                                                       ethRequestService, logManager);

            if (ndmConfig.ProviderAddress == null)
            {
                return(NullNdmCapabilityConnector.Instance);
            }

            NdmCapabilityConnector capabilityConnector = new NdmCapabilityConnector(
                protocolsManager,
                protocolHandlerFactory,
                accountService,
                logManager,
                new Address(ndmConfig.ProviderAddress));

            return(capabilityConnector);
        }