Example #1
0
        /// <summary>
        /// Initializes all necessary settings for SqlServer.
        /// </summary>
        public static void Initialize()
        {
            // Skip if already initialized
            if (IsInitialized == true)
            {
                return;
            }

            // Map the DbSetting
            var dbSetting = new SqlServerDbSetting();

            DbSettingMapper.Add(typeof(Microsoft.Data.SqlClient.SqlConnection), dbSetting, true);
            DbSettingMapper.Add(typeof(System.Data.SqlClient.SqlConnection), dbSetting, true);

            // Map the DbHelper
            var dbHelper = new SqlServerDbHelper();

            DbHelperMapper.Add(typeof(Microsoft.Data.SqlClient.SqlConnection), dbHelper, true);
            DbHelperMapper.Add(typeof(System.Data.SqlClient.SqlConnection), dbHelper, true);

            // Map the Statement Builder
            var statementBuilder = new SqlServerStatementBuilder(dbSetting);

            StatementBuilderMapper.Add(typeof(Microsoft.Data.SqlClient.SqlConnection), statementBuilder, true);
            StatementBuilderMapper.Add(typeof(System.Data.SqlClient.SqlConnection), statementBuilder, true);

            // Set the flag
            IsInitialized = true;
        }
Example #2
0
        /// <summary>
        /// Initializes all the necessary settings for SQL Server.
        /// </summary>
        public static void Initialize()
        {
            // Skip if already initialized
            if (IsInitialized == true)
            {
                return;
            }

            // Map the DbSetting
            var dbSetting = new SqlServerDbSetting();

            DbSettingMapper.Add <SqlConnection>(dbSetting, true);

            // Map the DbHelper
            var dbHelper = new SqlServerDbHelper();

            DbHelperMapper.Add <SqlConnection>(dbHelper, true);

            // Map the Statement Builder
            var statementBuilder = new SqlServerStatementBuilder(dbSetting);

            StatementBuilderMapper.Add <SqlConnection>(statementBuilder, true);

            // Set the flag
            IsInitialized = true;
        }
        public void Init(string connectionString, DatabaseProvider databaseType)
        {
            DatabaseProvider = databaseType;
            conn             = DatabaseProvider.GetAndConfigureConnection(connectionString, (connection, dbType) =>
            {
                switch (dbType)
                {
                case DatabaseProvider.MySqlData:
                    MySqlBootstrap.Initialize();
                    break;

                case DatabaseProvider.Npgsql:
                    PostgreSqlBootstrap.Initialize();
                    break;

                case DatabaseProvider.SystemData:
                    {
                        var dbSetting = new SqlServerDbSetting();
                        DbSettingMapper.Add(typeof(System.Data.SqlClient.SqlConnection), dbSetting, true);

                        // Map the DbHelper
                        var dbHelper = new SqlServerDbHelper();
                        DbHelperMapper.Add(typeof(System.Data.SqlClient.SqlConnection), dbHelper, true);

                        // Map the Statement Builder
                        var statementBuilder = new SqlServerStatementBuilder(dbSetting);
                        StatementBuilderMapper.Add(typeof(System.Data.SqlClient.SqlConnection), statementBuilder, true);
                        break;
                    }

                case DatabaseProvider.MicrosoftData:
                    {
                        var dbSetting = new SqlServerDbSetting();
                        DbSettingMapper.Add(typeof(Microsoft.Data.SqlClient.SqlConnection), dbSetting, true);

                        // Map the DbHelper
                        var dbHelper = new SqlServerDbHelper();
                        DbHelperMapper.Add(typeof(Microsoft.Data.SqlClient.SqlConnection), dbHelper, true);

                        // Map the Statement Builder
                        var statementBuilder = new SqlServerStatementBuilder(dbSetting);
                        StatementBuilderMapper.Add(typeof(Microsoft.Data.SqlClient.SqlConnection), statementBuilder, true);
                        break;
                    }

                case DatabaseProvider.MySqlConnector:
                    MySqlConnectorBootstrap.Initialize();
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                connection.Open();
                return(connection);
            });
        }
Example #4
0
        /// <summary>
        /// 创建一个非关系型数据存储类
        /// </summary>
        /// <param name="dBHelper">对应的数据对象</param>
        /// <param name="keyName">数据所对应数据库中的key名</param>
        /// <param name="valueName">数据所对应数据库中的value名</param>
        /// <param name="tableName">数据所对应数据库的表名</param>
        /// <param name="syncPeriod">同步周期 用于控制写入到持久化数据库的时间 单位 毫秒 默认 1000ms</param>
        /// <param name="condition">数据查询的其他条件 如不需要则默认值即可,注意此处不需要再次写入key名所对应的条件了</param>
        public NoSqlStorage(SqlServerDbHelper dBHelper, string keyName, string valueName, string tableName, int syncPeriod = 1000, string condition = "")
        {
            this.dBHelper   = dBHelper;
            this.keyName    = keyName;
            this.valueName  = valueName;
            this.tableName  = tableName;
            this.syncPeriod = syncPeriod;
            this.condition  = !string.IsNullOrEmpty(condition) ? (condition + " AND ") : "";

            timeFlow = BaseTimeFlow.CreateTimeFlow(this, 0);
            timeFlow.StartTimeFlowES();
        }
Example #5
0
 /// <summary>
 /// 构建函数
 /// <para>需要传入一个非空数据库助手实例对象</para>
 /// </summary>
 /// <param name="dBHelper">数据库助手实例</param>
 private SqlBuilder(SqlServerDbHelper dBHelper)
 {
     if (dBHelper == null)
     {
         Exception ex = new NullReferenceException("DBHelper Is Null");
         throw ex;
     }
     else
     {
         this.dBHelper = dBHelper;
     }
 }
Example #6
0
 /// <summary>
 /// 读取数据对
 /// </summary>
 /// <param name="dBHelper">数据库链接对象</param>
 /// <param name="primaryKey">主键名,用于更新和寻找唯一依据字段</param>
 /// <param name="tableName">SQL表名</param>
 /// <param name="whereCondition">SQL条件判断条件【Where语句后的内容 包括排序等】</param>
 /// <param name="fieldNames">SQL字段名【默认为:*】</param>
 /// <param name="topNum">SQL取值数量【默认为:-1 无限】</param>
 /// <param name="isNoLock">是否不锁Sql,默认锁表</param>
 /// <returns></returns>
 public static DataEntityRows Load(SqlServerDbHelper dBHelper, string primaryKey, string tableName, string whereCondition, string fieldNames = "*", int topNum = -1, bool isNoLock = false)
 {
     if (dBHelper != null)
     {
         CommandResult result = dBHelper.CommandSQL($"SELECT {(topNum > -1 ? ("TOP(" + topNum + ")") : "")} {fieldNames} FROM {tableName} {(isNoLock ? "WITH(NOLOCK)" : "")} {(whereCondition != null && whereCondition != "" ? ("WHERE " + whereCondition) : "")}");
         if (result != null && result.EffectNum > 0)
         {
             DataEntityRows dataPairs = new DataEntityRows(dBHelper, result.Collection, primaryKey, tableName, fieldNames);
             return(dataPairs);
         }
     }
     return(null);
 }
Example #7
0
        public void GetSurrogateKeyReturnQuery(IDbConnection connection)
        {
            var surrogateKeyReturnQuery = QueryHelper.GetSurrogateKeyReturnQuery(connection);

            Assert.NotEmpty(surrogateKeyReturnQuery);

            if (connection is SqlConnection)
            {
                var sqlServerDbHelper = new SqlServerDbHelper();
                Assert.Equal(sqlServerDbHelper.GetSurrogateKeyReturnQuery(), surrogateKeyReturnQuery);
            }
            else if (connection is MySqlConnection)
            {
                var mysqlDbHelper = new MySqlDbHelper();
                Assert.Equal(mysqlDbHelper.GetSurrogateKeyReturnQuery(), surrogateKeyReturnQuery);
            }
        }
Example #8
0
        public Test_DBSqlServer()
        {
            Console.WriteLine("数据测试开始");
            // 数据库连接使用此函数即可简单创建 数据库的创建还提供更多重载方案,可以点入查看
            dbHelper = new SqlServerDbHelper("127.0.0.1", "sa", "123456", "db_test");
            // 增加异常监听器
            dbHelper.SetExceptionListener(this);
            // 检测数据库连接是否成功调用 成功返回true
            if (dbHelper.CheckConnected())
            {
                Console.WriteLine("数据库已连接");
            }
            //获取数据库时间 如果获取不到默认获取程序本地时间
            Console.WriteLine("数据库时间:" + dbHelper.Now);

            Console.WriteLine("数据库测试结束");
        }
Example #9
0
        /// <summary>
        /// 命名空间构造函数
        /// </summary>
        internal DataEntityRows(SqlServerDbHelper dBHelper, DataRowCollection collection, string primaryKey, string tableName, string fieldNames)
        {
            this.dBHelper   = dBHelper;
            this.TableName  = tableName;
            this.PrimaryKey = primaryKey;
            this.FieldNames = fieldNames;
            foreach (DataRow dataRow in collection)
            {
                DataEntityRow dataObject = new DataEntityRow(this);
                foreach (object column in dataRow.Table.Columns)
                {
                    dataObject.data.TryAdd(column.ToString(), dataRow[column.ToString()]);
                }
                rows.TryAdd(dataRow[primaryKey], dataObject);
            }

            timeFlow = BaseTimeFlow.CreateTimeFlow(this, 0);
            timeFlow.StartTimeFlowES();
        }
Example #10
0
        static void Main(string[] args)
        {
            SqlServerDbHelper sqlServerDbHelper = SqlServerDbHelper.GetInstance();

            #region SELECT All & By Id
            //var company = sqlServerDbHelper.GetDataById<Company>(Id: 1);
            //var companys = sqlServerDbHelper.GetDataArray<Company>();
            //var user = sqlServerDbHelper.GetDataById<User>(Id: 1);
            //var users = sqlServerDbHelper.GetDataArray<User>();
            //Utils.ShowProperties(company);
            //foreach (var c in companys)
            //{
            //    Utils.ShowProperties(c);
            //}
            //Utils.ShowProperties(user);
            //foreach (var c in users)
            //{
            //    Utils.ShowProperties(c);
            //}

            #endregion
            #region INSERT
            //int companyCount = sqlServerDbHelper.AddData<Company>(new Company
            //{
            //    Name = "Microsoft",
            //    CreateTime = DateTime.Now,
            //    CreatorId = 1,
            //    LastModifierId = 1,
            //    LastModifyTime = DateTime.Now
            //});
            //int userCount = sqlServerDbHelper.AddData<User>(new User
            //{
            //    Name = "小林",
            //    Account = "admin",
            //    PassWord = "******",
            //    Email = "12",
            //    Mobile = "133",
            //    CompanyId = 4,
            //    CompanyName = "Microsoft",
            //    State = 0,
            //    UserType = 2,
            //    LastLoginTime = DateTime.Now,
            //    CreateTime = DateTime.Now,
            //    CreatorId = 1,
            //    LastModifierId = 1,
            //    LastModifyTime = DateTime.Now,

            //});
            //Console.WriteLine($"ConpanyCount:{companyCount}   UserCount:{userCount}");
            #endregion
            #region UPDATE
            //int companyCount = sqlServerDbHelper.ChangeData(new Company
            //{
            //    Id = 4,
            //    CreatorId = 2,
            //    LastModifierId = 2,
            //    LastModifyTime = DateTime.Now
            //});
            //int userCount = sqlServerDbHelper.ChangeData(new User
            //{
            //    Id = 7,
            //    Account = "manager"
            //});
            //Console.WriteLine($"CompanyCount:{companyCount}   UserCount:{userCount}");
            #endregion
            #region DELETE
            int count = sqlServerDbHelper.DeleteData(new Company {
                Id = 5
            });
            Console.WriteLine(count);
            #endregion
            Console.Read();
        }
Example #11
0
 /// <summary>
 /// 创建一个构造器
 /// <para>需要传入一个非空数据库助手实例对象</para>
 /// </summary>
 /// <param name="dBHelper">数据库助手实例</param>
 /// <returns></returns>
 public static SqlBuilder Create(SqlServerDbHelper dBHelper)
 {
     return(new SqlBuilder(dBHelper));
 }
Example #12
0
 public void ProcedureException(SqlServerDbHelper helper, string procedure, SqlParameter[] sqlParameters, Exception exception)
 {
     Log.Exception(exception, "ProcedureException");
 }
Example #13
0
 public void CommandSQLException(SqlServerDbHelper helper, string sql, Exception exception)
 {
     Log.Exception(exception, "CommandSQLException");
 }
Example #14
0
 public void CheckConnectedException(SqlServerDbHelper helper, Exception exception)
 {
     Log.Exception(exception, "CheckConnectedException");
 }
Example #15
0
        static void Main(string[] args)
        {
            #region 抽象工程模式

            // ef 打开和关闭
            AbstractFactory efFactory = new EfFactory();
            efFactory.CreateOpen().Print();
            efFactory.CreateClose().Print();

            // dapper 打开和关闭
            AbstractFactory dapperFactory = new DapperFactory();
            dapperFactory.CreateOpen().Print();
            dapperFactory.CreateClose().Print();

            #endregion

            Console.WriteLine("------------------------------");

            #region 建造者模式

            var director      = new Director();
            var saiyanBuilder = new SaiyanBuilder();
            var naimBuilder   = new NaimBuilder();

            director.Construct(saiyanBuilder);

            // 组装赛亚人
            var saiyanPerson = saiyanBuilder.GetPerson();
            saiyanPerson.Show();

            // 组装那美克人
            director.Construct(naimBuilder);
            var naimPerson = naimBuilder.GetPerson();
            naimPerson.Show();

            #endregion

            Console.WriteLine("------------------------------");

            #region MyRegion

            var mingren1 = new MingrenPrototype();
            var mingren2 = mingren1.Clone() as MingrenPrototype;
            //mingren1 负责攻击
            mingren1.Attack();
            //mingren2 负责保护
            mingren2?.Protect();

            #endregion

            Console.WriteLine("------------------------------");

            #region 适配器模式

            //类的适配器模式
            var baiduMap = new BaiduAdapter();
            baiduMap.Gen();

            //对象的适配器模式
            var baiduMap1 = new BaiduAdapter1();
            baiduMap1.Gen();

            #endregion

            Console.WriteLine("------------------------------");

            #region 桥接模式

            DbControlAbstract dbControlAbstract = new DbControl();
            // Sql Server
            dbControlAbstract.Db = new SqlServerDb();
            dbControlAbstract.Open();
            dbControlAbstract.Add();
            dbControlAbstract.Close();

            // MySql
            dbControlAbstract.Db = new MySqlDb();
            dbControlAbstract.Open();
            dbControlAbstract.Add();
            dbControlAbstract.Close();

            #endregion

            Console.WriteLine("------------------------------");

            #region 装饰者模式

            // SqlServerDbHelper
            DbHelper dbHelper = new SqlServerDbHelper();
            // check
            Decorator decorator = new CheckDecorator(dbHelper);
            decorator.Add();

            #endregion

            Console.WriteLine("------------------------------");

            //透明式
            Car car = new Motorcycle();
            car.Travel();
            car.Two(new SuvCar());
            car.Ten(new SuvCar());

            car = new SuvCar();
            car.Travel();
            car.Two(new SuvCar());
            car.Ten(new SuvCar());

            //安全式
            Car1 car1 = new Motorcycle1();
            car1.Travel();

            Car1 bus = new Bus();
            bus.Travel();
            ((FourCar)bus).Two(new Bus());
            ((FourCar)bus).Ten(new Bus());

            Console.ReadKey();
        }
Example #16
0
        static void Main(string[] args)
        {
            #region 简单工厂

            var add = Factory.GetOperat("1");
            var sub = Factory.GetOperat("2");

            #endregion

            Console.WriteLine("------------------------------");

            #region 单例模式

            Singleton.GetInstance();
            var s1 = Singleton1.Instance;
            var s2 = Singleton2.Instance;

            #endregion

            Console.WriteLine("------------------------------");

            #region 抽象工程模式

            // ef 打开和关闭
            AbstractFactory efFactory = new EfFactory();
            efFactory.CreateOpen().Print();
            efFactory.CreateClose().Print();

            // dapper 打开和关闭
            AbstractFactory dapperFactory = new DapperFactory();
            dapperFactory.CreateOpen().Print();
            dapperFactory.CreateClose().Print();

            #endregion

            Console.WriteLine("------------------------------");

            #region 建造者模式

            var director      = new Director();
            var saiyanBuilder = new SaiyanBuilder();
            var naimBuilder   = new NaimBuilder();

            director.Construct(saiyanBuilder);

            // 组装赛亚人
            var saiyanPerson = saiyanBuilder.GetPerson();
            saiyanPerson.Show();

            // 组装那美克人
            director.Construct(naimBuilder);
            var naimPerson = naimBuilder.GetPerson();
            naimPerson.Show();

            #endregion

            Console.WriteLine("------------------------------");

            #region 原型模式

            var mingren1 = new MingrenPrototype();
            var mingren2 = mingren1.Clone() as MingrenPrototype;
            //mingren1 负责攻击
            mingren1.Attack();
            //mingren2 负责保护
            mingren2?.Protect();

            #endregion

            Console.WriteLine("------------------------------");

            #region 适配器模式

            //类的适配器模式
            var baiduMap = new BaiduAdapter();
            baiduMap.Gen();

            //对象的适配器模式
            var baiduMap1 = new BaiduAdapter1();
            baiduMap1.Gen();

            #endregion

            Console.WriteLine("------------------------------");

            #region 桥接模式

            DbControlAbstract dbControlAbstract = new DbControl();
            // Sql Server
            dbControlAbstract.Db = new SqlServerDb();
            dbControlAbstract.Open();
            dbControlAbstract.Add();
            dbControlAbstract.Close();

            // MySql
            dbControlAbstract.Db = new MySqlDb();
            dbControlAbstract.Open();
            dbControlAbstract.Add();
            dbControlAbstract.Close();

            #endregion

            Console.WriteLine("------------------------------");

            #region 装饰者模式

            // SqlServerDbHelper
            DbHelper dbHelper = new SqlServerDbHelper();
            // check
            Decorator decorator = new CheckDecorator(dbHelper);
            decorator.Add();

            #endregion

            Console.WriteLine("------------------------------");

            #region 组合模式

            //透明式
            Car car = new Motorcycle();
            car.Travel();
            car.Two(new SuvCar());
            car.Ten(new SuvCar());

            car = new SuvCar();
            car.Travel();
            car.Two(new SuvCar());
            car.Ten(new SuvCar());

            //安全式
            Car1 car1 = new Motorcycle1();
            car1.Travel();

            Car1 bus = new Bus();
            bus.Travel();
            ((FourCar)bus).Two(new Bus());
            ((FourCar)bus).Ten(new Bus());

            #endregion

            Console.WriteLine("------------------------------");

            #region 外观模式

            var facade = new Facade();
            facade.Buy();

            #endregion

            Console.WriteLine("------------------------------");

            #region 享元模式

            foreach (var item in new[] { "a", "b", "c", "a", "b" })
            {
                var flyweight = FlyweightFactory.GetFlyweight(item);
                flyweight.Operation(1);
            }
            Console.WriteLine(FlyweightFactory.DicFlyweight.Count);

            #endregion

            Console.WriteLine("------------------------------");

            #region 代理模式

            var proxy = new Proxy();
            proxy.Do("上网");

            #endregion

            Console.WriteLine("------------------------------");

            #region 模板方法模式

            var chain = new ChinaBank();
            chain.Get();
            var shBank = new ShanghaiBank();
            shBank.Get();

            #endregion

            Console.WriteLine("------------------------------");

            #region 命令模式

            var r = new Receiver1();
            var c = new CommandImp(r);
            var i = new Invoke(c);
            i.ExecuteCommand();

            #endregion

            Console.WriteLine("------------------------------");

            #region 迭代器模式

            ICollection list     = new Collection();
            var         iterator = list.GetIterator();

            while (iterator.MoveNext())
            {
                var j = (int)iterator.GetCurrent();
                Console.WriteLine(j.ToString());
                iterator.Next();
            }

            #endregion

            Console.WriteLine("------------------------------");

            #region 观察者模式

            HousingDeveloper hd = new WuhanHousingDeveloper();
            hd.Add(new NoHouseObserver("A"));
            hd.Add(new NoHouseObserver("B"));
            hd.Add(new NoHouseObserver("C"));

            hd.Add(new HasHouseObserver("D"));
            hd.Add(new HasHouseObserver("E"));
            hd.Add(new HasHouseObserver("F"));

            hd.Notify();

            #endregion

            Console.WriteLine("------------------------------");

            #region 中介者模式

            var buyer    = new Buyer();
            var seller   = new Seller();
            var mediator = new MediatorImp(buyer, seller);
            buyer.MoneyChange(5, mediator);
            seller.MoneyChange(10, mediator);

            #endregion

            Console.WriteLine("------------------------------");

            #region 状态模式

            var user = new User("admin");
            for (var j = 0; j < 10; j++)
            {
                user.Recharge(20 * j);
            }

            #endregion

            Console.WriteLine("------------------------------");

            #region 策略模式

            var context = new NotifyContext(new EmailStragety());
            context.Send("新的消息");
            context.Stragety = new SmsStragety();
            context.Send("第二条消息");

            #endregion

            Console.WriteLine("------------------------------");

            #region 责任链模式

            var leaveRequest1 = new LeaveRequest("张三", 1);
            var leaveRequest2 = new LeaveRequest("李四", 4);
            var leaveRequest3 = new LeaveRequest("王五", 7);
            var leaveRequest4 = new LeaveRequest("赵六", 11);

            Approver projectManager = new ProjectManager("项目管理者");
            Approver departManager  = new DepartManager("部门管理者");
            Approver ceo            = new Ceo("CEO");

            // 设置责任链
            projectManager.NextApprover = departManager;
            departManager.NextApprover  = ceo;

            // 处理请求
            projectManager.ProcessRequest(leaveRequest1);
            projectManager.ProcessRequest(leaveRequest2);
            projectManager.ProcessRequest(leaveRequest3);
            projectManager.ProcessRequest(leaveRequest4);

            #endregion

            Console.WriteLine("------------------------------");

            #region 访问者模式

            Visitor visitor = new VisitorImp();
            var     app     = new AppStructure(visitor);

            FinancialManagement financialManagement = new Bank();
            financialManagement.SaveMoney();
            app.Process(financialManagement);


            financialManagement = new Yeb();
            financialManagement.SaveMoney();
            app.Process(financialManagement);


            financialManagement = new Jj();
            financialManagement.SaveMoney();
            app.Process(financialManagement);

            #endregion

            Console.WriteLine("------------------------------");

            #region 备忘录模式

            var persons = new List <ContactPerson>()
            {
                new ContactPerson {
                    Name = "A", MobileNumber = "13533332222"
                },
                new ContactPerson {
                    Name = "B", MobileNumber = "13966554433"
                },
                new ContactPerson {
                    Name = "C", MobileNumber = "13198765544"
                }
            };

            //手机名单发起人
            var mobileOriginator = new MobileBackOriginator(persons);
            mobileOriginator.Show();

            // 创建备忘录并保存备忘录对象
            var manager = new MementoManager {
                ContactPersonMemento = mobileOriginator.CreateMemento()
            };

            // 更改发起人联系人列表
            Console.WriteLine("----移除最后一个联系人--------");
            mobileOriginator.ContactPersonList.RemoveAt(2);
            mobileOriginator.Show();

            // 恢复到原始状态
            Console.WriteLine("-------恢复联系人列表------");
            mobileOriginator.RestoreMemento(manager.ContactPersonMemento);
            mobileOriginator.Show();

            #endregion

            #region 解释器模式

            Console.WriteLine("------------------------------");

            const string roman = "六千四百五十二";
            var          interpreterContext = new InterpreterContext(roman);
            var          tree = new ArrayList
            {
                new GeExpression(),
                new ShiExpression(),
                new BaiExpression(),
                new QianExpression()
            };
            foreach (Expression exp in tree)
            {
                exp.Interpreter(interpreterContext);
            }
            Console.Write(interpreterContext.Data);

            #endregion

            Console.ReadKey();
        }