Beispiel #1
0
 protected DatabaseBaseTest(DbAccessType type, bool asyncExecution, bool syncronised, params object[] additionalArguments)
 {
     //TestContext.CurrentContext.Test.Properties.Add("Type", type);
     AdditionalArguments = additionalArguments.Concat(new[] { asyncExecution ? "1" : "0", Synronised ? "1" : "0" }).ToArray();
     Type           = type;
     AsyncExecution = asyncExecution;
     Synronised     = syncronised;
 }
Beispiel #2
0
            public LocalRemotingStrategy(DbAccessType emulateDbType, DbConfig config, RemotingManager manager,
                                         string instanceName) : base(emulateDbType, config)
            {
                _manager = manager;
                var wrapper = _manager._subManager.GetWrapper(_manager._subManager.DbAccessType, instanceName);

                RemotingConsumerServer = new RemotingConsumerServer(() =>
                {
                    return(wrapper);
                });
            }
        /// <inheritdoc />
        public RemotingStrategyExternal(DbAccessType emulateDbType, DbConfig config) : base(emulateDbType, config)
        {
            ConnectionIds  = new ConcurrentDictionary <RemotingDbConnection, string>();
            TransactionIds = new ConcurrentDictionary <RemoteDbTransaction, string>();

            Events.ConnectionOpened += Events_ConnectionOpened;
            Events.ConnectionClosed += Events_ConnectionClosed;

            Events.TransactionCreated  += Events_TransactionCreated;
            Events.TransactionCommit   += Events_TransactionCommit;
            Events.TransactionRollback += Events_TransactionRollback;
        }
Beispiel #4
0
		public DbAccessLayer GetWrapper(DbAccessType type)
		{
			DbAccessLayer expectWrapper = null;
			var elementType = GetElementType();

			expectWrapper = _managers[type].GetWrapper(type);

			//if (elementType == DbAccessType.MsSql)
			//{
			//	expectWrapper = new MsSqlManager().GetWrapper();
			//}
			//else if (elementType == DbAccessType.SqLite)
			//{
			//	expectWrapper = new SqLiteManager().GetWrapper();
			//}

			_errorData = new StringBuilder();
			expectWrapper.RaiseEvents = true;
			expectWrapper.OnSelect += (sender, eventArg) =>
			{
				_errorData.AppendFormat(@"SELECT: \r\n{0}", eventArg.QueryDebugger);
				_errorData.AppendLine();
			};

			expectWrapper.OnDelete += (sender, eventArg) =>
			{
				_errorData.AppendFormat(@"DELETE: \r\n{0}", eventArg.QueryDebugger);
				_errorData.AppendLine();
			};

			expectWrapper.OnInsert += (sender, eventArg) =>
			{
				_errorData.AppendFormat(@"INSERT: \r\n{0}", eventArg.QueryDebugger);
				_errorData.AppendLine();
			};

			expectWrapper.OnUpdate += (sender, eventArg) =>
			{
				_errorData.AppendFormat(@"Update: \r\n{0}", eventArg.QueryDebugger);
				_errorData.AppendLine();
			};

			Assert.NotNull(expectWrapper, "This test cannot run as no Database Variable is defined");
			bool checkDatabase = expectWrapper.CheckDatabase();
			Assert.IsTrue(checkDatabase);

			expectWrapper.Config.ConstructorSettings.FileCollisonDetection = CollisonDetectionMode.Pessimistic;
			expectWrapper.Config.ConstructorSettings.CreateDebugCode = false;
			expectWrapper.Multipath = true;
			QueryDebugger.UseDefaultDatabase = expectWrapper.DatabaseStrategy;
			return expectWrapper;
		}
Beispiel #5
0
        /// <summary>
        ///     Create a DbAccessLayer that uses a Predefined type and Connection string
        /// </summary>
        public DbAccessLayer(DbAccessType dbAccessType, string connection, DbConfig config = null)
            : this(config)
        {
            if (dbAccessType == DbAccessType.Unknown)
            {
                throw new InvalidEnumArgumentException("dbAccessType", (int)DbAccessType.Unknown, typeof(DbAccessType));
            }

            DbAccessType = dbAccessType;
            Database     = new DefaultDatabaseAccess(new InstanceConnectionController());
            var database =
                GenerateStrategyFromExternal(ProviderCollection.FirstOrDefault(s => s.Key == dbAccessType).Value, connection);
            Database.Attach(database);
            DatabaseStrategy = database;
        }
