Exemple #1
0
 static ConfigManger()
 {
     _dbBaseProvider = DbConnectionProvider.CreateDbProvider(ConnectKey);
     if (_dbBaseProvider == null)
     {
         string providerType     = ConfigUtils.GetSetting("PayDB_ProviderType");
         string connectionFormat = ConfigUtils.GetSetting("PayDB_ConnectionString");
         string dataSource       = string.Empty;
         string userInfo         = string.Empty;
         try
         {
             dataSource = ConfigUtils.GetSetting("PayDB_Server");
             userInfo   = ConfigUtils.GetSetting("PayDB_Acount");
             if (!string.IsNullOrEmpty(userInfo))
             {
                 userInfo = CryptoHelper.DES_Decrypt(userInfo, GameEnvironment.Setting.ProductDesEnKey);
             }
         }
         catch (Exception) { }
         string connectionString = "";
         if (!string.IsNullOrEmpty(dataSource) && !string.IsNullOrEmpty(userInfo))
         {
             connectionString = string.Format(connectionFormat, dataSource, userInfo);
         }
         _dbBaseProvider = DbConnectionProvider.CreateDbProvider(ConnectKey, providerType, connectionString);
     }
 }
Exemple #2
0
        //private MiddlewareSection section;

        public ServersDataProvider()
        {
            if (_provider == null)
            {
                _provider = DbConnectionProvider.CreateDbProvider(ConnectKey);

                var command = _provider.CreateCommandStruct("StaticServer", CommandMode.Inquiry, "ServerId,Name,Ip,Port");

                command.Parser();

                using (var dr = _provider.ExecuteReader(CommandType.Text, command.Sql, command.Parameters))
                {
                    var serversDatas = new ShareCacheStruct <StaticServer>();
                    while (dr.Read())
                    {
                        StaticServer oneServerModel = new StaticServer();
                        oneServerModel.ServerId = Convert.ToInt32(dr["ServerId"]);
                        oneServerModel.Name     = dr["Name"].ToString();
                        oneServerModel.Ip       = dr["Ip"].ToString();
                        oneServerModel.Port     = Convert.ToInt32(dr["Port"]);
                        //ServerList.Add(oneServerModel);
                        serversDatas.Add(oneServerModel);
                    }
                }
                //this.AddATestCache();
            }
        }
Exemple #3
0
        protected override IList <UserRank> GetCacheList()
        {
            if (rankList.Count > 0)
            {
                return(rankList);
            }
            var    dbProvider = DbConnectionProvider.CreateDbProvider(DbConfig.Data);
            string sql        = "SELECT GameUser.[UserID],GameUser.[NickName],GameUser.[CombatNum],GameUser.[VictoryNum], GameUser.[RankID],GameUser.[UserLv],GameUser.[ObtainNum],GameUser.GameCoin,GameUser.VipLv,GameUser.CountryID,GameUser.[SportsIntegral],GameUser.[RankDate] FROM GameUser where GameUser.RankID>0 order by GameUser.RankID";

            using (IDataReader reader = dbProvider.ExecuteReader(CommandType.Text, sql))
            {
                while (reader.Read())
                {
                    UserRank rankInfo = new UserRank();
                    rankInfo.UserID         = reader["UserID"].ToString();
                    rankInfo.NickName       = reader["NickName"].ToString();
                    rankInfo.UserLv         = Convert.ToInt16(reader["UserLv"]);
                    rankInfo.ObtainNum      = Convert.ToInt32(reader["ObtainNum"]);
                    rankInfo.TotalCombatNum = Convert.ToInt32(reader["CombatNum"]);
                    rankInfo.VictoryNum     = Convert.ToInt32(reader["VictoryNum"]);
                    rankInfo.GameCoin       = Convert.ToInt32(reader["GameCoin"]);
                    rankInfo.CountryID      = reader["CountryID"].ToEnum <CountryType>();
                    rankInfo.VipLv          = Convert.ToInt16(reader["VipLv"]);
                    //rankInfo.HeadID = reader["HeadID"].ToString();
                    rankInfo.RankId         = Convert.ToInt32(reader["RankID"]);
                    rankInfo.SportsIntegral = Convert.ToInt32(reader["SportsIntegral"]);
                    rankInfo.RankDate       = reader["RankDate"].ToDateTime();
                    rankList.Add(rankInfo);
                }
            }
            return(rankList);
        }
