/// <summary>
        /// Instantiate a Table by directly deserializing byte data from the given Deserializer.
        /// </summary>
        /// <param name="input">The Deserializer providing the data for the table.</param>
        internal TableBase(Deserializer input)
        {
            // Total byte length of the table data (ignored).
            int tableLength = input.ReadInt32();

            // Total byte length of the Table metadata.
            int tableMetadataLength = input.ReadInt32();

            // Status code (custom user-set value).
            this.Status = input.ReadSByte();
            // Column Count.
            this.ColumnCount = input.ReadInt16();

            // Initialize column-driven data store.
            ColumnType = new DBType[this.ColumnCount];
            Column = new object[this.ColumnCount];

            // Read column data types.
            for (short c = 0; c < this.ColumnCount; c++)
                ColumnType[c] = (DBType)input.ReadSByte();

            // Read column names.
            this.ColumnNameData = input.ReadRaw(tableMetadataLength - 3 - this.ColumnCount);

            // Row count.
            this.RowCount = input.ReadInt32();
        }
Exemple #2
0
        public static IDBProvider InitProvider(DBType type, IPEndPoint ep, string user, string pwd, object other)
        {
            IDBProvider provider = null;
            switch (type)
            {
                case DBType.MSSQL:
                    {
                        provider = new MSSQLProvider();
                        provider.Username = user;
                        provider.Password = pwd;
                        provider.SetConnectionBuilder(ep, user, pwd);
                    }
                    break;
                case DBType.MYSQL:
                    {

                    }
                    break;
                case DBType.ORACLE:
                    {

                    }
                    break;
                default:
                    {
                        provider = null;
                    }
                    break;
            }
            return provider;
        }
        public WebConfigImpl(FileInfo fileInfo)
        {
            Debug.Assert(null != fileInfo);
            if (!fileInfo.Exists) throw new InvalidDataException("fileInfo file does not exists.");

            string xsd = "http://chernoivanov.org/SmsDeliveryTest";
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(fileInfo.FullName);
            XmlNamespaceManager names = new XmlNamespaceManager(xDoc.NameTable);
            names.AddNamespace("a", xsd);

            XmlNode node = xDoc.SelectSingleNode("//a:DB", names);
            this.dbType = (DBType)Enum.Parse(typeof(DBType), node.Attributes["type"].Value, true);
            this.dbConnectionString = Utils.formatText(node.SelectSingleNode("a:ConnectionString/text()", names).Value).Replace("; ", ";");

            XmlNodeList nodes = xDoc.SelectNodes("//a:AudioFiles/*", names);

            if (0 == nodes.Count)
                throw new InvalidDataException("No nodes in AudioFiles");
            foreach (XmlNode n in xDoc.SelectNodes("//a:AudioFiles/*", names))
            {
                WebFileConfigImpl fileCfg = new WebFileConfigImpl(
                    n.Attributes["DirectoryForAudioFiles"].Value, 
                    n.Attributes["AudioFileExtension"].Value);
                senderConfigDictionary.Add(n.Attributes["MailSender"].Value, fileCfg);
            }
        }
Exemple #4
0
 public void Put(DBType typecode, int size, string value)
 {
     SortedList<int, string> map;
     if (!weighted.TryGetValue(typecode, out map))
     {
         weighted[typecode] = map = new SortedList<int, string>();
     }
     map[size] = value;
 }
Exemple #5
0
 public string Get(DBType typecode, int size, int precision, byte scale)
 {
     if (size == 0 && precision == 0 && scale == 0)
         return Get(typecode);
     SortedList<int, string> map;
     weighted.TryGetValue(typecode, out map);
     if (map != null && map.Count > 0)
         foreach (KeyValuePair<int, string> entry in map)
             if (size <= entry.Key || precision > 0 || scale > 0)
                 return Replace(entry.Value, size, precision, scale);
     return Replace(Get(typecode), size, precision, scale);
 }
Exemple #6
0
        protected override void ConvertDBTypeToNativeType(IDbDataParameter p, DBType dbType)
        {
            if (SetSqlDbType == null)
            {
                SetSqlDbType = p.GetType().Module.GetType("System.Data.SqlServerCe.SqlCeParameter").GetProperty("SqlDbType", BindingFlags.Public | BindingFlags.Instance).GetSetter();

            }
            if (SetSqlDbType != null)
                SetSqlDbType(p, (SqlDbType)(int)dbType);
            else
                base.ConvertDBTypeToNativeType(p, dbType);
        }
Exemple #7
0
 public static IHaveDbProvider GetProvider(DBType type)
 {
     switch (type)
     {
         case DBType.SqlServer: return new SqlServerProvider();
         case DBType.SqlServerCE: return new SqlServerCEProvider();
         case DBType.MySql: return new MySqlProvider();
         case DBType.PostgreSQL:return new PostgresProvider();
         case DBType.Oracle:return new OracleProvider();
         case DBType.SQLite:return new SqliteProvider();
     }
     throw new Exception("Unkown provider");
 }
 private static string GetDBTypeString(DBType dbType)
 {
     switch (dbType)
     {
         case DBType.Date:
             return "Date";
         case DBType.Integer:
             return "Integer";
         case DBType.NVarChar:
             return "Nvarchar";
         default:
             return "Ntext";
     }
 }
 public static IDBDialog GetDBDialog(DBType dbTypeName)
 {
     switch (dbTypeName)
     {
         case DBType.Oracle:
             return new OracleDBDialog();
         case DBType.MySql:
             return new MySQLDBDialog();
         case DBType.SqlServer:
             return new SqlServerDBDialog();
         default:
             return null;
     }
 }
