Example #1
0
		internal EagarDataReader(object sourceObject, DbAccessLayer accessLayer)
		{
			foreach (var item in accessLayer.Config.GetOrCreateClassInfoCache(sourceObject.GetType()).Propertys)
			{
				Objects.Add(item.Key, item.Value.Getter.Invoke(sourceObject));
			}
		}
Example #2
0
 public void TestMethod1()
 {
     var manager = new DbAccessLayer();
     manager.Database =
         Database.CreateMSSQL(
             "Data Source=(localdb)\\Projects;Initial Catalog=TestDB;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False");
 }
		internal QueryLazyEnumerator(IQueryContainer queryContainer, Type type)
		{
			_type = queryContainer.AccessLayer.GetClassInfo(type);
			_accessLayer = new DbAccessLayer(queryContainer.AccessLayer.Database);
			_accessLayer.Database.Connect(IsolationLevel.ReadCommitted);
			var command = queryContainer.Compile();
			queryContainer.AccessLayer.RaiseSelect(command);

			_executeReader = command.ExecuteReader();
		}
		public static int[] AddBooks(int number, DbAccessLayer mgr)
		{
			var books = new List<Book>();
			for (int i = 0; i < number; i++)
			{
				var book = new Book();
				book.BookName = Guid.NewGuid().ToString();
				books.Add(mgr.InsertWithSelect(book));
			}
			return books.Select(f => f.BookId).ToArray();
		}
		public static long[] AddUsers(int number, DbAccessLayer mgr)
		{
			var users = new List<Users>();
			for (int i = 0; i < number; i++)
			{
				var user = new Users();
				user.UserName = Guid.NewGuid().ToString();
				users.Add(mgr.InsertWithSelect(user));
			}
			return users.Select(f => f.User_ID).ToArray();
		}
Example #6
0
		/// <summary>
		/// Enumerates all items in the source record
		/// </summary>
		public EgarDataRecord(IDataRecord sourceRecord, DbAccessLayer accessLayer)
			: this()
		{
			_accessLayer = accessLayer;
			for (var i = 0; i < sourceRecord.FieldCount; i++)
			{
				var obj = sourceRecord.GetValue(i);
				var name = sourceRecord.GetName(i);
				Objects.Add(name, obj);
			}
		}
		public static long[] AddImages(int number, DbAccessLayer mgr)
		{
			var images = new List<Image>();
			for (int i = 0; i < number; i++)
			{
				var image = new Image();
				image.Text = Guid.NewGuid().ToString();
				images.Add(mgr.InsertWithSelect(image));
			}
			return images.Select(f => f.ImageId).ToArray();
		}
Example #8
0
        public async Task EnumerateAsync(DbAccessLayer db, IDbCommand command, Action <IDataReader> onRecord, CommandBehavior executionHint = CommandBehavior.Default)
        {
            await db.Database.RunAsync(
                async s =>
            {
                using (command)
                {
                    command.Connection  = command.Connection ?? s.GetConnection();
                    command.Transaction = command.Transaction ?? s.ConnectionController.Transaction;

                    IDataReader dr = null;
                    try
                    {
                        var query = command as DbCommand;
                        if (query != null && db.Async)
                        {
                            dr = await query.ExecuteReaderAsync(executionHint).ConfigureAwait(DbAccessLayer.ConfigureAwait);
                        }
                        else
                        {
                            dr = command.ExecuteReader(executionHint);
                        }

                        do
                        {
                            var reader = dr as DbDataReader;
                            while (reader != null && db.Async
                                                                        ? await reader.ReadAsync().ConfigureAwait(DbAccessLayer.ConfigureAwait)
                                                                        : dr.Read())
                            {
                                onRecord(dr);
                            }
                        } while (dr.NextResult());
                    }
                    catch (Exception ex)
                    {
                        db.RaiseFailedQuery(this, command, ex);
                        throw;
                    }
                    finally
                    {
                        dr?.Dispose();
                    }
                }

                return(new object());
            });
        }
Example #9
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;
		}