Beispiel #6
0
        /// <inheritdoc />
        public string CreationCommand(DbAccessType accessType)
        {
            switch (accessType)
            {
            case DbAccessType.MsSql:
                return(CreateMsSql);

            case DbAccessType.MySql:
                return(CreateMySql);

            case DbAccessType.SqLite:
                return(CreateSqLite);

            default:
                throw new ArgumentOutOfRangeException(nameof(accessType), accessType, null);
            }
        }
Beispiel #7
0
        public DbAccessLayer GetWrapper(DbAccessType type, string testName)
        {
            if (ConfigurationManager.AppSettings["RDBMS.MySql.StartManagedServer"] == "True")
            {
                if (!MySqlConnectorInstance.Instance.HasStarted)
                {
                    MySqlConnectorInstance.Instance.CreateDatabaseFiles().Wait();
                    MySqlConnectorInstance.Instance.RunMySql();
                }
            }
            var dbname = string.Format("YAORM_TestDb_{0}", testName);

            if (_expectWrapper != null)
            {
                _expectWrapper.Database.CloseAllConnection();
            }

            //Darn MySql with only 64 chars?
            if (dbname.Length > 64)
            {
                dbname = dbname.Substring(dbname.Length - 64);
            }

            var redesginDatabase = string.Format(
                "DROP DATABASE IF EXISTS {0};",
                dbname);

            _expectWrapper = new DbAccessLayer(DbAccessType, ConnectionString, new DbConfig(true));
            _expectWrapper.ExecuteGenericCommand(_expectWrapper.Database.CreateCommand(redesginDatabase));
            _expectWrapper.ExecuteGenericCommand(
                _expectWrapper.Database.CreateCommand(string.Format("CREATE DATABASE {0};", dbname)));
            _expectWrapper = new DbAccessLayer(DbAccessType, string.Format(ConnectionString + "Database={0};", dbname));
            foreach (var databaseMeta in MetaManager.DatabaseMetas)
            {
                _expectWrapper.ExecuteGenericCommand(_expectWrapper.Database.CreateCommand(databaseMeta.Value.CreationCommand(DbAccessType)));
            }
            //_expectWrapper.ExecuteGenericCommand(_expectWrapper.Database.CreateCommand("CREATE PROC TestProcA " +
            //																		 "AS BEGIN " +
            //																		 "SELECT * FROM Users " +
            //																		 "END"));
            //_expectWrapper.ExecuteGenericCommand(_expectWrapper.Database.CreateCommand("CREATE PROC TestProcB @bigThen INT " +
            //																		 "AS BEGIN " +
            //																		 "SELECT * FROM Users us WHERE @bigThen > us.User_ID " +
            //																		 "END "));
            return(_expectWrapper);
        }
Beispiel #8
0
		public DbAccessLayer GetWrapper(DbAccessType type)
		{
			const string dbname = "testDB";
			if (expectWrapper != null)
			{
				expectWrapper.Database.CloseAllConnection();
			}

			var redesginDatabase = string.Format(
				"IF EXISTS (select * from sys.databases where name=\'{0}\') DROP DATABASE {0}",
				dbname);

			expectWrapper = new DbAccessLayer(DbAccessType, ConnectionString, null, new DbConfig(true));
			try
			{
				expectWrapper.ExecuteGenericCommand(expectWrapper.Database.CreateCommand(string.Format("ALTER DATABASE {0} SET SINGLE_USER WITH ROLLBACK IMMEDIATE ", dbname)));
			}
			catch (Exception)
			{
				Console.WriteLine("Db does not exist");
			}

			expectWrapper.ExecuteGenericCommand(expectWrapper.Database.CreateCommand(redesginDatabase));
			expectWrapper.ExecuteGenericCommand(expectWrapper.Database.CreateCommand(string.Format("CREATE DATABASE {0}", dbname)));

			expectWrapper = new DbAccessLayer(DbAccessType, string.Format(ConnectionString + "Initial Catalog={0};", dbname));
			expectWrapper.ExecuteGenericCommand(expectWrapper.Database.CreateCommand(UsersMeta.CreateMsSql));
			expectWrapper.ExecuteGenericCommand(expectWrapper.Database.CreateCommand(BookMeta.CreateMsSQl));
			expectWrapper.ExecuteGenericCommand(expectWrapper.Database.CreateCommand(ImageMeta.CreateMsSQl));

			expectWrapper.ExecuteGenericCommand(expectWrapper.Database.CreateCommand("CREATE PROC TestProcA " +
																					 "AS BEGIN " +
																					 "SELECT * FROM Users " +
																					 "END"));

			expectWrapper.ExecuteGenericCommand(expectWrapper.Database.CreateCommand("CREATE PROC TestProcB @bigThen INT " +
																					 "AS BEGIN " +
																					 "SELECT * FROM Users us WHERE @bigThen > us.User_ID " +
																					 "END "));


			return expectWrapper;
		}