Exemple #4
0
        public void SetServerEnableDate(int gameId, int serverId, DateTime enableDate)
        {
            string key = GenerateKey(gameId, serverId);

            try
            {
                var dbProvider = DbConnectionProvider.CreateDbProvider("DirData");
                var command    = dbProvider.CreateCommandStruct("ServerInfo", CommandMode.Modify);
                command.AddParameter("EnableDate", enableDate);

                command.Filter           = dbProvider.CreateCommandFilter();
                command.Filter.Condition = string.Format("{0} AND {1}",
                                                         command.Filter.FormatExpression("ID"),
                                                         command.Filter.FormatExpression("GameID"));
                command.Filter.AddParam("ID", serverId);
                command.Filter.AddParam("GameID", gameId);
                command.Parser();
                dbProvider.ExecuteQuery(CommandType.Text, command.Sql, command.Parameters);
                ServerInfo serverInfo;
                if (TryGet(key, out serverInfo))
                {
                    serverInfo.EnableDate = enableDate;
                }
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("SetServerEnableDate {0}_{1} error:{2}", ContainerKey, key, ex);
            }
        }
Exemple #5
0
        private IDataReader GetReader <T>()
        {
            string sql = string.Empty;

            try
            {
                if (Capacity < 0 || _filter == null || _schema == null)
                {
                    TraceLog.WriteError("The {0} schema config is empty.", typeof(T).FullName);
                    return(null);
                }
                string tableName = _schema.GetTableName();
                if (string.IsNullOrEmpty(tableName))
                {
                    TraceLog.WriteError("The {0} schema table name is empty.", _schema.EntityType.FullName);
                    return(null);
                }

                DbBaseProvider dbprovider = DbConnectionProvider.CreateDbProvider(_schema);
                if (dbprovider == null)
                {
                    TraceLog.WriteError("The {0} ConnectKey:{1} is empty.", _schema.EntityType.FullName, _schema.ConnectKey);
                    return(null);
                }
                var command = dbprovider.CreateCommandStruct(tableName, CommandMode.Inquiry);
                var columns = _schema.GetColumnNames();
                command.Columns = string.Join(",", columns);
                command.OrderBy = (string.IsNullOrEmpty(_filter.OrderColumn) ? _schema.OrderColumn : _filter.OrderColumn) ?? "";
                if (Capacity < int.MaxValue && Capacity > 0)
                {
                    command.Top = Capacity;
                    if (string.IsNullOrEmpty(command.OrderBy))
                    {
                        string orderStr = "";
                        foreach (var key in _schema.Keys)
                        {
                            if (orderStr.Length > 0)
                            {
                                orderStr += ",";
                            }
                            orderStr += string.Format("{0}", dbprovider.FormatName(key));
                        }
                        command.OrderBy = orderStr;
                    }
                }
                command.Filter = dbprovider.CreateCommandFilter();

                command.Filter.Condition = MergerCondition(_filter.Condition, _schema.Condition);
                ParseDataParameter(command.Filter);

                command.Parser();
                sql = command.Sql;
                return(dbprovider.ExecuteReader(CommandType.Text, command.Sql, command.Parameters));
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("DB execute reader sql:\"{0}\" error:{1}", sql, ex);
            }
            return(null);
        }
Exemple #6
0
        private bool SendToDb <T>(T data, EntityPropertyGetFunc <T> getFunc, EnttiyPostColumnFunc <T> postColumnFunc, bool synchronous) where T : ISqlEntity
        {
            if (Equals(data, null))
            {
                return(false);
            }
            SchemaTable    schemaTable = EntitySchemaSet.Get(data.GetType());
            DbBaseProvider dbProvider  = DbConnectionProvider.CreateDbProvider(_connectKey ?? schemaTable.ConnectKey);

            if (dbProvider == null)
            {
                return(false);
            }
            CommandStruct command = GenerateCommand(dbProvider, data, schemaTable, getFunc, postColumnFunc);

            if (command != null)
            {
                bool result = (synchronous
                    ? dbProvider.ExecuteQuery(CommandType.Text, command.Sql, command.Parameters)
                    : dbProvider.ExecuteNonQuery(data.GetMessageQueueId(), CommandType.Text, command.Sql, command.Parameters)) > 0;
                data.ResetState();
                return(result);
            }
            return(false);
        }
Exemple #7
0
        internal bool ReloadServer(int gameID)
        {
            try
            {
                var dbProvider = DbConnectionProvider.CreateDbProvider("DirData");
                var command    = dbProvider.CreateCommandStruct("ServerInfo", CommandMode.Inquiry);
                command.Columns          = "ID,GameID,ServerName,BaseUrl,ActiveNum,Weight,isEnable,TargetServer,EnableDate,IntranetAddress";
                command.OrderBy          = "GameID asc, ID asc";
                command.Filter           = dbProvider.CreateCommandFilter();
                command.Filter.Condition = command.Filter.FormatExpression("GameID");
                command.Filter.AddParam("GameID", gameID);
                command.Parser();

                using (var reader = dbProvider.ExecuteReader(CommandType.Text, command.Sql, command.Parameters))
                {
                    LoadServer(reader);
                }
                return(true);
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("ReloadServer {0}_{1} error:{2}", ContainerKey, gameID, ex);
                return(false);
            }
        }