Example #10
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;
		}
		public static int[] AddBooksWithImage(int number, int imagesPerBook, DbAccessLayer mgr)
		{
			var books = new List<Book>();
			for (int i = 0; i < number; i++)
			{
				var book = new Book();
				book.BookName = Guid.NewGuid().ToString();
				books.Add(book = mgr.InsertWithSelect(book));

				for (int j = 0; j < imagesPerBook; j++)
				{
					mgr.Insert(new Image()
					{
						Text = Guid.NewGuid().ToString(),
						IdBook = book.BookId
					});
				}
			}
			return books.Select(f => f.BookId).ToArray();
		}
Example #12
0
        public EagarDataRecord[][] ExecuteMARSCommand(DbAccessLayer db, IDbCommand query, out int recordsAffected)
        {
            var recordsAffectedA = 0;
            var result           = db.Database.Run(
                s =>
            {
                var records = new List <EagarDataRecord[]>();
                using (query)
                {
                    query.Connection  = query.Connection ?? s.GetConnection();
                    query.Transaction = query.Transaction ?? s.ConnectionController.Transaction;
                    using (var dr = query.ExecuteReader())
                    {
                        recordsAffectedA = dr.RecordsAffected;
                        try
                        {
                            do
                            {
                                var resultSet = new List <EagarDataRecord>();
                                while (dr.Read())
                                {
                                    resultSet.Add(EagarDataRecord.WithExcludedFields(dr));
                                }

                                records.Add(resultSet.ToArray());
                            } while (dr.NextResult());
                        }
                        catch (Exception ex)
                        {
                            db.RaiseFailedQuery(this, query, ex);
                            throw;
                        }
                    }
                }

                return(records.ToArray());
            });

            recordsAffected = recordsAffectedA;
            return(result);
        }
Example #13
0
		public void CreateEntrys(string connection, string outputPath, string database)
		{
			TargetDir = outputPath;
			Manager = new DbAccessLayer(DbAccessType.MsSql, connection);
			bool checkDatabase;
			try
			{
				checkDatabase = Manager.CheckDatabase();
			}
			catch (Exception)
			{
				checkDatabase = false;
			}

			if (!checkDatabase)
			{
				throw new Exception("Database not accessible. Maybe wrong Connection or no Selected Database?");
			}
			var databaseName = string.IsNullOrEmpty(Manager.Database.DatabaseName) ? database : Manager.Database.DatabaseName;
			if (string.IsNullOrEmpty(databaseName))
			{
				throw new Exception("Database not exists. Maybe wrong Connection or no Selected Database?");
			}
			Console.WriteLine("Connection OK ... Reading Server Version ...");

			SqlVersion = Manager.RunPrimetivSelect<string>("SELECT SERVERPROPERTY('productversion')").FirstOrDefault();

			Console.WriteLine("Server version is {0}", SqlVersion);

			Console.WriteLine("Reading Tables from {0} ...", databaseName);

			Tables = Manager.Select<TableInformations>().Select(s => new TableInfoModel(s, databaseName, Manager)).ToList();
			Views = Manager.Select<ViewInformation>().Select(s => new TableInfoModel(s, databaseName, Manager)).ToList();
			StoredProcs = Manager.Select<StoredProcedureInformation>().Select(s => new StoredPrcInfoModel(s)).ToList();

			Console.WriteLine("Found {0} Tables, {1} Views, {2} Procedures ... select a Table to see Options or start an Action", Tables.Count(), Views.Count(), StoredProcs.Count());
			Enums = new List<Dictionary<int, string>>();
			RenderMenu();
		}
		public static void ClearDb(DbAccessLayer mgr)
		{
			mgr.Config.Dispose();
			DbConfig.Clear();
			if (mgr.DbAccessType == DbAccessType.MsSql)
			{
				mgr.ExecuteGenericCommand(string.Format("DELETE FROM {0} ", UsersMeta.TableName), null);
				mgr.ExecuteGenericCommand(string.Format("DELETE FROM {0} ", ImageMeta.TableName), null);
				mgr.ExecuteGenericCommand(string.Format("DELETE FROM {0} ", BookMeta.TableName), null);
				mgr.ExecuteGenericCommand(string.Format("TRUNCATE TABLE {0} ", UsersMeta.TableName), null);
				mgr.ExecuteGenericCommand(string.Format("TRUNCATE TABLE {0} ", ImageMeta.TableName), null);
			}

			if (mgr.DbAccessType == DbAccessType.SqLite)
			{
				mgr.ExecuteGenericCommand(string.Format("DELETE FROM {0} ", UsersMeta.TableName), null);
				mgr.ExecuteGenericCommand(string.Format("VACUUM"), null);
				mgr.ExecuteGenericCommand(string.Format("DELETE FROM {0} ", BookMeta.TableName), null);
				mgr.ExecuteGenericCommand(string.Format("VACUUM"), null);
				mgr.ExecuteGenericCommand(string.Format("DELETE FROM {0} ", ImageMeta.TableName), null);
				mgr.ExecuteGenericCommand(string.Format("VACUUM"), null);
			}
		}