Beispiel #9
0
		public DbAccessLayer GetWrapper(DbAccessType type)
		{
			if (expectWrapper != null)
			{
				expectWrapper.Database.CloseAllConnection();
			}

			//string dbname = "testDB";
			//var sqlLiteFileName = dbname + ".sqlite";

			var tempPath = Path.GetTempFileName();


			expectWrapper = new DbAccessLayer(DbAccessType, string.Format(ConnectionString, tempPath));
			expectWrapper.ExecuteGenericCommand(expectWrapper.Database.CreateCommand(UsersMeta.CreateSqLite));
			expectWrapper.ExecuteGenericCommand(expectWrapper.Database.CreateCommand(BookMeta.CreateSqLite));
			expectWrapper.ExecuteGenericCommand(expectWrapper.Database.CreateCommand(ImageMeta.CreateSqLite));
			return expectWrapper;
		}
Beispiel #10
0
        public DbAccessLayer GetWrapper(DbAccessType type, string testName)
        {
            _dbname = string.Format("YAORM_2_TestDb_Test_MsSQL_{0}", testName);
            if (_expectWrapper != null)
            {
                _expectWrapper.Database.CloseAllConnection();
            }

            var dbConfig = new DbConfig(true);

            dbConfig.EnableInstanceThreadSafety = true;
            _expectWrapper = new DbAccessLayer(DbAccessType, ConnectionString, dbConfig);

            var redesginDatabase = string.Format(
                "IF EXISTS (select * from sys.databases where name=\'{0}\') DROP DATABASE {0}",
                _dbname);

            _expectWrapper.ExecuteGenericCommand(_expectWrapper.Database.CreateCommand(redesginDatabase));
            _expectWrapper.ExecuteGenericCommand(
                _expectWrapper.Database.CreateCommand(string.Format("CREATE DATABASE {0}", _dbname)));

            _expectWrapper = new DbAccessLayer(DbAccessType,
                                               string.Format(ConnectionString + "Initial Catalog={0};", _dbname), dbConfig);

            foreach (var databaseMeta in MetaManager.DatabaseMetas)
            {
                _expectWrapper.ExecuteGenericCommand(_expectWrapper.Database.CreateCommand(databaseMeta.Value.CreationCommand(DbAccessType)));
            }

            _expectWrapper.ExecuteGenericCommand(_expectWrapper.Database.CreateCommand("CREATE PROC TestProcA " +
                                                                                       "AS BEGIN " +
                                                                                       "SELECT * FROM Users " +
                                                                                       "END"));

            _expectWrapper.ExecuteGenericCommand(
                _expectWrapper.Database.CreateCommand("CREATE PROC TestProcB @bigThen INT " +
                                                      "AS BEGIN " +
                                                      "SELECT * FROM Users us WHERE @bigThen > us.User_ID " +
                                                      "END "));


            return(_expectWrapper);
        }
Beispiel #11
0
        /// <summary>
        /// 获取数据连接对象
        /// </summary>
        /// <param name="accessType">数据库类型:读/写,默认使用写库</param>
        /// <returns></returns>
        public IDbConnection GetDbConnection(DbAccessType accessType = DbAccessType.Write)
        {
            IDbConnection conn = null;

            if (OpenRwSeparate && accessType == DbAccessType.Read)
            {
                try
                {
                    conn = GetReadSqlConn();
                }
                catch
                {
                    conn = GetSqlConnection(_dbWriteConnectInfo);
                }
            }
            else
            {
                conn = GetSqlConnection(_dbWriteConnectInfo);
            }
            return(conn);
        }
