public void LocalSessionFactoryObjectWithDbProviderAndProperties() { IDbProvider dbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient"); dbProvider.ConnectionString = "Data Source=(local);Database=Spring;Trusted_Connection=false"; LocalSessionFactoryObject sfo = new LocalSessionFactoryObject(); sfo.DbProvider = dbProvider; sfo.ApplicationContext = new StaticApplicationContext(); IDictionary properties = new Hashtable(); properties.Add(Environment.Dialect, typeof(MsSql2000Dialect).AssemblyQualifiedName); properties.Add(Environment.ConnectionDriver, typeof(SqlClientDriver).AssemblyQualifiedName); properties.Add(Environment.ConnectionProvider, typeof(DriverConnectionProvider).AssemblyQualifiedName); #if NH_2_1 // since 2.1. "hbm2ddl.keywords = 'keywords'" is the default which causes the SessionFactory to connect to the db upon creation // we don't want this in this unit test properties.Add(Environment.Hbm2ddlKeyWords, "none"); #endif sfo.HibernateProperties = properties; sfo.AfterPropertiesSet(); Assert.IsNotNull(sfo.Configuration); Assert.AreEqual(sfo.Configuration.Properties[Environment.ConnectionProvider], typeof(DriverConnectionProvider).AssemblyQualifiedName); Assert.AreEqual(sfo.Configuration.Properties[Environment.ConnectionDriver], typeof(SqlClientDriver).AssemblyQualifiedName); Assert.AreEqual(sfo.Configuration.Properties[Environment.Dialect], typeof(MsSql2000Dialect).AssemblyQualifiedName); #if NH_2_1 Assert.AreEqual(sfo.Configuration.Properties[Environment.ProxyFactoryFactoryClass], typeof(ProxyFactoryFactory).AssemblyQualifiedName); // Spring's IBytecodeProvider should be the default // Assert.AreEqual(typeof(BytecodeProvider), Environment.BytecodeProvider.GetType(), "default IBytecodeProvider was not Spring's BytecodeProvider"); #endif }
public void OracleTest() { //Data Source=XE;User ID=hr;Unicode=True IDbProvider dbProvider = DbProviderFactory.GetDbProvider("System.Data.OracleClient"); dbProvider.ConnectionString = "Data Source=XE;User ID=hr;Password=hr;Unicode=True"; AdoTemplate adoTemplate = new AdoTemplate(dbProvider); decimal count = (decimal)adoTemplate.ExecuteScalar(CommandType.Text, "select count(*) from emp"); Assert.AreEqual(14, count); EmpProc empProc = new EmpProc(dbProvider); IDictionary dict = empProc.GetEmployees(); foreach (DictionaryEntry entry in dict) { Console.WriteLine("Key = " + entry.Key + ", Value = " + entry.Value); } IList employeeList = dict["employees"] as IList; foreach (Employee employee in employeeList) { Console.WriteLine(employee); } }
public void CanSetConfigurationAndProperties() { IDbProvider dbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient"); dbProvider.ConnectionString = "Data Source=(local);Database=Spring;Trusted_Connection=false"; DelegatingLocalSessionFactoryObject lsfo = new DelegatingLocalSessionFactoryObject(); lsfo.DbProvider = dbProvider; lsfo.ApplicationContext = new StaticApplicationContext(); IDictionary properties = new Hashtable(); properties.Add(NhCfg.Environment.Dialect, typeof(MsSql2000Dialect).AssemblyQualifiedName); properties.Add(NhCfg.Environment.ConnectionDriver, typeof(SqlClientDriver).AssemblyQualifiedName); properties.Add(NhCfg.Environment.ConnectionProvider, typeof(DriverConnectionProvider).AssemblyQualifiedName); properties.Add(NhCfg.Environment.Hbm2ddlKeyWords, "none"); lsfo.HibernateProperties = properties; lsfo.AfterPropertiesSet(); Assert.IsNotNull(lsfo.Configuration); Assert.AreEqual(lsfo.Configuration.Properties[NhCfg.Environment.ConnectionProvider], typeof(DriverConnectionProvider).AssemblyQualifiedName); Assert.AreEqual(lsfo.Configuration.Properties[NhCfg.Environment.ConnectionDriver], typeof(SqlClientDriver).AssemblyQualifiedName); Assert.AreEqual(lsfo.Configuration.Properties[NhCfg.Environment.Dialect], typeof(MsSql2000Dialect).AssemblyQualifiedName); Assert.AreEqual(lsfo.Configuration.Properties[NhCfg.Environment.ProxyFactoryFactoryClass], typeof(ProxyFactoryFactory).AssemblyQualifiedName); }
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 }
public void SetUpMocks() { mocks = new MockRepository(); provider = (IDbProvider)mocks.DynamicMock(typeof(IDbProvider)); IDbConnection connection = (IDbConnection)mocks.DynamicMock(typeof(IDbConnection)); Expect.Call(provider.CreateConnection()).Return(connection); // Creating a query (setting DbProvider property) // will call new DbParameters(IDbProvider), which is a real pain to mock. // to store the declared parameters. command = (IDbCommand)mocks.DynamicMock(typeof(IDbCommand)); //This IDbCommand is used as a container for the underlying parameter collection. Expect.Call(provider.CreateCommand()).Return(command); //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. Expect.Call(command.Parameters).Return(dbParameters.DataParameterCollection); Expect.Call(provider.CreateCommand()).Return(command); // done with init of DbParameters mock/stubbing }
private IDbProvider GetDbProvider(string connectionString) { IDbProvider provider = DbProviderFactory.GetDbProvider("System.Data.SqlClient"); provider.ConnectionString = connectionString; return(provider); }
public void LocalSessionFactoryObjectWithDbProviderAndProperties() { IDbProvider dbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient"); dbProvider.ConnectionString = "Data Source=(local);Database=Spring;Trusted_Connection=false"; LocalSessionFactoryObject sfo = new LocalSessionFactoryObject(); sfo.DbProvider = dbProvider; sfo.ApplicationContext = new StaticApplicationContext(); Dictionary <string, string> properties = new Dictionary <string, string>(); properties.Add(Environment.Dialect, typeof(MsSql2000Dialect).AssemblyQualifiedName); properties.Add(Environment.ConnectionDriver, typeof(SqlClientDriver).AssemblyQualifiedName); properties.Add(Environment.ConnectionProvider, typeof(DriverConnectionProvider).AssemblyQualifiedName); // since 2.1. "hbm2ddl.keywords = 'keywords'" is the default which causes the SessionFactory to connect to the db upon creation // we don't want this in this unit test properties.Add(Environment.Hbm2ddlKeyWords, "none"); sfo.HibernateProperties = properties; sfo.AfterPropertiesSet(); Assert.IsNotNull(sfo.Configuration); Assert.AreEqual(sfo.Configuration.Properties[Environment.ConnectionProvider], typeof(DriverConnectionProvider).AssemblyQualifiedName); Assert.AreEqual(sfo.Configuration.Properties[Environment.ConnectionDriver], typeof(SqlClientDriver).AssemblyQualifiedName); Assert.AreEqual(sfo.Configuration.Properties[Environment.Dialect], typeof(MsSql2000Dialect).AssemblyQualifiedName); Assert.Throws <KeyNotFoundException>(() => { var x = sfo.Configuration.Properties[Environment.ProxyFactoryFactoryClass]; }, "ProxyFactoryFactory should not be explicitly set!"); Assert.AreNotEqual(typeof(BytecodeProvider), Environment.BytecodeProvider.GetType(), "default IBytecodeProvider should not be Spring's BytecodeProvider!"); }
public void Test() { IDbProvider dbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient"); dbProvider.ConnectionString = @"Data Source=MARKT60\SQL2005;Database=Spring;User ID=springqa;Password=springqa;Trusted_Connection=False"; TestObjectStoredProc sp = new TestObjectStoredProc(dbProvider); IList <TestObject> testObjectList = sp.GetByName("George"); Assert.IsNotNull(testObjectList); TestObjectandVacationStoredProc vsp = new TestObjectandVacationStoredProc(dbProvider); System.Collections.IDictionary outParams = vsp.ExecStoreProc("George"); testObjectList = outParams["testObjectRowMapper"] as IList <TestObject>; Assert.IsNotNull(testObjectList); Assert.AreEqual(1, testObjectList.Count); IList <Vacation> vacationList = outParams["vacationRowMapper"] as IList <Vacation>; Assert.IsNotNull(vacationList); Assert.AreEqual(2, vacationList.Count); }
/// <summary> /// /// </summary> /// <param name="id">平台配置对象中的id</param> public DbProvider(string id) { DsConfigurationManager dm = new DsConfigurationManager(); var c = dm.DsRootConfigurationSection.Connections.OfType <ConnectionElement>().Where(o => o.ID == id).FirstOrDefault(); dbprovider = DbProviderFactory.GetDbProvider(c.Provider); dbprovider.ConnectionString = c.ConnectionString; }
public void DeclareParameterAfterCompile() { TestAdoOperation operation = new TestAdoOperation(); operation.DbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient"); operation.Sql = "select * from table"; operation.Compile(); IDbParameters parameters = new DbParameters(operation.DbProvider); operation.DeclaredParameters = parameters; }
private static AdoTemplate CreateTemplate(ConnectionStringSettings connectionStringSettings) { var dbProvider = DbProviderFactory.GetDbProvider(connectionStringSettings.ProviderName); dbProvider.ConnectionString = connectionStringSettings.ConnectionString; return(new AdoTemplate(dbProvider) { DataReaderWrapperType = typeof(NullMappingDataReader), CommandTimeout = 120 }); }
private static SpringBaseDao CreateDao(string connectionString) { IDbProvider dbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient"); dbProvider.ConnectionString = connectionString; SpringBaseDao springBaseDao = new SpringBaseDao(dbProvider, typeof(NamedNullMappingDataReader)); springBaseDao.AdoTemplate.CommandTimeout = 500; return(springBaseDao); }
public void QueryWithMapper() { IDbProvider dbProvider = DbProviderFactory.GetDbProvider("SybaseAse-15"); dbProvider.ConnectionString = "Data Source='MARKT60';Port='5000';UID='sa';PWD='';Database='pubs2';"; PubDao pubDao = new PubDao(dbProvider); IList <Sale> sales = pubDao.GetSales("5023"); Assert.AreEqual(50, sales.Count); }
public void DeclareParameterAfterCompile() { TestAdoOperation operation = new TestAdoOperation(); operation.DbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient"); operation.Sql = "select * from table"; operation.Compile(); IDbParameters parameters = new DbParameters(operation.DbProvider); Assert.Throws <InvalidDataAccessApiUsageException>(() => operation.DeclaredParameters = parameters); }
public void QueryWithMapperODBC() { IDbProvider dbProvider = DbProviderFactory.GetDbProvider("Odbc-2.0"); dbProvider.ConnectionString = "Driver={Adaptive Server Enterprise};server=MARKT60;port=5000;Database=pubs2;uid=sa;pwd=;"; PubDao pubDao = new PubDao(dbProvider); IList <Sale> sales = pubDao.GetSales("5023"); Assert.AreEqual(50, sales.Count); }
public void TooFewParameters() { TestAdoOperation operation = new TestAdoOperation(); operation.DbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient"); operation.Sql = "select * from table"; IDbParameters parameters = new DbParameters(operation.DbProvider); parameters.Add("name"); operation.DeclaredParameters = parameters; operation.Compile(); operation.ValidateParams(null); }
public void Setup() { _dbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient"); _dbProvider.ConnectionString = @"Data Source=SPRINGQA;Database=Spring;User ID=springqa;Password=springqa;Trusted_Connection=False"; IDbCommand command = _dbProvider.CreateCommand(); command.Connection = _dbProvider.CreateConnection(); ClearTestData(command); CreateTestData(command); }
public void TooFewParameters() { TestAdoOperation operation = new TestAdoOperation(); operation.DbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient"); operation.Sql = "select * from table"; IDbParameters parameters = new DbParameters(operation.DbProvider); parameters.Add("name"); operation.DeclaredParameters = parameters; operation.Compile(); Assert.Throws <InvalidDataAccessApiUsageException>(() => operation.ValidateParams(null)); }
public void InstallMSSQLDatabase() { IDbProvider dbProvider = DbProviderFactory.GetDbProvider("SqlServer-2.0"); AdoTemplate ado = new AdoTemplate(dbProvider); // (re-)create database(s) dbProvider.ConnectionString = DBConnection.Replace("$DATABASE$", "master"); SimpleAdoTestUtils.ExecuteSqlScript(ado, GetResource(this, "RecreateDatabases.sql")); // create tables dbProvider.ConnectionString = DBConnection.Replace("$DATABASE$", "Spring"); SimpleAdoTestUtils.ExecuteSqlScript(ado, GetResource(this, "Data.NHibernate/creditdebit.sql")); SimpleAdoTestUtils.ExecuteSqlScript(ado, GetResource(this, "Data.NHibernate/testObject.sql")); }
/// <summary> /// Gets the Spring IDbProvider given the ISessionFactory. /// </summary> /// <remarks>The matching is performed by comparing the assembly qualified /// name string of the hibernate Driver.ConnectionType to those in /// the DbProviderFactory definitions. No connections are created /// in performing this comparison.</remarks> /// <param name="sessionFactory">The session factory.</param> /// <returns>The corresponding IDbProvider, null if no mapping was found.</returns> /// <exception cref="InvalidOperationException">If DbProviderFactory's ApplicaitonContext is not /// an instance of IConfigurableApplicaitonContext.</exception> public static IDbProvider GetDbProvider(ISessionFactory sessionFactory) { ISessionFactoryImplementor sfi = sessionFactory as ISessionFactoryImplementor; if (sfi != null) { IConnectionProvider cp = sfi.ConnectionProvider; if (cp != null) { IConfigurableApplicationContext ctx = DbProviderFactory.ApplicationContext as IConfigurableApplicationContext; if (ctx == null) { throw new InvalidOperationException( "Implementations of IApplicationContext must also implement IConfigurableApplicationContext"); } DriverBase db = cp.Driver as DriverBase; if (db != null) { Type hibCommandType = db.CreateCommand().GetType(); var providerNames = ctx.GetObjectNamesForType(typeof(DbProvider), true, false); string hibCommandAQN = hibCommandType.AssemblyQualifiedName; string hibCommandAQNWithoutVersion = hibCommandType.FullName + ", " + hibCommandType.Assembly.GetName().Name; foreach (string providerName in providerNames) { IObjectDefinition objectdef = ctx.ObjectFactory.GetObjectDefinition(providerName); ConstructorArgumentValues ctorArgs = objectdef.ConstructorArgumentValues; ConstructorArgumentValues.ValueHolder vh = ctorArgs.NamedArgumentValues["dbmetadata"] as ConstructorArgumentValues.ValueHolder; IObjectDefinition od = ((ObjectDefinitionHolder)vh.Value).ObjectDefinition; ConstructorArgumentValues dbmdCtorArgs = od.ConstructorArgumentValues; string commandType = dbmdCtorArgs.GetArgumentValue("commandType", typeof(string)).Value as string; if (hibCommandAQN.Equals(commandType) || hibCommandAQNWithoutVersion.Equals(commandType)) { IDbProvider prov = DbProviderFactory.GetDbProvider(providerName); return(prov); } } } else { log.Info("Could not derive IDbProvider from SessionFactory"); } } } return(null); }
public void DeriveParams() { IDbProvider dbProvider = DbProviderFactory.GetDbProvider("SybaseAse-15"); dbProvider.ConnectionString = "Data Source='MARKT60';Port='5000';UID='sa';PWD='';Database='pubs2';"; AdoTemplate adoTemplate = new AdoTemplate(dbProvider); IDataParameter[] derivedParameters = adoTemplate.DeriveParameters("@sp_hello", true); if (derivedParameters.Length == 0) { Console.WriteLine("Derived Parameters = 0!!!!"); } for (int i = 0; i < derivedParameters.Length; i++) { Console.WriteLine("Parameter " + i + ", Name = " + derivedParameters[i].ParameterName + ", Value = " + derivedParameters[i].Value); } }
public void TxTemplate() { IDbProvider dbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient"); dbProvider.ConnectionString = @"Data Source=SPRINGQA;Initial Catalog=CreditsAndDebits;User ID=springqa; Password=springqa"; //IPlatformTransactionManager tm = new ServiceDomainPlatformTransactionManager(); //IPlatformTransactionManager tm = new TxScopeTransactionManager(); IPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider); AdoTemplate adoTemplate = new AdoTemplate(dbProvider); TransactionTemplate tt = new TransactionTemplate(tm); tt.PropagationBehavior = TransactionPropagation.Required; tt.Execute(delegate(ITransactionStatus status) { if (System.Transactions.Transaction.Current != null) { Console.WriteLine("tx 1 id = " + System.Transactions.Transaction.Current.TransactionInformation.LocalIdentifier); } Console.WriteLine("tx 1 'IsNewTransaction' = " + status.IsNewTransaction); adoTemplate.ExecuteNonQuery(CommandType.Text, "insert into Credits (CreditAmount) VALUES (@amount)", "amount", DbType.Decimal, 0, 444); TransactionTemplate tt2 = new TransactionTemplate(tm); tt2.PropagationBehavior = TransactionPropagation.RequiresNew; tt2.Execute(delegate(ITransactionStatus status2) { if (System.Transactions.Transaction.Current != null) { Console.WriteLine("tx 2 = " + System.Transactions.Transaction.Current.TransactionInformation.LocalIdentifier); } Console.WriteLine("tx 2 'IsNewTransaction' = " + status2.IsNewTransaction); adoTemplate.ExecuteNonQuery(CommandType.Text, "insert into dbo.Debits (DebitAmount) VALUES (@amount)", "amount", DbType.Decimal, 0, 555); //throw new ArithmeticException("can't do the math."); status2.SetRollbackOnly(); return(null); }); if (System.Transactions.Transaction.Current != null) { Console.WriteLine("tx id1 = " + System.Transactions.Transaction.Current.TransactionInformation.LocalIdentifier); } return(null); }); }
public void SetUp() { IDbProvider dbProvider = DbProviderFactory.GetDbProvider("SqlServer-1.1"); dbProvider.ConnectionString = "Server=(local);Integrated Security=no;User ID=springqa;PWD=springqa;initial catalog=SpringAir;"; dao = new AircraftDao(); dao.DbProvider = dbProvider; /* * ReflectiveDbConnectionFactory connectionfactory = new ReflectiveDbConnectionFactory(); * connectionfactory.ConnectionType = typeof (SqlConnection); * connectionfactory.ConnectionString = * "Server=(local)\\Spring;Integrated Security=no;User ID=sa;PWD=spring;initial catalog=SpringAir;"; * * dao = new AircraftDao(); * dao.ConnectionFactory = connectionfactory; * dao.CommandType = typeof (SqlCommand); * dao.AircraftMapper = new AircraftMapper(); */ }
public void Test() { //IDbProvider dbProvider = DbProviderFactory.GetDbProvider("SybaseAse1.15"); // dbProvider.ConnectionString = "Data Source='MARKT60';Port='5000';UID='sa';PWD='';Database='pubs2';"; IDbProvider dbProvider = DbProviderFactory.GetDbProvider("Odbc-2.0"); dbProvider.ConnectionString = "Driver={Adaptive Server Enterprise};server=MARKT60;port=5000;Database=pubs2;uid=sa;pwd=;"; Assert.IsNotNull(dbProvider); AdoTemplate adoTemplate = new AdoTemplate(dbProvider); IList <string> authorList = adoTemplate.QueryWithRowMapperDelegate <string>(CommandType.Text, "select au_lname from authors", delegate(IDataReader dataReader, int rowNum) { return(dataReader.GetString(0)); }); foreach (string s in authorList) { Console.WriteLine(s); } Assert.IsTrue(authorList.Count > 0); }
public void SqlServerTest() { string errorCode = "544"; string[] errorCodes = new string[4] { "544", "2627", "8114", "8115" }; //Array.IndexOf() //Array.Sort(errorCodes); foreach (string code in errorCodes) { Console.WriteLine(code); } //if (Array.BinarySearch(errorCodes, errorCode) >= 0) if (Array.IndexOf(errorCodes, errorCode) >= 0) { Console.WriteLine("yes"); } else { Assert.Fail("did not find error code"); } IDbProvider dbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient"); dbProvider.ConnectionString = @"Data Source=SPRINGQA;Initial Catalog=Spring;Persist Security Info=True;User ID=springqa;Password=springqa"; AdoTemplate adoTemplate = new AdoTemplate(dbProvider); try { adoTemplate.ExecuteNonQuery(CommandType.Text, "insert into Vacations (FirstName,LastName) values ('Jack','Doe')"); } catch (Exception e) { Console.Write(e); throw; } }
public TestDbProvider() { IDbProvider provider = DbProviderFactory.GetDbProvider("System.Data.SqlClient"); dbMetadata = provider.DbMetadata; }
public TestDbProvider() { IDbProvider provider = DbProviderFactory.GetDbProvider("SqlServer-1.1"); dbMetadata = provider.DbMetadata; }