Example #15
0
        public void Enumerate(DbAccessLayer db, IDbCommand command, Action <IDataReader> onRecord,
                              CommandBehavior executionHint = CommandBehavior.Default)
        {
            db.Database.Run(
                s =>
            {
                using (command)
                {
                    command.Connection  = command.Connection ?? s.GetConnection();
                    command.Transaction = command.Transaction ?? s.ConnectionController.Transaction;

                    IDataReader dr = null;
                    try
                    {
                        dr = command.ExecuteReader(executionHint);
                        do
                        {
                            while (dr.Read())
                            {
                                onRecord(dr);
                            }
                        } while (dr.NextResult());
                    }
                    catch (Exception ex)
                    {
                        db.RaiseFailedQuery(this, command, ex);
                        throw;
                    }
                    finally
                    {
                        dr?.Dispose();
                    }
                }

                return(new object());
            });
        }
Example #16
0
		public TableInfoModel(TableInformations info, string database, DbAccessLayer db)
		{
			CreateSelectFactory = true;
			Info = info;
			Database = database;
			ColumnInfos = db.Select<ColumnInfo>(new object[] { Info.TableName, database }).Select(s => new ColumInfoModel(s)).ToList();

			var firstOrDefault = db.RunPrimetivSelect(typeof(string),
				"SELECT COLUMN_NAME " +
				"FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc " +
				"JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu " +
				"ON tc.CONSTRAINT_NAME = ccu.Constraint_name " +
				"WHERE tc.CONSTRAINT_TYPE = 'Primary Key' " +
				"AND tc.TABLE_CATALOG = @database " +
				"AND tc.TABLE_NAME = @tableName", new List<IQueryParameter>()
				{
					new QueryParameter("tableName",info.TableName),
					new QueryParameter("database",Database)
				}).FirstOrDefault() as string;

			var columInfoModel = ColumnInfos.FirstOrDefault(s => s.ColumnInfo.ColumnName == firstOrDefault);
			if (columInfoModel != null)
				columInfoModel.PrimaryKey = true;


			var forgeinKeyDeclarations = db.Select<ForgeinKeyInfoModel>(new object[] { info.TableName, database });

			foreach (var item in ColumnInfos)
			{
				var fod = forgeinKeyDeclarations.FirstOrDefault(s => s.SourceColumn == item.ColumnInfo.ColumnName);
				if (fod != null)
				{
					item.ForgeinKeyDeclarations = fod;
				}
			}
		}
Example #17
0
		public void Init()
		{
			expectWrapper = new Manager().GetWrapper(_type);
		}
Example #18
0
		public EagarDataReader(IDataRecord sourceRecord, DbAccessLayer accessLayer)
			: base(sourceRecord, accessLayer)
		{
		}
Example #19
0
 public object GetSkalar(DbAccessLayer db, IDbCommand command, Type requestedType)
 {
     return(db.Database.Run(s => s.GetSkalar(command)));
 }
Example #20
0
		public FooTest()
		{
			var access = new DbAccessLayer(DbAccessType.MsSql,
				"Data Source=(localdb)\\Projects;Initial Catalog=Northwind;Integrated Security=True;");
			var @select = access.Select<Foo>("SomeName");
		}
Example #21
0
		public QueryElement(DbAccessLayer database) : base(database)
		{
		}