Exemple #10
0
 private void button2_Click(object sender, EventArgs e)
 {
     DbSettings dialog = new DbSettings();
     DialogResult result = dialog.ShowDialog(this);
     if (result == DialogResult.OK)
     {
         DBType = dialog.DBType;
         DbUser = dialog.DBUser;
         DbPass = dialog.DBPass;
         DbName = dialog.DBName;
         DbAddr = dialog.DBAddr;
         DbTNam = dialog.DBTNam;
     }
 }
Exemple #11
0
        /// <summary>
        /// 获取连接字符串
        /// </summary>
        /// <param name="dbType">数据库类型</param>
        /// <param name="server">host地址</param>
        /// <param name="port">SqlServer默认端口:1433,MySql默认端口:3306,SqlServer默认端口:1433,Oracle默认端口:1521,PostgreSql默认端口:5432,DB2默认端口:50000</param>
        /// <param name="databBase">数据库名称</param>
        /// <param name="uid">用户名</param>
        /// <param name="pwd">密码</param>
        /// <returns>连接字符串</returns>
        public static string GetConnectionString(DBType dbType, string server, int?port, string databBase, string uid, string pwd, int connTimeOut = 60)
        {
            server    = (server ?? string.Empty).Trim();
            databBase = (databBase ?? string.Empty).Trim();
            uid       = (uid ?? string.Empty).Trim();

            string connectionString = string.Empty;

            switch (dbType)
            {
            case DBType.SqlServer:
                connectionString = string.Format(@"server={0}{1};database={2};uid={3};pwd={4};connection timeout={5}", server, (port.HasValue ? ("," + port.Value) : string.Empty), databBase, uid, pwd, connTimeOut);
                break;

            case DBType.MySql:
                connectionString = string.Format(@"Server={0};{1}Database={2};User={3};Password={4};OldGuids=True;connection timeout={5}", server, (port.HasValue ? ("Port=" + port.Value + ";") : string.Empty), databBase, uid, pwd, connTimeOut);
                break;

            case DBType.Oracle:
                connectionString = string.Format("Data Source={0}:{1}/{2};User Id={3};password={4};Pooling=true;connection timeout={5}", server, (port ?? 1521), databBase, uid, pwd, connTimeOut);
                break;

            case DBType.OracleDDTek:
                connectionString = string.Format("Host={0};Port={1};Service Name={2};User ID={3};Password={4};PERSIST SECURITY INFO=True;connection timeout={5}", server, (port ?? 1521), databBase, uid, pwd, connTimeOut);
                break;

            case DBType.PostgreSql:
                connectionString = string.Format("host={0};{1}database={2};user id={3};password={4};timeout={5}", server, (port.HasValue ? ("port=" + port.Value + ";") : string.Empty), databBase, uid, pwd, connTimeOut);
                break;

            case DBType.SQLite:
                //connectionString = string.Format("Data Source={0};Pooling=True;BinaryGUID=True;Enlist=N;Synchronous=Off;Journal Mode=WAL;Cache Size=5000;", databBase);
                connectionString = string.Format("Data Source={0};", databBase);
                if (!string.IsNullOrWhiteSpace(pwd))
                {
                    connectionString += "version=3;password="******"server={0}:{1};Database={2};Uid={3};Pwd={4};connection timeout={5}", server, (port ?? 50000), databBase, uid, pwd, connTimeOut);
                break;

            default:
                throw new ArgumentException("未知数据库类型!");
            }
            return(connectionString);
        }
Exemple #12
0
        /// <summary>
        /// 根据数据库类型设置默认用户名等 扩展修改 2019-01-24 21:23
        /// </summary>
        private void SetUserNameByDbType()
        {
            btnSelectFile.Visible = false;

            TxtHost.Enabled  = true;
            TxtPort.Enabled  = true;
            TxtUName.Enabled = true;

            labDBName.Text = "数据库";
            DBType dbtype = (DBType)Enum.Parse(typeof(DBType), cboDBType.Text.ToString());

            if (dbtype == DBType.SqlServer)
            {
                TxtUName.Text = "sa";
            }
            else if (dbtype == DBType.MySql)
            {
                TxtUName.Text = "root";
            }
            else if (dbtype == DBType.Oracle || dbtype == DBType.OracleDDTek)
            {
                TxtUName.Text  = "scott";
                labDBName.Text = "服务名";
            }
            else if (dbtype == DBType.PostgreSql)
            {
                TxtUName.Text = "postgres";
            }
            else if (dbtype == DBType.DB2)
            {
                TxtUName.Text = "db2admin";
            }
            else if (dbtype == DBType.SQLite)
            {
                btnSelectFile.Visible = true;

                TxtHost.Enabled  = false;
                TxtPort.Enabled  = false;
                TxtUName.Enabled = false;

                //暂不支持 加密的 Sqlite数据库
                TxtPwd.Enabled = false;
            }
            else
            {
                TxtUName.Text = "";
            }
        }
Exemple #13
0
        [TestMethod] public void LookupCollection()
        {
            // Arrange
            var type = typeof(List <string>);

            // Act
            var           supported = DBType.IsSupported(type);
            Func <DBType> action    = () => DBType.Lookup(type);

            // Assert
            supported.Should().BeFalse();
            action.Should().ThrowExactly <ArgumentException>()
            .WithAnyMessage()
            .And
            .ParamName.Should().NotBeNullOrEmpty();
        }
        /// <summary>
        /// 获得like语句链接符
        /// </summary>
        /// <param name="databaseType"></param>
        /// <returns></returns>
        public static string GetLikeConnectorWords(DBType databaseType)
        {
            string result = "+";

            switch (databaseType)
            {
            case DBType.PostgreSQL:
            case DBType.Oracle:
            case DBType.MySql:
            case DBType.SQLite:
                result = "||";
                break;
            }

            return(result);
        }