Beispiel #12
0
        public DbAccessLayer GetWrapper(DbAccessType type, string testName)
        {
            if (_expectWrapper != null)
            {
                _expectWrapper.Database.CloseAllConnection();
            }

            SqLiteInteroptWrapper.EnsureSqLiteInteropt();
            //string dbname = "testDB";
            //var sqlLiteFileName = dbname + ".sqlite";

            var sqLiteConnection = Environment.ExpandEnvironmentVariables(ConfigurationManager
                                                                          .ConnectionStrings["RDBMS.SqLite.DefaultConnection"].ConnectionString);
            var connectionRegex = new Regex("Data Source=(.*);").Match(sqLiteConnection);

            _dbFilePath = Path.Combine(connectionRegex.Groups[1].Value, string.Format("YAORM_SqLite_{0}.db", testName));
            var connection = sqLiteConnection.Replace(connectionRegex.Groups[1].Value, _dbFilePath);

            if (File.Exists(_dbFilePath))
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                File.Delete(_dbFilePath);
            }

            File.Create(_dbFilePath).Dispose();

            //var file = MemoryMappedFile.CreateNew(dbname, 10000, MemoryMappedFileAccess.ReadWrite);

            //tempPath = Path.GetTempFileName() + dbname + "sqLite";

            _expectWrapper = new DbAccessLayer(new DataAccess.SqLite.SqLiteStrategy(connection), new DbConfig(true));
            foreach (var databaseMeta in MetaManager.DatabaseMetas)
            {
                _expectWrapper.ExecuteGenericCommand(_expectWrapper.Database.CreateCommand(databaseMeta.Value.CreationCommand(DbAccessType)));
            }
            return(_expectWrapper);
        }
Beispiel #13
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="emulateDbType"></param>
 /// <param name="config"></param>
 public RemotingStrategy(DbAccessType emulateDbType, DbConfig config)
 {
     Config         = config;
     SourceDatabase = DbAccessType.Remoting | emulateDbType;
     Events         = new RemotingStrategyEvents();
 }
 public QueryBuilderTests(DbAccessType type, bool asyncExecution, bool syncronised, bool asyncEnumeration)
     : base(type, asyncExecution, syncronised, asyncEnumeration)
 {
     _asyncEnumeration = asyncEnumeration;
 }
Beispiel #15
0
 public SelectionTests(DbAccessType type, bool egarLoading, bool asyncExecution, bool syncronised) : base(type, asyncExecution, syncronised, egarLoading.ToString())
 {
     _egarLoading = egarLoading;
 }
 public CheckWrapperDatabaseBaseTests(DbAccessType type, bool asyncExecution, bool syncronised) : base(type, asyncExecution, syncronised)
 {
 }
Beispiel #17
0
 public static void AddManager(DbAccessType type, IManager manager)
 {
     _managers.Add(type, manager);
 }
Beispiel #18
0
 /// <inheritdoc />
 public InsertTests(DbAccessType type, bool asyncExecution, bool syncronised) : base(type, asyncExecution, syncronised)
 {
 }
Beispiel #19
0
 /// <inheritdoc />
 public UpdateRefreshTests(DbAccessType type, bool asyncExecution, bool syncronised) : base(type, asyncExecution, syncronised)
 {
 }