Exemple #8
0
        /// <summary>
        /// 检测数据表结构变动
        /// </summary>
        /// <param name="schema"></param>
        private static void CheckTableSchema(SchemaTable schema)
        {
            string tableName = schema.GetTableName();

            try
            {
                DbBaseProvider dbprovider = DbConnectionProvider.CreateDbProvider(schema);
                if (dbprovider == null)
                {
                    if (schema.StorageType.HasFlag(StorageType.ReadOnlyDB) ||
                        schema.StorageType.HasFlag(StorageType.ReadWriteDB) ||
                        schema.StorageType.HasFlag(StorageType.WriteOnlyDB))
                    {
                        TraceLog.WriteError("Not found DB connection key \"{1}\" of the {0} entity.", schema.EntityName, schema.ConnectKey);
                    }
                    return;
                }
                DbColumn[] columns;
                if (dbprovider.CheckTable(tableName, out columns))
                {
                    ModifyTableSchema(schema, dbprovider, tableName, columns);
                }
                else
                {
                    CreateTableSchema(schema, dbprovider, tableName);
                }
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("CheckTableSchema {0} error:{1}", tableName, ex);
            }
        }
        private static void OnCheckDynamicTable(string key, object value, CacheRemovedReason reason)
        {
            try
            {
                DateTime date = DateTime.Now;
                int      logPriorBuildMonth = GetEntitySection().LogPriorBuildMonth;
                var      tableTypes         = _dynamicTables.ToList();
                foreach (var schema in tableTypes)
                {
                    DbBaseProvider dbprovider = DbConnectionProvider.CreateDbProvider(schema);
                    if (dbprovider == null)
                    {
                        continue;
                    }
                    string tableName = "";
                    int    count     = logPriorBuildMonth > 1 ? logPriorBuildMonth : 2;
                    for (int i = 0; i < count; i++)
                    {
                        tableName = schema.GetTableName(date, i);

                        DbColumn[] columns;
                        if (!dbprovider.CheckTable(tableName, out columns))
                        {
                            CreateTableSchema(schema, dbprovider, tableName);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("OnCheckLogTable error:{0}", ex);
            }
        }
        /// <summary>
        /// 处理加载数据参数
        /// </summary>
        /// <param name="personalId"></param>
        /// <param name="isReplace"></param>
        /// <returns></returns>
        protected bool ProcessLoadParam(string personalId, bool isReplace)
        {
            string            redisKey     = CreateRedisKey(personalId);
            TransReceiveParam receiveParam = new TransReceiveParam(redisKey);

            receiveParam.Schema = SchemaTable();
            string paramName  = receiveParam.Schema.PersonalName;
            int    periodTime = receiveParam.Schema.PeriodTime;
            int    maxCount   = receiveParam.Schema.Capacity;

            var provider = DbConnectionProvider.CreateDbProvider(receiveParam.Schema);

            if (receiveParam.Schema.StorageType.HasFlag(StorageType.ReadOnlyDB) ||
                receiveParam.Schema.StorageType.HasFlag(StorageType.ReadWriteDB))
            {
                if (provider == null)
                {
                    TraceLog.WriteError("Not found db connection of {0} entity.", receiveParam.Schema.EntityName);
                    return(false);
                }
                var filter = new DbDataFilter(maxCount);
                if (!string.IsNullOrEmpty(personalId))
                {
                    filter.Condition = provider.FormatFilterParam(paramName);
                    filter.Parameters.Add(paramName, personalId);
                }
                receiveParam.DbFilter = filter;
            }
            return(TryLoadCache(personalId, receiveParam, periodTime, false));
        }
        public static bool IsNickName(string name)
        {
            bool bl = false;

            bl = new PersonalCacheStruct <UserBasisCache>().IsExist(u => u.NickName.ToLower() == name.ToLower().Trim());
            if (!bl)
            {
                var dbProvider = DbConnectionProvider.CreateDbProvider(DbConfig.Data);

                var command = dbProvider.CreateCommandStruct("UserBasisCache", CommandMode.Inquiry, "NickName");
                command.Filter           = dbProvider.CreateCommandFilter();
                command.Filter.Condition = command.Filter.FormatExpression("NickName");
                command.Filter.AddParam("NickName", name);
                command.Parser();
                using (var reader = dbProvider.ExecuteReader(CommandType.Text, command.Sql, command.Parameters))
                {
                    while (reader.Read())
                    {
                        bl = true;
                    }
                }
            }

            return(bl);
        }
Exemple #12
0
        static ConfigManger()
        {
            _dbBaseProvider = DbConnectionProvider.CreateDbProvider(ConnectKey);
            if (_dbBaseProvider == null)
            {
                //todo is expired format

                /*
                 * string providerType = ConfigUtils.GetSetting("PayDB_ProviderType");
                 * string connectionFormat = ConfigUtils.GetSetting("PayDB_ConnectionString");
                 * string dataSource = string.Empty;
                 * string userInfo = string.Empty;
                 * try
                 * {
                 *  dataSource = ConfigUtils.GetSetting("PayDB_Server");
                 *  userInfo = ConfigUtils.GetSetting("PayDB_Acount");
                 *  if (!string.IsNullOrEmpty(userInfo))
                 *  {
                 *      userInfo = CryptoHelper.DES_Decrypt(userInfo, GameEnvironment.Setting.ProductDesEnKey);
                 *  }
                 * }
                 * catch (Exception) { }
                 * string connectionString = "";
                 * if (!string.IsNullOrEmpty(dataSource) && !string.IsNullOrEmpty(userInfo))
                 * {
                 *  connectionString = string.Format(connectionFormat, dataSource, userInfo);
                 * }
                 * _dbBaseProvider = DbConnectionProvider.CreateDbProvider(ConnectKey, providerType, connectionString);
                 */
            }
        }
Exemple #13
0
        private bool SendToDb <T>(T data, EntityPropertyGetFunc <T> getFunc, EnttiyPostColumnFunc <T> postColumnFunc, bool synchronous) where T : ISqlEntity
        {
            if (Equals(data, null))
            {
                return(false);
            }
            SchemaTable    schemaTable = EntitySchemaSet.Get(data.GetType());
            DbBaseProvider dbProvider  = DbConnectionProvider.CreateDbProvider(_connectKey ?? schemaTable.ConnectKey);

            if (dbProvider == null)
            {
                return(false);
            }
            CommandStruct command = GenerateCommand(dbProvider, data, schemaTable, getFunc, postColumnFunc);

            if (command != null)
            {
                int result;
                if (synchronous)
                {
                    //同时采集
                    ProfileManager.PostSqlOfMessageQueueTimes(command.TableName, 1);
                    ProfileManager.ProcessSqlOfMessageQueueTimes(command.TableName);
                    result = dbProvider.ExecuteQuery(CommandType.Text, command.Sql, command.Parameters);
                }
                else
                {
                    //put into pool
                    result = dbProvider.ExecuteNonQuery(data.GetMessageQueueId(), CommandType.Text, command.TableName, command.Sql, command.Parameters);
                }
                data.ResetState();
                return(result > 0);
            }
            return(false);
        }
Exemple #14
0
        private void LoadUnlineUser()
        {
            TraceLog.ReleaseWrite("正在加载玩家数据...");
            List <string> userList = new List <string>();

            try
            {
                int              loadUnlineDay = ConfigUtils.GetSetting("LoadUnlineDay", "1").ToInt();
                int              maxCount      = ConfigUtils.GetSetting("MaxLoadCount", "100").ToInt();
                string           sql           = string.Format("SELECT top {0} [UserID] FROM GameUser where LoginDate>@LoginDate order by LoginDate desc", maxCount);
                IDataParameter[] para          = new SqlParameter[] {
                    SqlParamHelper.MakeInParam("@LoginDate", SqlDbType.DateTime, 0, DateTime.Now.Date.AddDays(-loadUnlineDay))
                };
                var dbProvider = DbConnectionProvider.CreateDbProvider(DbConfig.Data);
                using (IDataReader reader = dbProvider.ExecuteReader(CommandType.Text, sql, para))
                {
                    while (reader.Read())
                    {
                        userList.Add(reader["UserID"].ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("LoadUnlineUser:{0}", ex);
            }
            var cacheSet = new GameDataCacheSet <GameUser>();

            foreach (string userId in userList)
            {
                cacheSet.FindKey(userId);
            }
            TraceLog.ReleaseWrite("正在加载玩家结束");
        }
Exemple #15
0
        public void SendMutilDb()
        {
            var dbProvider = DbConnectionProvider.CreateDbProvider(MyDataConfigger.DbKey);
            var data       = new DataTable();

            data.Columns.Add("id", typeof(long));
            data.Columns.Add("name", typeof(string));
            data.Columns.Add("sex", typeof(bool));
            data.Columns.Add("money", typeof(decimal));
            data.Columns.Add("create_time", typeof(DateTime));
            for (int i = 0; i < 10; i++)
            {
                var dr = data.NewRow();
                dr["id"]          = i + 1;
                dr["name"]        = "晨test_" + i;
                dr["sex"]         = 1;
                dr["money"]       = 45.23;
                dr["create_time"] = DateTime.Now;
                data.Rows.Add(dr);
            }
            DbBulkOption option = new DbBulkOption()
            {
            };
            var watch  = Stopwatch.StartNew();
            var result = dbProvider.ExecuteBulkQuery("bulk_temp", data, option);

            Trace.WriteLine("result:" + result);
            WaitEnd(watch);
        }
Exemple #16
0
        /// <summary>
        /// 尝试接收数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="receiveParam"></param>
        /// <param name="dataList"></param>
        /// <returns>return null is load error</returns>
        public bool TryReceiveData <T>(TransReceiveParam receiveParam, out List <T> dataList) where T : AbstractEntity, new()
        {
            bool result = false;

            dataList = null;
            //表为空时,不加载数据
            if (receiveParam.Schema == null ||
                string.IsNullOrEmpty(receiveParam.Schema.Name) ||
                DbConnectionProvider.CreateDbProvider(receiveParam.Schema) == null)
            {
                //DB is optional and can no DB configuration
                dataList = new List <T>();
                return(true);
            }

            //配置库不放到Redis,尝试从DB加载
            if (receiveParam.Schema.AccessLevel == AccessLevel.ReadOnly)
            {
                return(_dbTransponder.TryReceiveData(receiveParam, out dataList));
            }

            if (!string.IsNullOrEmpty(receiveParam.RedisKey) &&
                _redisTransponder.TryReceiveData(receiveParam, out dataList))
            {
                if (dataList.Count > 0)
                {
                    return(true);
                }
                //从Redis历史记录表中加载
                result = TryLoadHistory(receiveParam.RedisKey, out dataList);
            }

            return(result);
        }
Exemple #17
0
        /// <summary>
        /// 检测数据表结构变动
        /// </summary>
        /// <param name="schema"></param>
        private static void CheckTableSchema(SchemaTable schema)
        {
            string tableName = schema.Name;

            try
            {
                DbBaseProvider dbprovider = DbConnectionProvider.CreateDbProvider(schema);
                if (dbprovider == null)
                {
                    return;
                }
                DbColumn[] columns;
                if (dbprovider.CheckTable(tableName, out columns))
                {
                    ModifyTableSchema(schema, dbprovider, tableName, columns);
                }
                else
                {
                    CreateTableSchema(schema, dbprovider, tableName);
                }
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("CheckTableSchema {0} error:{1}", tableName, ex);
            }
        }
Exemple #18
0
 public DBProvider(string connKey)
 {
     if (!m_DBs.ContainsKey(connKey))
     {
         m_DBs[connKey] = DbConnectionProvider.CreateDbProvider(connKey);
     }
     m_DB = m_DBs[connKey];
 }
Exemple #19
0
        /// <summary>
        /// 检测数据表结构变动
        /// </summary>
        /// <param name="schema"></param>
        private static IList <Tuple <DbBaseProvider, SchemaTable> > CheckTableSchema(SchemaTable schema)
        {
            string tableName = schema.GetTableName(DateTime.Now);

            try
            {
                if (DbConnectionProvider.Count == 0)
                {
                    //not seting connection.
                    return(null);
                }
                var            dbProviderPools = new List <DbBaseProvider>();
                var            watchList       = new List <Tuple <DbBaseProvider, SchemaTable> >();
                DbBaseProvider dbprovider      = DbConnectionProvider.CreateDbProvider(schema);
                if (dbprovider == null)
                {
                    if (schema.StorageType.HasFlag(StorageType.ReadOnlyDB) ||
                        schema.StorageType.HasFlag(StorageType.ReadWriteDB) ||
                        schema.StorageType.HasFlag(StorageType.WriteOnlyDB))
                    {
                        TraceLog.WriteError("Not found DB connection key \"{1}\" of the {0} entity.", schema.EntityName, schema.ConnectKey);
                    }
                    return(null);
                }
                dbProviderPools.Add(dbprovider);
                //增加从库节点配置
                if (schema.SlaveConnectKeys != null && schema.SlaveConnectKeys.Length > 0)
                {
                    foreach (var connectKey in schema.SlaveConnectKeys)
                    {
                        DbBaseProvider provider = DbConnectionProvider.CreateDbProvider(connectKey);
                        if (provider != null)
                        {
                            dbProviderPools.Add(provider);
                        }
                    }
                }
                foreach (var provider in dbProviderPools)
                {
                    watchList.Add(Tuple.Create(provider, schema));
                    DbColumn[] columns;
                    if (provider.CheckTable(tableName, out columns))
                    {
                        ModifyTableSchema(schema, provider, tableName, columns);
                    }
                    else
                    {
                        CreateTableSchema(schema, provider, tableName);
                    }
                }
                return(watchList);
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("CheckTableSchema {0} error:{1}", tableName, ex);
                return(null);
            }
        }
Exemple #20
0
        /// <summary>
        /// 尝试接收数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="receiveParam"></param>
        /// <param name="dataList"></param>
        /// <returns>return null is load error</returns>
        public bool TryReceiveData <T>(TransReceiveParam receiveParam, out List <T> dataList) where T : AbstractEntity, new()
        {
            dataList = null;
            bool hasDbConnect = DbConnectionProvider.CreateDbProvider(receiveParam.Schema) != null;
            var  schema       = receiveParam.Schema;

            //表为空时,不加载数据
            if (schema == null ||
                string.IsNullOrEmpty(schema.EntityName))
            {
                //DB is optional and can no DB configuration
                dataList = new List <T>();
                return(true);
            }

            //配置库不放到Redis,尝试从DB加载
            if (schema.StorageType.HasFlag(StorageType.ReadOnlyDB) ||
                schema.StorageType.HasFlag(StorageType.ReadWriteDB))
            {
                if (!hasDbConnect)
                {
                    dataList = new List <T>();
                    return(true);
                }
                var result = _dbTransponder.TryReceiveData(receiveParam, out dataList);
                TraceLog.ReleaseWriteDebug("The readonly-data:{0} has been loaded {1}", receiveParam.RedisKey, dataList.Count);
                return(result);
            }

            if (schema.StorageType.HasFlag(StorageType.ReadOnlyRedis) ||
                schema.StorageType.HasFlag(StorageType.ReadWriteRedis))
            {
                if (!string.IsNullOrEmpty(receiveParam.RedisKey) &&
                    _redisTransponder.TryReceiveData(receiveParam, out dataList))
                {
                    if (dataList.Count > 0)
                    {
                        TraceLog.ReleaseWriteDebug("The data:{0} has been loaded {1}", receiveParam.RedisKey, dataList.Count);
                        return(true);
                    }
                    //从Redis历史记录表中加载
                    if (hasDbConnect && Setting != null && Setting.IsStorageToDb)
                    {
                        var result = TryLoadHistory(receiveParam.RedisKey, out dataList);
                        TraceLog.ReleaseWriteDebug("The data:{0} has been loaded {1} from history.", receiveParam.RedisKey, dataList.Count);
                        return(result);
                    }
                    dataList = new List <T>();
                    return(true);
                }
                //read faild from redis.
                return(false);
            }
            return(true);
        }
Exemple #21
0
        public static void Init()
        {
            string connectionString = string.Format("Data Source={0};Database={1};Uid={2};Pwd={3};Pooling=true;",
                                                    AppSetting.Current.Contract.Server,
                                                    AppSetting.Current.Contract.Database,
                                                    AppSetting.Current.Contract.UserId,
                                                    AppSetting.Current.Contract.Password);

            dbProvider   = DbConnectionProvider.CreateDbProvider("ContractData", "", connectionString);
            saveTempPath = Path.Combine(MathUtils.RuntimePath, AppSetting.Current.Contract.CaseOutPath);
        }
Exemple #22
0
        private bool DoWriteToDb(RedisClient redisClient, byte[] buffer)
        {
            SqlStatement statement = null;

            try
            {
                statement = ProtoBufUtils.Deserialize <SqlStatement>(buffer);
                if (statement != null)
                {
                    var dbProvider = DbConnectionProvider.CreateDbProvider("", statement.ProviderType, statement.ConnectionString);
                    if (dbProvider != null)
                    {
                        var paramList = ConvertParam(dbProvider, statement.Params);
                        dbProvider.ExecuteQuery(statement.CommandType, statement.CommandText, paramList);
                        redisClient.ZRem(_setId, buffer);
                        return(true);
                    }
                }
                _errorCount++;
                return(false);
            }
            catch (Exception ex)
            {
                _errorCount++;
                try
                {
                    if (removeCheckBox.Checked)
                    {
                        redisClient.ZRem(_setId, buffer);
                    }
                }
                catch
                {
                }
                if (statement != null)
                {
                    try
                    {
                        msgListBox.Items.Add(string.Format("pos:{0}, error:{1}", _currentIndex, ex.Message));
                        TraceLog.WriteError("WriteToDb:{0}\r\n{1}\r\nParam:{2}",
                                            ex.Message,
                                            statement.CommandText,
                                            GetParamToString(statement.Params));
                    }
                    catch
                    {
                    }
                }
                return(false);
            }
        }
Exemple #23
0
        /// <summary>
        /// 从数据库恢复
        /// </summary>
        /// <param name="chart">条件</param>
        /// <param name="value">值</param>
        public static void RecoverFromDb(string chart, int value = -2)
        {
            var cacheSet = new GameDataCacheSet <tb_User>();

            if (cacheSet.Count == 0)
            {
                SchemaTable    schema   = EntitySchemaSet.Get <tb_User>();
                DbBaseProvider provider = DbConnectionProvider.CreateDbProvider(schema);
                DbDataFilter   filter   = new DbDataFilter(0);
                filter.Condition = provider.FormatFilterParam("isRobot", chart);
                filter.Parameters.Add("isRobot", value);
                cacheSet.TryRecoverFromDb(filter);//从数据库中恢复数据
            }
        }
Exemple #24
0
        public bool AddToCache(ServerInfo serverInfo)
        {
            string key = GenerateKey(serverInfo.GameID, serverInfo.ID);

            try
            {
                //判断是否重名
                ServerInfo tempServer = Find(p => p.GameID == serverInfo.GameID && Equals(p.ServerName, serverInfo.ServerName));
                if (tempServer == null)
                {
                    tempServer                 = new ServerInfo();
                    tempServer.ID              = serverInfo.ID;
                    tempServer.GameID          = serverInfo.GameID;
                    tempServer.TargetServer    = serverInfo.TargetServer;
                    tempServer.ServerName      = serverInfo.ServerName;
                    tempServer.ServerUrl       = serverInfo.ServerUrl;
                    tempServer.ActiveNum       = serverInfo.ActiveNum;
                    tempServer.Status          = serverInfo.Status;
                    tempServer.EnableDate      = serverInfo.EnableDate;
                    tempServer.IntranetAddress = serverInfo.IntranetAddress;

                    var dbProvider = DbConnectionProvider.CreateDbProvider("DirData");
                    var command    = dbProvider.CreateCommandStruct("ServerInfo", CommandMode.Insert);

                    command.AddParameter("ID", serverInfo.ID);
                    command.AddParameter("GameID", serverInfo.GameID);
                    command.AddParameter("TargetServer", serverInfo.TargetServer);
                    command.AddParameter("ServerName", serverInfo.ServerName);
                    command.AddParameter("BaseUrl", serverInfo.ServerUrl);
                    command.AddParameter("ActiveNum", serverInfo.ActiveNum);
                    command.AddParameter("EnableDate", serverInfo.EnableDate);
                    command.AddParameter("IntranetAddress", serverInfo.IntranetAddress);
                    command.Parser();
                    dbProvider.ExecuteQuery(CommandType.Text, command.Sql, command.Parameters);
                    AddOrUpdate(key, tempServer);
                }
                else
                {
                    tempServer.TargetServer = serverInfo.TargetServer;
                    tempServer.ActiveNum    = serverInfo.ActiveNum;
                    tempServer.Status       = serverInfo.Status;
                }
                return(true);
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("AddToCache {0}_{1} error:{2}", ContainerKey, key, ex);
                return(false);
            }
        }
Exemple #25
0
        public bool TryMoveKeyToDb(ConnectionString setting, IEnumerable <string> keys, out int success)
        {
            success = 0;
            return(false);

            //结构调用, 不使用;
            int num = 0;

            if (!setting.HasConfig())
            {
                throw new ArgumentNullException("database connectionstring is empty.");
            }
            var proveder = DbConnectionProvider.CreateDbProvider(setting.Name, setting.ProviderName.ToString(), setting.FormatString());

            bool b = TryExecute(client =>
            {
                bool isError = false;
                foreach (var key in keys)
                {
                    byte[] buffer = ProtoBufUtils.Serialize(client.HGetAll(key));
                    //var buffer = client.Get<byte[]>(key);
                    if (buffer != null)
                    {
                        var command = proveder.CreateCommandStruct(HistoryTable, CommandMode.ModifyInsert);
                        command.AddParameter("Key", key);
                        command.AddParameter("Value", buffer);
                        command.Filter           = proveder.CreateCommandFilter();
                        command.Filter.Condition = proveder.FormatFilterParam("Key");
                        command.Filter.AddParam("F_Key", key);
                        command.Parser();
                        if (proveder.ExecuteQuery(CommandType.Text, command.Sql, command.Parameters) > 0)
                        {
                            num++;
                        }
                        else
                        {
                            isError = true;
                        }
                    }
                }
                if (!isError)
                {
                    client.RemoveAll(keys);
                }
                return(!isError);
            });

            success = num;
            return(b);
        }
Exemple #26
0
 private void OnSyncSql(object state)
 {
     try
     {
         if (Monitor.TryEnter(syncSqlObject, 1000))
         {
             try
             {
                 TraceLog.ReleaseWrite("Sql waiting to be written to the Redis");
                 while (true)
                 {
                     var list = CacheChangeManager.Current.PopSql(100);
                     if (list.Count == 0)
                     {
                         break;
                     }
                     foreach (var key in list)
                     {
                         string redisKey = key;
                         try
                         {
                             dynamic     entity      = CacheFactory.GetEntityFromRedis(redisKey, true);
                             SchemaTable schemaTable = entity.GetSchema();
                             if (entity != null && schemaTable != null)
                             {
                                 DbBaseProvider dbProvider = DbConnectionProvider.CreateDbProvider(schemaTable);
                                 if (dbProvider != null)
                                 {
                                     DataSyncManager.GetDataSender().Send(entity, false);
                                 }
                             }
                         }
                         catch (Exception e)
                         {
                             TraceLog.WriteError("Sync to db {0} error:{1}", redisKey, e);
                         }
                     }
                 }
             }
             finally
             {
                 Monitor.Exit(syncSqlObject);
             }
         }
     }
     catch (Exception ex)
     {
         TraceLog.WriteError("Sql sync error:{0}", ex);
     }
 }
Exemple #27
0
        /// <summary>
        /// OrderInfoCache
        /// </summary>
        public static void DoOrderInfoCache()
        {
            var orderInfoSet = new ShareCacheStruct <OrderInfoCache>();

            TraceLog.WriteInfo("Do OrderInfoCache table start...");
            int count = 0;

            try
            {
                var    dbProvider = DbConnectionProvider.CreateDbProvider(DbConfig.MERGE);
                string sql        = "SELECT OrderId,UserId,NickName,MerchandiseName,PayId,Amount,PassportID,PassportID," +
                                    "GameCoins,CreateDate,RetailID,RcId FROM OrderInfoCache";
                using (IDataReader reader = dbProvider.ExecuteReader(CommandType.Text, sql))
                {
                    while (reader.Read())
                    {
                        OrderInfoCache newOrderInfo = new OrderInfoCache()
                        {
                            OrderId         = reader["OrderId"].ToString(),
                            UserId          = reader["UserId"].ToInt(),
                            NickName        = reader["NickName"].ToString(),
                            MerchandiseName = reader["MerchandiseName"].ToString(),
                            PayId           = reader["PayId"].ToInt(),
                            Amount          = reader["Amount"].ToInt(),
                            PassportID      = reader["PassportID"].ToString(),
                            ServerID        = reader["ServerID"].ToInt(),
                            GameCoins       = reader["GameCoins"].ToInt(),
                            CreateDate      = reader["CreateDate"].ToDateTime(),
                            RetailID        = reader["RetailID"].ToString(),
                            RcId            = reader["RcId"].ToInt(),
                        };
                        if (orderInfoSet.FindKey(newOrderInfo.OrderId) == null)
                        {
                            //orderInfoSet.Add(newOrderInfo);
                            count++;
                        }
                    }
                    //orderInfoSet.Update();
                }
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("Do OrderInfoCache table error Exception: {0} .", ex);
                return;
            }


            TraceLog.WriteInfo("Do OrderInfoCache table successful : {0} .", count);
        }
Exemple #28
0
        private static void WriteSqlLog(ProfileSummary summary, string dbProviderName, string connectionString)
        {
            var dbProvider = DbConnectionProvider.CreateDbProvider(ConnectKey, dbProviderName, connectionString);
            var command    = dbProvider.CreateCommandStruct(MessageQueueTableName, CommandMode.Insert);

            foreach (var pair in GetDetailValues(summary))
            {
                if (pair.Key.ToLower() == MessageQueueColumns[0].ToLower())
                {
                    //ignore "id"
                    continue;
                }
                command.AddParameter(pair.Key, pair.Value);
            }
            dbProvider.ExecuteQuery(command);
        }
Exemple #29
0
        /// <summary>
        /// Generate sql statement
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <returns></returns>
        internal SqlStatement GenerateSqlQueue <T>(T data) where T : AbstractEntity
        {
            SchemaTable    schemaTable = data.GetSchema();
            DbBaseProvider dbProvider  = DbConnectionProvider.CreateDbProvider(schemaTable.ConnectKey);

            if (dbProvider != null)
            {
                CommandStruct command = GenerateCommand(dbProvider, data, schemaTable, false, null);
                if (command != null)
                {
                    int identityId = data.GetIdentityId();
                    return(dbProvider.GenerateSql(identityId, command));
                }
            }
            return(null);
        }
        /// <summary>
        /// 初始化机哭人队列,MySQLDAL.Model.tb_User 数据
        /// </summary>
        public static void InitiRobotList()
        {
            _robotUserList = new List <tb_User>();

            var cacheSet = new GameDataCacheSet <tb_User>();

            cacheSet.ReLoad();
            if (cacheSet.Count == 0)
            {
                SchemaTable    schema   = EntitySchemaSet.Get <tb_User>();
                DbBaseProvider provider = DbConnectionProvider.CreateDbProvider(schema);
                DbDataFilter   filter   = new DbDataFilter(0);
                filter.Condition = provider.FormatFilterParam("isRobot", "=");
                filter.Parameters.Add("isRobot", 1);

                cacheSet.TryRecoverFromDb(filter);//从数据库中恢复数据
            }
            var            robotIdList = tb_UserEx.GetUserIdListByRobot(1);
            List <tb_User> _userList   = new List <tb_User>(); // List<tb_User> _userList = cacheSet.FindAll();

            if (robotIdList.Any())
            {
                robotIdList.ForEach(t =>
                {
                    tb_User user;
                    cacheSet.TryFindKey(t.ToString(), out user);
                    if (user != null)
                    {
                        _userList.Add(user);
                    }
                });
            }

            //// List<tb_User> _userList = cacheSet.FindAll();
            if (_userList == null || _userList.Count == 0)
            {
                ErrorRecord.Record(" tb_user 中没有机器人,201610231608");
                return;
            }
            //SetWebChartName();
            // var setName = SetWebChartName(_userList);
            // var temp = SetRobotWebChartImg(_userList);
            // ModifyFileName();
            // cacheSet.AddOrUpdate(setName);
            //cacheSet.Update();
            _robotUserList.AddRange(_userList);
        }