Exemple #15
0
        /// <summary>
        /// 資料庫類型
        /// </summary>
        /// <returns></returns>
        private static string Get_DBType(DBType t)
        {
            string result = "";

            switch ((int)t)
            {
            case 0:
                result = "Port=5432;";
                break;

            case 1:
                result = "Port=1433;";
                break;
            }
            return(result);
        }
Exemple #16
0
        private DataAccess.Record _GeneralRecord(DataRow dataRow, DBType type)
        {
            DataAccess.Record record = new DataAccess.Record("hqftable2");
            record.emLgdbId = "123";
            record.TableId  = "1222";
            foreach (DataColumn dc in dataRow.Table.Columns)
            {
                record.AddField(dc.ColumnName
                                , dataRow[dc]
                                , _SetFieldType(dc)
                                , IsKey(dc.ColumnName));
            }
            record.dbType = type;

            return(record);
        }
Exemple #17
0
        public static string GetCreateSqlScript(Type ty, DBType DBType = DBType.SqlServer)
        {
            var           props = ty.GetProperties();
            StringBuilder sbSql = new StringBuilder();

            sbSql.AppendFormat("create table {0}", ty.Name);
            sbSql.Append("(");
            for (int j = 0; j < props.Length; j++)
            {
                PropertyInfo pInfo   = props[j];
                string       colType = GetColTypeByProperty(pInfo, DBType);
                sbSql.Append(colType + " " + ((j == props.Length - 1) ? "" : ","));
            }
            sbSql.Append(")");
            return(sbSql.ToString());
        }
Exemple #18
0
        //获取数据库连接字符串的key
        public static string GetConnectionStringKey(DBType dbType)
        {
            string sqlStrKey = "sqlStrTest";

            switch (dbType)
            {
            case DBType.LogTrace:
                sqlStrKey = AppConfig.GetFinalConfig("UserCfg_TraceDBConKey", "logTraceSqlStr", LogApi.GetUserCfg_TraceDBConKey());
                break;

            case DBType.LogMonitor:
                sqlStrKey = AppConfig.GetFinalConfig("UserCfg_MonitorDBConKey", "logMonitorSqlStr", LogApi.GetUserCfg_MonitorDBConKey());
                break;
            }
            return(sqlStrKey);
        }
Exemple #19
0
        public DBManager()
        {
            var url   = System.Environment.GetEnvironmentVariable("MysqlDBUrl");
            var uid   = System.Environment.GetEnvironmentVariable("MysqlDBUser");
            var port  = System.Environment.GetEnvironmentVariable("MysqlDBPort");
            var passd = System.Environment.GetEnvironmentVariable("MysqlDBPassword");

            this.str = "Server=" + url
                       + ";Port=" + port
                       + ";Database=zhuae;Uid=" + uid
                       + ";Pwd=" + passd
                       + ";CharSet=utf8mb4; SslMode =none;";

            Console.Write(this.str);
            this.dbt = DBType.Mysql;
        }
Exemple #20
0
        public static IDBHelper GetDBInstance(string connectStr, DBType dbType)
        {
            IDBHelper dbHelper = null;

            switch (dbType)
            {
            case DBType.Sqlite:
                dbHelper = new DBGen.DBHelpers.SQLiteHelper(connectStr);
                break;

            case DBType.SqlServer:
                dbHelper = new DBGen.DBHelpers.SQLServerHelper(connectStr);
                break;
            }
            return(dbHelper);
        }
Exemple #21
0
        private void initialForm()
        {
            DBType type = ConfigManager.GetCurrentDBType();

            if (type == DBType.sqlserver)
            {
                this.comboBox1.SelectedIndex = 0;
            }
            else if (type == DBType.sqlite)
            {
                this.comboBox1.SelectedIndex = 1;
            }
            string connStr = ConfigManager.GetDBConnectString(type);

            this.txtConnString.Text = connStr;
        }
Exemple #22
0
        public static object CreateObject(DBType e)
        {
            switch (e)
            {
            case DBType.Online:
                return(new D_Online());

            case DBType.EmployeeLogin:
                return(new D_EmployeeLogin());

            case DBType.AdminLogin:
                return(new D_AdminLogin());

            case DBType.Supplier:
                return(new D_Supplier());

            case DBType.Purchase:
                return(new D_Purchase());

            case DBType.Purchase_Body:
                return(new D_Purchase_Body());

            case DBType.Material:
                return(new D_Material());

            case DBType.Invoice:
                return(new D_Invoice());

            case DBType.AuditFlow:
                return(new D_AuditFlow());

            case DBType.AuditRecord:
                return(new D_AuditRecord());

            case DBType.AuditAccess:
                return(new D_AuditAccess());

            case DBType.TokenTable:
                return(new D_TokenTable());

            case DBType.Access:
                return(new D_Access());

            default:
                return(null);
            }
        }