Beispiel #20
0
		/// <summary>
		///     Creates an instance based on a Ctor injection or Reflection loading
		///		or when using a MsCoreLib type direct enumeration
		/// </summary>
		/// <returns></returns>
		public static object CreateInstance(DbClassInfoCache classInfo,
			IDataRecord reader,
			out bool fullLoaded,
			DbAccessType? accessType = null)
		{
			if (classInfo.Type.Assembly == MsCoreLibAssembly && reader.FieldCount == 1)
			{
				fullLoaded = true;
				return reader.GetValue(0);
			}

			if (classInfo.Factory != null)
			{
				fullLoaded = classInfo.FullFactory;
				return classInfo.Factory(reader);
			}

			var objectFactorys = classInfo.Constructors.Where(s =>
				s.Arguments.Count == 1
				&& s.Arguments.First().Type == typeof(IDataRecord))
				.ToArray();

			var constructor = objectFactorys.FirstOrDefault(s =>
				s.Attributes.Any(f =>
					f.Attribute is ObjectFactoryMethodAttribute
					&& (!accessType.HasValue || ((ObjectFactoryMethodAttribute) f.Attribute).TargetDatabase == accessType.Value)));

			if (constructor == null)
				constructor = objectFactorys.FirstOrDefault();

			//maybe single ctor with param

			if (constructor != null)
			{
				if (constructor.Arguments.Count == 1 && constructor.Arguments.First().Type == typeof(IDataRecord))
				{
					classInfo.FullFactory = true;
					classInfo.Factory = s => constructor.Invoke(new object[] {s});
					return CreateInstance(classInfo, reader, out fullLoaded, accessType);
				}
			}
			else
			{
				//check for a Factory mehtod
				var factory =
					classInfo.Mehtods
						.FirstOrDefault(s => s.Attributes.Any(f => f.Attribute is ObjectFactoryMethodAttribute));

				if (factory != null)
				{
					if (factory.MethodInfo.IsStatic)
					{
						var methodInfo = factory.MethodInfo as MethodInfo;
						if (methodInfo != null)
						{
							var returnType = methodInfo.ReturnParameter;

							if (returnType != null && returnType.ParameterType == classInfo.Type)
							{
								if (factory.Arguments.Count == 1 &&
								    factory.Arguments.First().Type == typeof(IDataRecord))
								{
									classInfo.FullFactory = true;
									classInfo.Factory = s => factory.Invoke(new object[] {reader});
									return CreateInstance(classInfo, reader, out fullLoaded, accessType);
								}
							}
						}
					}
				}
			}

			var emptyCtor = classInfo.Constructors.FirstOrDefault(f => !f.Arguments.Any());

			if (emptyCtor == null)
			{
				throw new NotSupportedException(
					"You have to define ether an ObjectFactoryMethod as static or constructor with and IDataReader or an constructor without any arguments");
			}

			classInfo.FullFactory = false;
			classInfo.Factory = s => emptyCtor.Invoke(new object[0]);
			return CreateInstance(classInfo, reader, out fullLoaded, accessType);
		}
Beispiel #21
0
 public QueryBuilderTests(DbAccessType type, bool asyncExecution, bool syncronised, bool asyncEnumeration, EnumerationMode enumerationMode)
     : base(type, asyncExecution, syncronised, enumerationMode, asyncEnumeration)
 {
     _enumerationMode  = enumerationMode;
     _asyncEnumeration = asyncEnumeration;
 }
Beispiel #22
0
		public PagerUnitTest(DbAccessType type)
		{
			_type = type;
		}
Beispiel #23
0
 public EventTest(DbAccessType type, bool asyncExecution, bool syncronised) : base(type, asyncExecution, syncronised)
 {
 }