Example #22
0
		public QueryElement(DbAccessLayer database, Type type) : base(database, type)
		{
		}
		/// <summary>
		///     Creates a new Instance of an QueryText Builder that creates Database aware querys
		/// </summary>
		public InternalContainerContainer(DbAccessLayer database)
		{
			AccessLayer = database;
			Parts = new List<GenericQueryPart>();
		}
		public void CreateEntrys(string connection, string outputPath, string database)
		{
			Status = "Try to connect";
			//Data Source=(LocalDb)\ProjectsV12;Integrated Security=True;Database=TestDB;
			IsEnumeratingDatabase = true;
			TargetDir = outputPath;
			Manager = new DbAccessLayer(DbAccessType.MsSql, connection);
			DbConfig.EnableGlobalThreadSafety = true;
			try
			{
				Connected = Manager.CheckDatabase();
			}
			catch (Exception)
			{
				IsEnumeratingDatabase = false;
				Connected = false;
			}

			if (!Connected)
			{
				IsEnumeratingDatabase = false;
				Status = ("Database not accessible. Maybe wrong Connection or no Selected Database?");
				return;
			}
			var databaseName = string.IsNullOrEmpty(Manager.Database.DatabaseName) ? database : Manager.Database.DatabaseName;
			if (string.IsNullOrEmpty(databaseName))
			{
				IsEnumeratingDatabase = false;
				Status = ("Database not exists. Maybe wrong Connection or no Selected Database?");
				Connected = false;
				return;
			}
			Status = "Connection OK ... Reading Server Version ...";

			SqlVersion = Manager.RunPrimetivSelect<string>("SELECT SERVERPROPERTY('productversion')").FirstOrDefault();
			Status = "Reading Tables";

			int counter = 3;
			base.SimpleWorkWithSyncContinue(() =>
			{
				return
					new DbAccessLayer(DbAccessType.MsSql, connection).Select<TableInformations>()
						.Select(s => new TableInfoModel(s, databaseName, new DbAccessLayer(DbAccessType.MsSql, connection)))
						.Select(s => new TableInfoViewModel(s, this))
						.ToList();
			}, dbInfo =>
			{
				foreach (var source in dbInfo)
				{
					if (Tables.All(f => f.Info.TableName != source.Info.TableName))
						Tables.Add(source);
				}
				this.SelectedTable = Tables.FirstOrDefault();
				counter--;
				if (counter == 0)
				{
					IsEnumeratingDatabase = false;
					Status = "Done";
				}
			});
			base.SimpleWorkWithSyncContinue(() =>
			{
				return
					new DbAccessLayer(DbAccessType.MsSql, connection)
					.Select<ViewInformation>()
					.Select(s => new TableInfoModel(s, databaseName, new DbAccessLayer(DbAccessType.MsSql, connection)))
					.ToList();
			}, dbInfo =>
			{
				foreach (var source in dbInfo)
				{
					if (Views.All(f => f.Info.TableName != source.Info.TableName))
						Views.Add(source);
				}

				counter--;
				if (counter == 0)
				{
					IsEnumeratingDatabase = false;
					Status = "Done";
				}
			});
		}
Example #25
0
 public void CheckDbdbaccess()
 {
     dbaccess = new DbAccessLayer(DbTypes.MsSql, "Data Source=(localdb)\\Projects;Initial Catalog=TestDB;Integrated Security=True;");
 }
Example #26
0
 public async Task <int> ExecuteCommandAsync(DbAccessLayer db, IDbCommand command)
 {
     return(await db.Database.RunAsync(async s => await s.ExecuteNonQueryAsync(command, db.Async)));
 }
Example #27
0
 public int ExecuteCommand(DbAccessLayer db, IDbCommand command)
 {
     return(db.Database.Run(s => s.ExecuteNonQuery(command)));
 }
		public void Init()
		{
			_mgr = new Manager();
			_dbAccess = _mgr.GetWrapper(_type);
		}
		/// <summary>
		///     Creates a new Instance of an QueryCommand Builder that creates Database aware querys
		/// </summary>
		public InternalContainerContainer(DbAccessLayer database, Type forType)
			: this(database)
		{
			ForType = forType;
		}
 public ProcedureProcessor(string query, DbAccessLayer dbAccessLayer)
 {
     _dbAccessLayer  = dbAccessLayer;
     Query           = query;
     QueryParameters = new List <IQueryParameter>();
 }