Exemple #23
0
        public static String Genrate(String tabName, String dbConfig, String dbStr, DBType dbType)
        {
            string        className = ConvertHelper.TableNameToClassName(tabName);
            StringBuilder column    = new StringBuilder();
            StringBuilder param     = new StringBuilder();
            StringBuilder clmparam  = new StringBuilder();
            StringBuilder clazzclm  = new StringBuilder();

            String result = template.Replace("$dbconfig$", dbConfig).Replace("$classname$", className).Replace("$tabname$", tabName);

            if (!string.IsNullOrEmpty(dbStr))
            {
                List <String> flist = new List <String>();
                if (dbType == DBType.MySql)
                {
                    flist = MySqlHelper.GetFields(dbStr, tabName);
                }
                if (dbType == DBType.SqlService)
                {
                    flist = SqlServiceHelper.GetFields(dbStr, tabName);
                }
                if (flist.Count > 0)
                {
                    foreach (var o in flist)
                    {
                        if (!o.ToLower().Equals("id"))
                        {
                            string paramStr = ConvertHelper.TableNameToClassName(o);
                            column.Append(o + ",");

                            param.Append("@" + paramStr + ",");
                            if (!o.ToLower().Contains("create"))
                            {
                                clmparam.Append(o + "=@" + paramStr + ",");
                            }

                            clazzclm.Append(o + " as " + paramStr + ",");
                        }
                    }
                }
                result = result.Replace("$column=param$", clmparam.ToString().Trim(',')).
                         Replace("$param$", param.ToString().Trim(',')).
                         Replace("$column$", column.ToString().Trim(',')).
                         Replace("$clazzclm$", clazzclm.ToString().Trim(','));
            }
            return(result);
        }
Exemple #24
0
        public void onUserDBRemoving(DBType dbType, int dbIndex)
        {
            switch (dbType)
            {
            case DBType.Group:
                onGroupRemoving(dbIndex);
                break;

            case DBType.User:
                removeUserConnection(dbIndex);
                break;

            case DBType.Monitor:
                onMonitorRemoving(dbIndex);
                break;
            }
        }
Exemple #25
0
        public string General(Record record)
        {
            DBType        dbType         = record.Connection.ConnectionType;
            List <Field>  keyFields      = GetKeyFields(record);
            StringBuilder sbChkCondition = new StringBuilder();

            foreach (Field field in keyFields)
            {
                sbChkCondition.Append(string.Format(@"{0}={1} and ", field.Name, _formatFieldValue(field, dbType)));
            }
            if (sbChkCondition.Length >= 5)
            {
                sbChkCondition = sbChkCondition.Remove(sbChkCondition.Length - 5, 5);
            }

            return(sbChkCondition.ToString());
        }
        public static String UIDName(DBType dbType)
        {
            var db  = DBConnectionString(dbType);
            var idx = 0;

            if (IsDB2(dbType))
            {
                idx = db.IndexOf("UID=", System.StringComparison.Ordinal);
            }
            else if (IsMSSQL(dbType))
            {
                idx = db.IndexOf("User Id=", System.StringComparison.Ordinal);
            }
            var nextIdx = db.IndexOf(';', idx);

            return(db.Substring(idx, nextIdx - idx).Split('=')[1]);
        }
        /// <summary>
        /// 构造函数注入。单例模式。
        /// </summary>
        /// <param name="dbType"></param>
        private DBFactory(DBType dbType)
        {
            switch (dbType)
            {
            case DBType.sql:
                dBUtil = SqlDBUtil.SingleSqlDBUtil();
                break;

            case DBType.access:
                dBUtil = AccessUtil.SingleSqlDBUtil();
                break;

            default:
                dBUtil = SqlDBUtil.SingleSqlDBUtil();
                break;
            }
        }
Exemple #28
0
        public static void SerializeTest()
        {
            var target = new DBType
            {
                Memo = "Memo"
            };
            var changedPropertyList = new List <string>();

            target.PropertyChanged += (sender, args) => { changedPropertyList.Add(args.PropertyName); };

            var clone = DeepCloner.DeepClone(target);

            Assert.IsTrue(clone.Equals(target));

            // プロパティ変更通知が発火していないこと
            Assert.AreEqual(changedPropertyList.Count, 0);
        }
Exemple #29
0
        /// <summary>
        /// 创建Database对象
        /// </summary>
        public static Database CreateDatabase(string strconn, DBType DBType)
        {
            //strconn = UBase.DES_Decrypt(strconn);//数据库连接字符串,DES解密
            #region Sqllite
            if (DBType == DBType.SqlLite)
            {
                strconn = string.Format("Data Source={0}", strconn);
                System.Data.SQLite.SQLiteDataAdapter mysqlda = new System.Data.SQLite.SQLiteDataAdapter();
                mysqlda.SelectCommand            = new System.Data.SQLite.SQLiteCommand();
                mysqlda.SelectCommand.Connection = new SQLiteConnection(strconn);
                return(new Database(mysqlda, DBType.SqlLite));
            }
            #endregion

            #region MYSQL
            if (DBType == DBType.MySql)
            {
                //Host=127.0.0.1;UserName=root;Password=123;Database=huizhan;Port=4002;CharSet=utf8;Allow Zero Datetime=true;
                MySql.Data.MySqlClient.MySqlDataAdapter mysqlda = new MySql.Data.MySqlClient.MySqlDataAdapter();
                mysqlda.SelectCommand            = new MySql.Data.MySqlClient.MySqlCommand();
                mysqlda.SelectCommand.Connection = new MySql.Data.MySqlClient.MySqlConnection(strconn);
                return(new Database(mysqlda, DBType.MySql));
            }
            #endregion

            #region MSSQL
            if (DBType == DBType.MSSQL)
            {
                SqlDataAdapter sqlda = new SqlDataAdapter();
                sqlda.SelectCommand            = new SqlCommand();
                sqlda.SelectCommand.Connection = new SqlConnection(strconn);
                return(new Database(sqlda, DBType.MSSQL));
            }
            #endregion

            #region Oracle
            if (DBType == DBType.Oracle)
            {
                MySql.Data.MySqlClient.MySqlDataAdapter mysqlda = new MySql.Data.MySqlClient.MySqlDataAdapter();
                mysqlda.SelectCommand            = new MySql.Data.MySqlClient.MySqlCommand();
                mysqlda.SelectCommand.Connection = new MySql.Data.MySqlClient.MySqlConnection(strconn);
                return(new Database(mysqlda, DBType.MySql));
            }
            #endregion
            return(null);
        }