Beispiel #24
0
		public static object ReflectionPropertySet(
			DbConfig config,
			object instance,
			DbClassInfoCache info,
			IDataRecord reader,
			Dictionary<int, DbPropertyInfoCache> cache,
			DbAccessType? dbAccessType)
		{
			if (instance == null) throw new ArgumentNullException("instance");
			if (info == null) throw new ArgumentNullException("info");
			if (reader == null)
				return instance;

			//Left c# property name and right the object to read from the reader
			//var listofpropertys = new Dictionary<string, object>();

			var propertys = info.Propertys.ToArray();
			var instanceOfFallbackList = new Dictionary<string, object>();

			if (cache == null)
			{
				cache = new Dictionary<int, DbPropertyInfoCache>();
				for (var i = 0; i < reader.FieldCount; i++)
				{
					DbPropertyInfoCache val = null;
					info.Propertys.TryGetValue(info.SchemaMappingDatabaseToLocal(reader.GetName(i)), out val);
					cache.Add(i, val);
				}
			}

			for (var i = 0; i < reader.FieldCount; i++)
			{
				var property = cache[i];
				var value = reader.GetValue(i);

				if (property != null)
				{
					var attributes = property.Attributes;
					var valueConverterAttributeModel =
						attributes.FirstOrDefault(s => s.Attribute is ValueConverterAttribute);

					//Should the SQL value be converted
					if (valueConverterAttributeModel != null)
					{
						var converter = valueConverterAttributeModel.Attribute as ValueConverterAttribute;
						//Create the converter and then convert the value before everything else
						var valueConverter = converter.CreateConverter();
						value = valueConverter.Convert(value, property.PropertyInfo.PropertyType, converter.Parameter,
							CultureInfo.CurrentCulture);
					}

					var xmlAttributeModel =
						attributes.FirstOrDefault(s => s.Attribute is FromXmlAttribute);

					//should the Content be considerd as XML text?
					if (xmlAttributeModel != null)
					{
						//Get the XML text and check if its null or empty
						var xmlStream = value.ToString();
						if (string.IsNullOrEmpty(xmlStream))
						{
							continue;
						}

						//Check for List
						//if this is a list we are expecting other entrys inside
						if (property.CheckForListInterface())
						{
							//target Property is of type list
							//so expect a xml valid list Take the first element and expect the propertys inside this first element
							var record = XmlDataRecord.TryParse(xmlStream,
								property.PropertyInfo.PropertyType.GetGenericArguments().FirstOrDefault(), false, config);
							var xmlDataRecords = record.CreateListOfItems();

							var genericArguments =
								config.GetOrCreateClassInfoCache(property.PropertyInfo.PropertyType.GetGenericArguments().FirstOrDefault());
							var enumerableOfItems =
								xmlDataRecords.Select(
									s => DbAccessLayerHelper.SetPropertysViaReflection(genericArguments, s, dbAccessType, config)).ToList();
							object castedList;

							if (genericArguments.Type.IsClass && genericArguments.Type.GetInterface("INotifyPropertyChanged") != null)
							{
								var caster =
									typeof(DbCollection<>).MakeGenericType(genericArguments.Type).GetConstructor(new[] {typeof(IEnumerable)});

								Debug.Assert(caster != null, "caster != null");

								castedList = caster.Invoke(new object[] {enumerableOfItems});
							}
							else
							{
								var caster =
									typeof(NonObservableDbCollection<>).MakeGenericType(genericArguments.Type)
										.GetConstructor(new[] {typeof(IEnumerable)});

								Debug.Assert(caster != null, "caster != null");

								castedList = caster.Invoke(new object[] {enumerableOfItems});
							}

							property.Setter.Invoke(instance, castedList);
						}
						else
						{
							var classInfo = config.GetOrCreateClassInfoCache(property
								.PropertyInfo
								.PropertyType);

							var xmlDataRecord = XmlDataRecord.TryParse(xmlStream, property.PropertyInfo.PropertyType, true, config);

							//the t
							var xmlSerilizedProperty = DbAccessLayerHelper.SetPropertysViaReflection(classInfo, xmlDataRecord, dbAccessType,
								config);
							property.Setter.Invoke(instance, xmlSerilizedProperty);
						}
					}
					else if (value is DBNull || value == null)
					{
						property.Setter.Invoke(instance, new object[] {null});
					}
					else
					{
						object changedType;
						if (value.GetType() != property.PropertyInfo.PropertyType)
						{
							changedType = DataConverterExtensions.ChangeType(value, property.PropertyInfo.PropertyType);
						}
						else
						{
							changedType = value;
						}

						property.Setter.Invoke(instance, changedType);
					}
				}
				//This variable is null if we tried to find a property with the LoadNotImplimentedDynamicAttribute but did not found it
				else if (instanceOfFallbackList != null)
				{
					//no property found Look for LoadNotImplimentedDynamicAttribute property to include it

					if (instanceOfFallbackList.Any())
					{
						instanceOfFallbackList.Add(reader.GetName(i), value);
					}
					else
					{
						var maybeFallbackProperty =
							propertys.FirstOrDefault(
								s => s.Value.Attributes.Any(e => e.Attribute is LoadNotImplimentedDynamicAttribute));
						if (maybeFallbackProperty.Value != null)
						{
							instanceOfFallbackList = (Dictionary<string, object>) maybeFallbackProperty.Value.Getter.Invoke(instance);
							if (instanceOfFallbackList == null)
							{
								instanceOfFallbackList = new Dictionary<string, object>();
								maybeFallbackProperty.Value.Setter.Invoke(instance, instanceOfFallbackList);
							}
							instanceOfFallbackList.Add(reader.GetName(i), value);
						}
						else
						{
							instanceOfFallbackList = null;
						}
					}
				}
			}


			//foreach (var item in listofpropertys)
			//{
			//	var property = propertys.FirstOrDefault(s => s.PropertyName == item.Key);

			//}

			if (reader is EgarDataRecord)
			{
				(reader as IDisposable).Dispose();
			}

			return instance;
		}
Beispiel #25
0
 public DbAccessor(DbAccessType accessType, string connectionString) : this()
 {
     this._AccessType       = accessType;
     this._ConnectionString = connectionString;
     this.CreateAccessCommand();
 }
Beispiel #26
0
 public DbAccessor()
 {
     this._AccessType = DbAccessType.Sql;
 }
Beispiel #27
0
 public static bool HasFlagFast(this DbAccessType value, DbAccessType flag)
 {
     return((value & flag) != 0);
 }
Beispiel #28
0
		/// <summary>
		///     Create a DbAccessLayer that uses a Predefined type and Connection string
		/// </summary>
		public DbAccessLayer(DbAccessType dbAccessType, string connection, ILogger logger = null, DbConfig config = null)
			: this(logger, config)
		{
			if (dbAccessType == DbAccessType.Unknown)
			{
				throw new InvalidEnumArgumentException("dbAccessType", (int) DbAccessType.Unknown, typeof(DbAccessType));
			}

			DbAccessType = dbAccessType;
			Database = new DefaultDatabaseAccess();
			var database =
				GenerateStrategy(ProviderCollection.FirstOrDefault(s => s.Key == dbAccessType).Value, connection);
			Database.Attach(database);
			DatabaseStrategy = database;
		}
Beispiel #29
0
 /// <inheritdoc />
 public PagerConstraintTests(DbAccessType type) : base(type, false, false)
 {
 }
 public PerformanceTests(DbAccessType type, bool asyncExecution, bool syncronised) : base(type, asyncExecution, syncronised)
 {
 }
		public PagerConstraintTests(DbAccessType type)
		{
			_type = type;
		}
Beispiel #32
0
		/// <summary>
		///     Creates a new Instance based on possible Ctor's and the given
		///     <paramref name="reader" />
		/// </summary>
		/// <returns></returns>
		public object SetPropertysViaReflection(DbClassInfoCache type, IDataRecord reader, DbAccessType? accessType)
		{
			return type.SetPropertysViaReflection(reader, DbAccessType, Config);
		}
Beispiel #33
0
 /// <inheritdoc />
 public ProcedureTests(DbAccessType type, bool asyncExecution, bool syncronised) : base(type, asyncExecution, syncronised)
 {
 }
Beispiel #34
0
		public static void AddManager(DbAccessType type, IManager manager)
		{
			_managers.Add(type, manager);
		}
Beispiel #35
0
 public ConfigurationTests(DbAccessType type, bool asyncExecution, bool syncronised) : base(type, asyncExecution, syncronised)
 {
 }
Beispiel #36
0
        public DbAccessLayer GetWrapper(DbAccessType type, params object[] additionalArguments)
        {
            DbAccessLayer expectWrapper = null;

            _errorData.AppendLine("---------------------------------------------");
            _errorData.AppendLine("Found " + type);

            Assert.That(new DbConfig().SClassInfoCaches, Is.Empty, () => "The Global Class cache is not empty");
            var testClassName = TestContext.CurrentContext.Test.ClassName.Replace(typeof(Manager).Namespace, "").Where(e => char.IsUpper(e)).Select(e => e.ToString())
                                .Aggregate((e, f) => e + f) + "." +
                                TestContext.CurrentContext.Test.MethodName;


            //var arguments =
            //		additionalArguments.Select(
            //		                           f =>
            //		                           {
            //			                           if (f == null)
            //			                           {
            //				                           return TestContext.CurrentContext.Random.NextShort().ToString();
            //			                           }

            //			                           if (typeof(string).Assembly.GetTypes().Contains(f.GetType()))
            //			                           {
            //				                           return f.ToString();
            //			                           }

            //			                           return f.GetHashCode().ToString();
            //		                           })
            //		                   .ToArray();

            //if (arguments.Any())
            //{
            //	testClassName =
            //}
            testClassName = testClassName + "_" + Guid.NewGuid().ToString("N");
            testClassName = new Regex("[^a-zA-Z0-9]").Replace(testClassName, "_");
            _errorData.AppendLine($"Attach to Database: {testClassName}");

            expectWrapper = (_selectedMgr = _managers[type]()).GetWrapper(type, testClassName);
            expectWrapper.Config.EnableInstanceThreadSafety = true;


            expectWrapper.RaiseEvents = true;
            expectWrapper.OnSelect   += (sender, eventArg) =>
            {
                _errorData.AppendFormat(@"SELECT: \r\n{0}", eventArg.QueryDebugger);
                _errorData.AppendLine();
            };

            expectWrapper.OnDelete += (sender, eventArg) =>
            {
                _errorData.AppendFormat(@"DELETE: \r\n{0}", eventArg.QueryDebugger);
                _errorData.AppendLine();
            };

            expectWrapper.OnInsert += (sender, eventArg) =>
            {
                _errorData.AppendFormat(@"INSERT: \r\n{0}", eventArg.QueryDebugger);
                _errorData.AppendLine();
            };

            expectWrapper.OnUpdate += (sender, eventArg) =>
            {
                _errorData.AppendFormat(@"UPDATE: \r\n{0}", eventArg.QueryDebugger);
                _errorData.AppendLine();
            };

            expectWrapper.OnFailedQuery += (sender, eventArg, exception) =>
            {
                _errorData.AppendFormat(@"Query Failed: \r\n{0}\r\n{1}", eventArg.QueryDebugger, exception);
                _errorData.AppendLine();
            };

            Assert.NotNull(expectWrapper, "This test cannot run as no Database Variable is defined");
            var checkDatabase = expectWrapper.CheckDatabase();

            Assert.IsTrue(checkDatabase);
            AllTestContextHelper.TestSetup(expectWrapper.Config.ConstructorSettings);
            expectWrapper.Multipath = true;
            return(expectWrapper);
        }