Exemple #30
0
        private void BtnTestConnect_Click(object sender, EventArgs e)
        {
            DBType type = (DBType)Enum.Parse(typeof(DBType), cboDBType.Text);

            try
            {
                if (type == DBType.Oracle && string.IsNullOrWhiteSpace(cboDBName.Text))
                {
                    throw new Exception("Oracle没有提供数据库名称查询支持,请输入服务名!");
                }

                string strDBName = cboDBName.Text;

                //DBUtils.Instance = DBMgr.UseDB(type, TxtHost.Text,
                //    (string.IsNullOrWhiteSpace(TxtPort.Text) ? null : new Nullable<int>(Convert.ToInt32(TxtPort.Text))),
                //    strDBName, TxtUName.Text, TxtPwd.Text,
                //    (string.IsNullOrWhiteSpace(txtConnTimeOut.Text) ? 60 : Convert.ToInt32(txtConnTimeOut.Text))
                //    , 300);

                this.InitDb(type, strDBName);

                var info = DBUtils.Instance.Info;

                cboDBName.Items.Clear();
                foreach (var dbName in info.DBNames)
                {
                    cboDBName.Items.Add(dbName);
                }
                cboDBName.SelectedItem = strDBName;

                // TODO 此段代码需注释,连接测试成功会触发数据库类型下拉框控件事件 2019-01-24 21:14
                //cboDBType.Items.Clear();
                //foreach (var item in FormUtils.DictDBType)
                //{
                //    cboDBType.Items.Add(item.Value.ToString());
                //}
                //cboDBType.SelectedItem = type.ToString();

                this.Text = "连接服务器成功!";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
        }
Exemple #31
0
        private void OnUserDBEdited(DBType dbType)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new updateDataDelegate(OnUserDBEdited), dbType);
                return;
            }

            UpdateUIView(dbType);

            switch (dbType)
            {
            case DBType.User:
                reloadDataGrid(dataGridViewGroup, groupPresenter.GetGroupsTable());
                break;
            }
        }
Exemple #32
0
        public static List <UpdateItem> NewStack(TECObject toSave)
        {
            DBType type = DBType.Bid;

            if (toSave is TECTemplates)
            {
                type = DBType.Templates;
            }
            List <UpdateItem> saveStack = new List <UpdateItem>();

            saveStack.AddRange(newStackForObject(toSave));
            if (toSave is IRelatable saveable)
            {
                saveStack.AddRange(DeltaStacker.ChildStack(Change.Add, saveable, type));
            }
            return(saveStack);
        }
Exemple #33
0
        public static DBType GetDBType()
        {
            DBType res = DBType.MSS;

            string provider = ConfigurationManager.ConnectionStrings["DataPlatformDB"].ProviderName;

            switch (provider)
            {
            case "Oracle.ManagedDataAccess.Client":
                res = DBType.ORA;
                break;

            default:
                break;
            }
            return(res);
        }
Exemple #34
0
        private static string GetDBTypeString(DBType dbType)
        {
            switch (dbType)
            {
            case DBType.Date:
                return("Date");

            case DBType.Integer:
                return("Integer");

            case DBType.NVarChar:
                return("Nvarchar");

            default:
                return("Ntext");
            }
        }
        public SQLHelper(string strConn, DBType dbtype)
        {
            switch (dbtype)
            {
            case DBType.SQLServer:
                this._DbCommand            = new SqlCommand();
                this._DbCommand.Connection = new SqlConnection(strConn);
                this._DbDataAdapter        = new SqlDataAdapter();
                break;

            case DBType.Access:
                this._DbCommand            = new OleDbCommand();
                this._DbCommand.Connection = new OleDbConnection(strConn);
                this._DbDataAdapter        = new OleDbDataAdapter();
                break;
            }
        }
Exemple #36
0
        private void InitializeColumnAttributeMapping(ColumnAttribute column)
        {
            this.name = string.IsNullOrEmpty(column.Name) ? this.memberInfo.Name : column.Name;

            if (column is KeyAttribute)
            {
                this.isPrimaryKey = true;

                this.key = (KeyAttribute)this.memberAttribute;

                this.isDbGenerated = this.isPrimaryKey && this.key.IsDbGenerated;

                this.sequenceName = this.key.SequenceName;
            }

            this.memberType = this.memberInfo.ReflectedType;
            this.dbType     = column.DbType;

            if (this.dbType == DBType.Char ||
                this.dbType == DBType.NChar ||
                this.dbType == DBType.NVarChar ||
                this.dbType == DBType.VarChar)
            {
                this.length = column.Length;
            }

            this.isNullable = this.isPrimaryKey ? false : column.IsNullable;
            this.isUnique   = this.isPrimaryKey ? true : column.IsUnique;

            if (column.IsVersion &&
                (this.dbType == DBType.Int16 ||
                 this.dbType == DBType.Int32 ||
                 this.dbType == DBType.Int64 ||
                 this.dbType == DBType.DateTime))
            {
                this.isVersion = true;
            }
            else
            {
                throw new MappingException(string.Format("Invalid Version member type '{0}' for  '{1}' , version type must be int or datetime type.",
                                                         this.dbType.ToString(),
                                                         this.entity.EntityType.Name + "." + this.memberInfo.Name));
            }

            this.updateCheck = column.UpdateCheck;
        }
Exemple #37
0
        /// <summary>
        /// 创建数据库实例
        /// </summary>
        /// <param name="dbType">数据库类型</param>
        /// <param name="connectString">数据库连接字符串</param>
        /// <returns></returns>
        public static AbstractDataBase Create(DBType dbType, string connectString)
        {
            switch (dbType)
            {
            case DBType.OleDb:
                return(new OleDb(connectString));

            case DBType.Odbc:
                return(new Odbc(connectString));

            case DBType.SqlServer:
                return(new SqlServer(connectString));

            default:
                return(null);
            }
        }