Beispiel #37
0
        public DbAccessLayer GetWrapper(DbAccessType type, params object[] additionalArguments)
        {
            DbAccessLayer expectWrapper = null;

            _errorData.AppendLine("---------------------------------------------");
            _errorData.AppendLine("Found " + type);

            Assert.That(new DbConfig().SClassInfoCaches, Is.Empty, () => "The Global Class cache is not empty");
            var testClassName = TestContext.CurrentContext.Test.ClassName.Replace(typeof(Manager).Namespace, "")
                                .Where(e => char.IsUpper(e)).Select(e => e.ToString())
                                .Aggregate((e, f) => e + f) + "." +
                                TestContext.CurrentContext.Test.MethodName;

            testClassName = testClassName + "_" + Guid.NewGuid().ToString("N");
            testClassName = new Regex("[^a-zA-Z0-9]").Replace(testClassName, "_");
            _errorData.AppendLine($"Attach to Database: {testClassName}");

            expectWrapper = (_selectedMgr = _managers[type]()).GetWrapper(type, testClassName);
            expectWrapper.Config.EnableInstanceThreadSafety = true;


            expectWrapper.RaiseEvents      = true;
            expectWrapper.RaiseEventsAsync = false;
            expectWrapper.OnSelect        += (sender, eventArg) =>
            {
                _querys.Add(new KeyValuePair <string, string>("SELECT", eventArg.QueryDebugger.ToString()));
            };

            expectWrapper.OnDelete += (sender, eventArg) =>
            {
                _querys.Add(new KeyValuePair <string, string>("DELETE", eventArg.QueryDebugger.ToString()));
            };

            expectWrapper.OnInsert += (sender, eventArg) =>
            {
                _querys.Add(new KeyValuePair <string, string>("INSERT", eventArg.QueryDebugger.ToString()));
            };

            expectWrapper.OnUpdate += (sender, eventArg) =>
            {
                _querys.Add(new KeyValuePair <string, string>("UPDATE", eventArg.QueryDebugger.ToString()));
            };

            expectWrapper.OnNonResultQuery += (sender, eventArg) =>
            {
                _querys.Add(new KeyValuePair <string, string>("Query", eventArg.QueryDebugger.ToString()));
            };

            expectWrapper.OnFailedQuery += (sender, eventArg, exception) =>
            {
                _querys.Add(new KeyValuePair <string, string>("Query Failed", eventArg.QueryDebugger.ToString()));
            };

            Assert.NotNull(expectWrapper, "This test cannot run as no Database Variable is defined");
            var checkDatabase = expectWrapper.CheckDatabase();

            Assert.IsTrue(checkDatabase);
            AllTestContextHelper.TestSetup(expectWrapper.Config.ConstructorSettings);
            expectWrapper.Multipath = true;
            return(expectWrapper);
        }
		public CheckWrapperBaseTests(DbAccessType type)
		{
			_type = type;
		}
Beispiel #39
0
 public DbAccessLayer GetWrapper(DbAccessType type, string instanceName)
 {
     return(new DbAccessLayer(_strategy = new LocalRemotingStrategy(type, new DbConfig(), this, instanceName + "RMT_")));
 }
		public QueryBuilderTests(DbAccessType type)
		{
			_type = type;
			Init();
		}