Exemple #38
0
        public static IDBManager GetInstance(DBType dbType, StringDictionary parameters)

        {
            switch (dbType)
            {
            case DBType.DocumentDB:
                if (_instance == null)
                {
                    _instance = CreateDocumentInstance(parameters);
                }
                break;

            default:
                break;
            }
            return(_instance);
        }
Exemple #39
0
        /// <summary>
        /// Metodo per la creazione di un reminder
        /// </summary>
        /// <param name="task"></param>
        /// <param name="infoUtente"></param>
        /// <returns></returns>
        public bool InsertReminder(DocsPaVO.Task.Task task, string subject, DocsPaVO.utente.InfoUtente infoUtente)
        {
            bool   result   = false;
            string query    = string.Empty;
            string function = "DocsPaDb.Query_DocsPAWS.Reminder.InsertReminder";

            logger.DebugFormat("{0} - START ", function);
            if (task == null)
            {
                logger.DebugFormat("{0} - Parameter task is null", function);
                logger.DebugFormat("{0} - END ");
                return(false);
            }

            try
            {
                DocsPaUtils.Query q = DocsPaUtils.InitQuery.getInstance().getQuery("I_DPA_REMINDER");
                if (DBType.ToUpper().Equals("ORACLE"))
                {
                    q.setParam("IdReminder", DocsPaDbManagement.Functions.Functions.GetSystemIdNextVal("DPA_REMINDER"));
                }

                q.setParam("IdTask", task.ID_TASK);
                q.setParam("IdUtenteMitt", task.UTENTE_MITTENTE.idPeople);
                q.setParam("IdUtenteDest", task.UTENTE_DESTINATARIO.idPeople);
                q.setParam("DtaScadenza", DocsPaDbManagement.Functions.Functions.ToDate(task.STATO_TASK.DATA_SCADENZA));
                q.setParam("NumInvii", "0");
                q.setParam("Descr", GetStringParameterValue(subject));

                query = q.getSQL();
                logger.DebugFormat("{0} - {1} ", function, query);
                if (!ExecuteNonQuery(query))
                {
                    throw new Exception("Errore durante la creazione del reminder: " + query);
                }

                result = true;
            }
            catch (Exception e)
            {
                logger.Error(function, e);
            }

            logger.DebugFormat("{0} - END", function);
            return(result);
        }
Exemple #40
0
        public static void ToBinaryTest(string testFilePath, DBType generatedData, int fileSize)
        {
            var generatedDataBuf = generatedData.ToBinary();

            using (var fs = new FileStream(testFilePath, FileMode.Open))
            {
                var length = (int)fs.Length;
                // ファイルサイズが規定でない場合誤作動防止の為テスト失敗にする
                Assert.AreEqual(length, fileSize);


                var fileData = new byte[length];
                fs.Read(fileData, 0, length);

                // binデータ出力
                fileData.Select((s, index) => $"=\"[{index}] = {{byte}} {s}\"").ToList()
                .ForEach(Console.WriteLine);

                Console.WriteLine();

                generatedDataBuf.Select((s, index) => $"=\"[{index}] = {{byte}} {s}\"").ToList()
                .ForEach(Console.WriteLine);

                for (var i = 0; i < generatedDataBuf.Length; i++)
                {
                    if (i == fileData.Length)
                    {
                        Assert.Fail(
                            $"データ帳が異なります。(期待値:{fileData.Length}, 実際:{generatedDataBuf.Length})");
                    }

                    if (fileData[i] != generatedDataBuf[i])
                    {
                        Assert.Fail(
                            $"offset: {i} のバイナリが異なります。(期待値:{fileData[i]}, 実際:{generatedDataBuf[i]})");
                    }
                }

                if (fileData.Length != generatedDataBuf.Length)
                {
                    Assert.Fail(
                        $"データ帳が異なります。(期待値:{fileData.Length}, 実際:{generatedDataBuf.Length})");
                }
            }
        }
Exemple #41
0
        public static IDBAccess Create(DBType type)
        {
            IDBAccess IRet = null;
            switch (type)
            {
                case DBType.Access:
                    IRet = new Access(type);
                    break;

                case DBType.SQL:
                    IRet = new SQL(type);
                    break;

                default:
                    break;
            }
            return IRet;
        }
Exemple #42
0
 public static string GetStatementByDBType(SQLStatementType statetype, DBType dbtype, object other)
 {
     string statement;
     switch (statetype)
     {
         case SQLStatementType.EXISTSLM:
             {
                 switch (dbtype)
                 {
                     case DBType.MSSQL:
                         {
                             statement = string.Format("select count(*) from master.dbo.sysobjects where xtype = 'U' and object_id(N'{0}') = id", Settings.Default.LMTABLE);
                         }
                         break;
                 }
             }
             break;
     }
     return null;
 }
Exemple #43
0
        public WorkingSet(string plantConnStr)
        {
            _dbType = Utility.GetDBType(plantConnStr);
              _connStrs[Constants.SPPID_PLANT_SCHEMA] = plantConnStr;

              if (Utility.GetDBType(plantConnStr) == DBType.ORACLE)
              {
            DataTable result = DBManager.Instance.ExecuteQuery(plantConnStr, Constants.ORACLE_GET_CURRENT_SCHEMA);

            if (result != null && result.Rows.Count > 0)
            {
              _plantSchema = result.Rows[0][0].ToString();
            }
              }
              else if (Utility.GetDBType(plantConnStr) == DBType.SQLServer)
              {
            //TODO: need to verify
            _plantSchema = "dbo";
              }
        }
Exemple #44
0
        SqlType(DBType dbType, int length)
        {
            this.DbType = dbType;
            this.Length = length;

            unchecked
            {
                hashCode = (dbType.GetHashCode() / 2) + (length.GetHashCode() / 2);
            }
        }
Exemple #45
0
        SqlType(DBType dbType, byte precision, byte scale)
        {
            this.DbType = dbType;
            this.Precision = precision;
            this.Scale = scale;

            unchecked
            {
                hashCode = (dbType.GetHashCode() / 3) + (precision.GetHashCode() / 3) + (scale.GetHashCode() / 3);
            }
        }
Exemple #46
0
 DB showForm(DBType t, DB db = null)
 {
     NewForm newForm = new NewForm(t);
     if (db != null) newForm.db = db;
     if (newForm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
     {
         return newForm.db;
     }
     return null;
 }
Exemple #47
0
 SqlType(DBType dbType)
 {
     this.DbType = dbType;
     hashCode = dbType.GetHashCode();
 }
 /// <summary>
 /// Execute คำสั่ง SQL ที่คืนค่าเป็นค่าเดียว
 /// </summary>
 /// <param name="strSql">SQL Query</param>
 /// <param name="strDBType">ชนิดของฐานข้อมูล เช่น sql,odbc,mysql</param>
 /// <param name="appsetting_name">ชื่อตัวแปรที่เก็บ ConnectionString ในไฟล์ AppSetting</param>
 /// <param name="outMessage">ข้อความ กรณีเกิดข้อผิดพลาด</param>
 /// <returns>ข้อมูล</returns>
 /// <example>
 /// string outMessage;
 /// clsSQL.Return("SELECT MAX(id) FROM member",clsSQL.DBType.MySQL,"cs",out outMessage);
 /// </example>
 public string Return(string strSql, DBType dbType, string appsetting_name, out string outMessage)
 {
     #region Variable
     var csSQL = System.Configuration.ConfigurationManager.AppSettings[appsetting_name];
     var strReturn = "";
     outMessage = "";
     #endregion
     #region Procedure
     if (!string.IsNullOrEmpty(csSQL))
     {
         if (dbType == DBType.SQLServer)
         {
             #region SQLServer
             var myConn_SQL = new SqlConnection(csSQL);
             var myCmd_SQL = new SqlCommand(strSql, myConn_SQL);
             try
             {
                 myConn_SQL.Open();
                 strReturn = myCmd_SQL.ExecuteScalar().ToString();
                 myConn_SQL.Close();
                 myCmd_SQL.Dispose();
             }
             catch (Exception ex)
             {
                 outMessage = ex.Message;
             }
             finally
             {
                 myCmd_SQL.Dispose();
                 myConn_SQL.Close();
             }
             #endregion
         }
         else if (dbType == DBType.ODBC)
         {
             #region ODBC
             var myConn_ODBC = new OdbcConnection(csSQL);
             var myCmd_ODBC = new OdbcCommand(strSql, myConn_ODBC);
             try
             {
                 myConn_ODBC.Open();
                 strReturn = myCmd_ODBC.ExecuteScalar().ToString();
                 myConn_ODBC.Close();
                 myCmd_ODBC.Dispose();
             }
             catch (Exception ex)
             {
                 outMessage = ex.Message;
             }
             finally
             {
                 myCmd_ODBC.Dispose();
                 myConn_ODBC.Close();
             }
             #endregion
         }
         else
         {
             strReturn = "";
             outMessage = "Not found DBType.";
         }
     }
     return strReturn;
     #endregion
 }
 /// <summary>
 /// Writes a DBType value (indicating the type of the next byte sequence).
 /// </summary>
 /// <param name="value">Value to write.</param>
 /// <returns>The serializer instance, ready to chain the next command.</returns>
 public Serializer Write(DBType value)
 {
     writer.WriteByte(unchecked((byte)value));
     return this;
 }
		private void selectSqlConnection(string connectionString, DBType dbType, string connectionName, bool isODBC)
		{
			if (!this.cbConnection.Items.OfType<LastDirectConnectionString>().Any(
				x => x.ConnectionString == connectionString
				&& x.IsODBC == isODBC
				)
			)
			{
				LastDirectConnectionString newItem = new LastDirectConnectionString()
				{
					DataBaseType     = dbType.Id.ToString(),
					ConnectionString = connectionString,
					IsODBC           = isODBC,
					Name             = connectionName
				};

				this.cbConnection.Items.Add(newItem);
				this.cbConnection.SelectedItem = newItem;
			}
			else
			{
				LastDirectConnectionString item =
					this.cbConnection.Items.OfType<LastDirectConnectionString>()
						.First(x => x.ConnectionString == connectionString && x.IsODBC == isODBC);

				this.cbConnection.SelectedItem = item;
			}
		}
Exemple #51
0
 protected void RegisterCastType(DBType code, string name)
 {
     castTypeNames.Put(code, name);
 }
		private void setModuleTypeItems(DBType selectedDbType)
		{
			if (selectedDbType != null && selectedDbType.ModuleTypes != null && selectedDbType.ModuleTypes.Count() > 0)
			{
				List<KeyValuePair<string, string>> moduleTypes = new List<KeyValuePair<string, string>>();

				foreach (ModuleType currentModuleType in selectedDbType.ModuleTypes)
				{
					i18n localeItem = currentModuleType.Locales.FirstOrDefault(
						l => l.Language == Program.Model.Settings.InterfaceLanguage);

					string localeText = localeItem != null ? localeItem.Text : currentModuleType.Id;

					moduleTypes.Add(new KeyValuePair<string, string>(localeText, currentModuleType.Id));
				}

				cbModuleType.DataSource = moduleTypes;
				cbModuleType.Enabled    = true;
			}
			else
			{
				cbModuleType.Enabled = false;
			}
		}
 public BaseProvider(string connectionStringName, DBType dbType)
     : base("KingSite.Purview", connectionStringName, dbType)
 {
 }
        //
        // System.Configuration.Provider.ProviderBase.Initialize Method
        //
        public override void Initialize(string name, NameValueCollection config)
        {
            //
            // Initialize values from web.config.
            //

            if (config == null)
                throw new ArgumentNullException("config");

            if (name == null || name.Length == 0)
                name = "KSP RoleProvider";

            if (String.IsNullOrEmpty(config["description"])) {
                config.Remove("description");
                config.Add("description", "KSP RoleProvider for sqlserver/mysql/oracle");
            }

            // Initialize the abstract base class.
            base.Initialize(name, config);

            _ApplicationName = Config.GetApplicationName();
            _KSPDBType = Config.GetDBType();
            _ConnectionStringName = Config.GetConnectionName();

            if (config["writeExceptionsToEventLog"] != null) {
                if (config["writeExceptionsToEventLog"].ToUpper() == "TRUE") {
                    _WriteExceptionsToEventLog = true;
                }
            }

            InitRepostory();
        }
 public Sys_UserInRoleRepository(string connectionStringName, DBType dbType)
     : base(connectionStringName, dbType)
 {
 }
Exemple #56
0
 internal static SqlType Get(DBType dbType, int length)
 {
     string key = GetKeyForLengthBased(dbType.ToString(), length);
     SqlType result;
     if (!SqlTypes.TryGetValue(key, out result))
     {
         result = new SqlType(dbType, length);
         lock (SqlTypes)
             SqlTypes.Add(key, result);
     }
     return result;
 }
Exemple #57
0
 public DBConnection(DBType newType)
 {
     currentDBType = newType;
 }
Exemple #58
0
 public SelectBuilder DB(DBType dbType)
 {
     DBType = dbType;
     return this;
 }
Exemple #59
0
 public DBMerge(string DBID, DBType type)
 {
     this.DBID = DBID;
     this.DBtype = type;
 }
    /// <summary>
    /// Execute คำสั่ง SQL ที่ใช้ในการบันทึกข้อมูล โดยสามารถระบุ SQL Parameter ได้
    /// </summary>
    /// <param name="strSql">SQL Query</param>
    /// <param name="arrParameter">SQL Parameter (new string[,] { { "?ID", txtTest.Text } })</param>
    /// <param name="strDBType">ชนิดของฐานข้อมูล เช่น sql,odbc,mysql</param>
    /// <param name="appsetting_name">ชื่อตัวแปรที่เก็บ ConnectionString ในไฟล์ AppSetting</param>
    /// <param name="outMessage">ข้อความ เมื่อเกิดข้อผิดพลาด</param>
    /// <returns>True=รันสำเร็จ , False=รันไม่สำเร็จ</returns>
    /// <example>
    /// string outMessage;
    /// clsSQL.Execute("UPDATE webboard_type SET type_name=?NAME WHERE type_id=?ID", new string[,] { { "?ID", txtTest.Text }, { "?NAME", "ใช้ Array 2 มิติ" } }, clsSQL.DBType.MySQL, "cs",out outMessage);
    /// </example>
    public bool Execute(string strSql, string[,] arrParameter, DBType dbType, string appsetting_name, out string outMessage)
    {
        #region Variable
        var csSQL = System.Configuration.ConfigurationManager.AppSettings[appsetting_name];
        var result = false;
        var i = 0;
        outMessage = "";
        #endregion
        #region Procedure
        if (!string.IsNullOrEmpty(csSQL) && arrParameter.Rank == 2)
        {
            if (dbType == DBType.SQLServer)
            {
                #region SQLServer
                var myConn_SQL = new SqlConnection(csSQL);
                var myCmd_SQL = new SqlCommand(strSql, myConn_SQL);

                for (i = 0; i < arrParameter.Length / arrParameter.Rank; i++)
                {
                    myCmd_SQL.Parameters.AddWithValue(arrParameter[i, 0], arrParameter[i, 1]);
                }

                try
                {
                    myConn_SQL.Open();
                    myCmd_SQL.ExecuteNonQuery();
                    myConn_SQL.Close();
                    myCmd_SQL.Dispose();
                    result = true;
                }
                catch (Exception ex)
                {
                    outMessage = ex.Message;
                    result = false;
                }
                finally
                {
                    myCmd_SQL.Dispose();
                    myConn_SQL.Close();
                }
                #endregion
            }
            else if (dbType == DBType.ODBC)
            {
                #region ODBC
                var myConn_ODBC = new OdbcConnection(csSQL);
                var myCmd_ODBC = new OdbcCommand(strSql, myConn_ODBC);

                for (i = 0; i < arrParameter.Length / arrParameter.Rank; i++)
                {
                    myCmd_ODBC.Parameters.AddWithValue(arrParameter[i, 0], arrParameter[i, 1]);
                }

                try
                {
                    myConn_ODBC.Open();
                    myCmd_ODBC.ExecuteNonQuery();
                    myConn_ODBC.Close();
                    myCmd_ODBC.Dispose();
                    result = true;
                }
                catch (Exception ex)
                {
                    outMessage = ex.Message;
                    result = false;
                }
                finally
                {
                    myCmd_ODBC.Dispose();
                    myConn_ODBC.Close();
                }
                #endregion
            }
            else
            {
                outMessage = "Not found DBType.";
                result = false;
            }
        }
        else
        {
            outMessage = "Not found AppSettingName.";
            result = false;
        }
        return result;
        #endregion
    }