Esempio n. 1
0
 private static void SetBaseKey(string baseKey, string key)
 {
     //baseKey是表的,不包括视图和自定义语句
     if (_MemCache.CacheType == CacheType.LocalCache)
     {
         if (cacheKeys.ContainsKey(baseKey))
         {
             cacheKeys[baseKey] = cacheKeys[baseKey].Append("," + key);
         }
         else
         {
             cacheKeys.Add(baseKey, new StringBuilder(key));
         }
     }
     else
     {
         StringBuilder sb = _MemCache.Get <StringBuilder>(baseKey);
         if (sb == null)
         {
             _MemCache.Set(baseKey, new StringBuilder(key));
         }
         else
         {
             sb.Append("," + key);
             _MemCache.Set(baseKey, sb);
         }
     }
 }
Esempio n. 2
0
 public void Set(string objName, string tableName)
 {
     if (string.IsNullOrEmpty(objName))
     {
         return;
     }
     if (midTableNameList.ContainsKey(MenuID))
     {
         string value = midTableNameList[MenuID];
         if (value.IndexOf(objName) == -1)
         {
             value += "," + objName;
         }
         if (!string.IsNullOrEmpty(tableName) && value.IndexOf(tableName) == -1)
         {
             value += "," + tableName;
         }
         midTableNameList[MenuID] = value;
     }
     else
     {
         string value = objName;
         if (!string.IsNullOrEmpty(tableName) && tableName != objName)
         {
             value += "," + tableName;
         }
         midTableNameList.Add(MenuID, value);
     }
 }
Esempio n. 3
0
        internal static ConnObject GetConnObject(string dbConn)
        {
            dbConn = string.IsNullOrEmpty(dbConn) ? AppConfig.DB.DefaultConn : dbConn;
            if (dbConn.EndsWith("_Bak"))
            {
                dbConn = dbConn.Replace("_Bak", "");
            }
            if (connDicCache.ContainsKey(dbConn))
            {
                return(connDicCache[dbConn]);
            }
            ConnBean cbMaster = GetConnBean(dbConn);

            if (cbMaster == null)
            {
                string errMsg = string.Format("Can't find the connection key '{0}' from web.config or app.config!", dbConn);
                if (dbConn == AppConfig.DB.DefaultConn)
                {
                    Error.Throw(errMsg);
                }
                else
                {
                    ConnBean cb = GetConnBean(AppConfig.DB.DefaultConn);
                    if (cb != null)
                    {
                        cbMaster = cb.Clone();//获取默认的值。
                    }
                    else
                    {
                        Error.Throw(errMsg);
                    }
                }
            }
            ConnObject co = new ConnObject();

            co.Master = cbMaster;
            if (dbConn != null && dbConn.Length < 32 && !dbConn.Trim().Contains(" ")) // 为configKey
            {
                ConnBean coBak = GetConnBean(dbConn + "_Bak");
                if (coBak != null && coBak.ProviderName == cbMaster.ProviderName)
                {
                    co.BackUp = coBak;
                }
                for (int i = 1; i < 1000; i++)
                {
                    ConnBean cbSlave = GetConnBean(dbConn + "_Slave" + i);
                    if (cbSlave == null)
                    {
                        break;
                    }
                    cbSlave.IsSlave = true;
                    co.Slave.Add(cbSlave);
                }
            }
            if (!connDicCache.ContainsKey(dbConn) && co.Master.ConfigName == dbConn) // 非一致的,由外面切换后再缓存
            {
                connDicCache.Set(dbConn, co);
            }
            return(co);
        }
Esempio n. 4
0
 public static DalBase Get(string key)
 {
     if (dalBaseDic.ContainsKey(key))
     {
         return(dalBaseDic[key]);
     }
     return(null);
 }
Esempio n. 5
0
 /// <summary>
 /// 是否存在缓存
 /// </summary>
 /// <param name="key">标识</param>
 /// <returns></returns>
 public override bool Contains(string key)
 {
     if (string.IsNullOrEmpty(key))
     {
         return(false);
     }
     return(theCache.ContainsKey(key) && theKeyTime.ContainsKey(key) && theKeyTime[key] > DateTime.Now);
 }
Esempio n. 6
0
        /// <summary>
        /// 获取Web.config或App.config的connectionStrings节点的值。
        /// </summary>
        public static string GetConn(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                name = DB.DefaultConn;
            }
            if (name.Trim().Contains(" "))
            {
                return(name);
            }
            if (connConfigs.ContainsKey(name))
            {
                return(connConfigs[name]);
            }
            ConnectionStringSettings conn = ConfigurationManager.ConnectionStrings[name];

            if (conn != null)
            {
                string connString = conn.ConnectionString;
                if (name == connString || string.IsNullOrEmpty(connString))//避免误写自己造成死循环。
                {
                    return(name);
                }


                if (connString.EndsWith(".txt") || connString.EndsWith(".ini") || connString.EndsWith(".json"))
                {
                    return(ConnConfigWatch.Start(name, connString));
                }
                //允许配置文件里加密。
                if (connString.Length > 32 && connString.Split(';', '=', ' ').Length == 1)
                {
                    connString = EncryptHelper.Decrypt(connString);
                }
                //启动高可用配置加载方式
                if (connString.Length < 32 && connString.Split(' ').Length == 1)
                {
                    return(GetConn(connString));
                }
                if (!connConfigs.ContainsKey(name))
                {
                    connConfigs.Add(name, connString);
                }
                return(connString);
            }
            if (name.Length > 32 && name.Split('=').Length > 3 && name.Contains(";")) //链接字符串很长,没空格的情况 txt path={0}
            {
                return(name);
            }
            if (name == "Conn" && name != DB.DefaultConn)
            {
                return(GetConn(DB.DefaultConn));
            }
            return("");
        }
        public override int Add(object value)
        {
            NoSqlParameter p = value as NoSqlParameter;

            if (p != null && !dic.ContainsKey(p.ParameterName))
            {
                dic.Add(p.ParameterName, p);
                return(1);
            }
            return(0);
        }
Esempio n. 8
0
        /// <summary>
        /// 获取列所在的索引位置(若不存在返回-1)
        /// </summary>
        public int GetIndex(string columnName)
        {
            columnName = columnName.Trim();
            if (columnIndex.Count == 0 || IsColumnNameChanged || columnIndex.Count != Count)
            {
                columnIndex.Clear();
                for (int i = 0; i < Count; i++)
                {
                    columnIndex.Add(this[i].ColumnName.Replace("_", ""), i);
                }
                IsColumnNameChanged = false;
            }

            if (!string.IsNullOrEmpty(columnName))
            {
                if (columnName.IndexOf('_') > -1)
                {
                    columnName = columnName.Replace("_", "");//兼容映射处理
                }
                if (columnIndex.ContainsKey(columnName))
                {
                    return(columnIndex[columnName]);
                }
                else
                {
                    //开启默认前缀检测
                    string[] items = AppConfig.UI.AutoPrefixs.Split(',');
                    if (items != null && items.Length > 0)
                    {
                        foreach (string item in items)
                        {
                            columnName = columnName.StartsWith(item) ? columnName.Substring(3) : item + columnName;
                            if (columnIndex.ContainsKey(columnName))
                            {
                                return(columnIndex[columnName]);
                            }
                        }
                    }
                }
                //for (int i = 0; i < Count; i++)
                //{
                //    if (string.Compare(this[i].ColumnName.Replace("_", ""), columnName, StringComparison.OrdinalIgnoreCase) == 0)//第三个参数用StringComparison.OrdinalIgnoreCase比用true快。
                //    {
                //        return i;
                //    }
                //}
            }
            return(-1);
        }
Esempio n. 9
0
        /// <summary>
        /// 获取列所在的索引位置(若不存在返回-1)
        /// </summary>
        public int GetIndex(string columnName)
        {
            if (columnIndex.Count == 0 || IsColumnNameChanged || columnIndex.Count != Count)
            {
                columnIndex.Clear();
                for (int i = 0; i < Count; i++)
                {
                    columnIndex.Add(this[i].ColumnName.Replace("_", ""), i);
                }
                IsColumnNameChanged = false;
            }

            if (!string.IsNullOrEmpty(columnName))
            {
                if (columnName.IndexOf('_') > -1)
                {
                    columnName = columnName.Replace("_", "");//兼容映射处理
                }
                if (columnIndex.ContainsKey(columnName))
                {
                    return(columnIndex[columnName]);
                }
                //for (int i = 0; i < Count; i++)
                //{
                //    if (string.Compare(this[i].ColumnName.Replace("_", ""), columnName, StringComparison.OrdinalIgnoreCase) == 0)//第三个参数用StringComparison.OrdinalIgnoreCase比用true快。
                //    {
                //        return i;
                //    }
                //}
            }
            return(-1);
        }
Esempio n. 10
0
 /// <summary>
 /// 设置Web.config或App.config的值。
 /// </summary>
 public static void SetApp(string key, string value)
 {
     try
     {
         if (appConfigs.ContainsKey(key))
         {
             appConfigs[key] = value;
         }
         else
         {
             appConfigs.Add(key, value);
         }
     }
     catch (Exception err)
     {
         CYQ.Data.Log.WriteLogToTxt(err);
     }
 }
Esempio n. 11
0
        /// <summary>
        /// 获取Shared文件View
        /// </summary>
        /// <param name="htmlName"></param>
        /// <returns></returns>
        private static XHtmlAction GetSharedView(string htmlName, string htmlPath)
        {
            string path = AppConfig.WebRootPath + AppConfig.GetApp("Views", "Views") + "/Shared/" + htmlName + ".html";

            if (!File.Exists(path))
            {
                path = null;
                string[] files = Directory.GetFiles(Path.GetDirectoryName(htmlPath), htmlName + ".html", SearchOption.AllDirectories);
                if (files != null && files.Length > 0)
                {
                    path = files[0];
                }
                else
                {
                    files = Directory.GetFiles(AppConfig.WebRootPath + AppConfig.GetApp("Views", "Views"), htmlName + ".html", SearchOption.AllDirectories);
                    if (files != null && files.Length > 0)
                    {
                        path = files[0];
                    }
                }
                if (path == null)
                {
                    return(null);
                }
            }
            XHtmlAction sharedView = null;
            string      key        = EncryptHelper.GetHashKey(path);

            if (sharedViews.ContainsKey(key))
            {
                sharedView = sharedViews[key];
                if (sharedView.IsXHtmlChanged)
                {
                    sharedViews.Remove(key);
                    sharedView = null;
                }
                else
                {
                    return(sharedView);
                }
            }

            sharedView = new XHtmlAction(true, true);
            if (sharedView.Load(path, XmlCacheLevel.Day, true))
            {
                lock (lockObj)
                {
                    if (!sharedView.Contains(key))
                    {
                        sharedViews.Add(key, sharedView);
                    }
                }
                return(sharedView);
            }

            return(null);
        }
Esempio n. 12
0
 /// <summary>
 /// 获得一个Cache对象
 /// </summary>
 /// <param name="key">标识</param>
 public override object Get(string key)
 {
     if (theState.ContainsKey(key))
     {
         lock (lockObj)
         {
             try
             {
                 theState[key].callCount++;
             }
             catch
             {
                 //errorCount++;
             }
         }
         return(theCache[key]);
     }
     return(null);
 }
Esempio n. 13
0
        public static bool BeginTransation(string conn, IsolationLevel level)
        {
            string key = StaticTool.GetTransationKey(conn);

            if (!TransationKeys.ContainsKey(key))
            {
                TransationKeys.Add(key, level);
                return(true);
            }
            return(false);
        }
Esempio n. 14
0
        /// <summary>
        /// 获取Web.config或App.config的connectionStrings节点的值。
        /// </summary>
        public static string GetConn(string name, out string providerName)
        {
            providerName = string.Empty;
            if (string.IsNullOrEmpty(name))
            {
                name = "Conn";
            }
            if (name.Trim().Contains(" "))
            {
                return(name);
            }
            if (connConfigs.ContainsKey(name))
            {
                return(connConfigs[name]);
            }
            ConnectionStringSettings conn = ConfigurationManager.ConnectionStrings[name];

            if (conn != null)
            {
                providerName = conn.ProviderName;
                if (name == conn.ConnectionString)//避免误写自己造成死循环。
                {
                    return(name);
                }
                name = conn.ConnectionString;
                if (!string.IsNullOrEmpty(name) && name.Length < 32 && name.Split(' ').Length == 1)
                {
                    return(GetConn(name));
                }
                if (!connConfigs.ContainsKey(name) && string.IsNullOrEmpty(providerName)) // 如果有providerName,则不存档
                {
                    connConfigs.Add(name, conn.ConnectionString);
                }
                return(conn.ConnectionString);
            }
            if (name.Length > 32 && name.Split('=').Length > 3 && name.Contains(";")) //链接字符串很长,没空格的情况
            {
                return(name);
            }
            return("");
        }
Esempio n. 15
0
        /// <summary>
        /// 设置Web.config或App.config的值 value为null时移除缓存。
        /// </summary>
        public static bool SetApp(string key, string value)
        {
            if (string.IsNullOrEmpty(key))
            {
                return(false);
            }
            if (value == null)
            {
                return(appConfigs.Remove(key));
            }
            if (appConfigs.ContainsKey(key))
            {
                appConfigs[key] = value;
            }
            else
            {
                appConfigs.Add(key, value);
            }

            return(true);
        }
Esempio n. 16
0
    public static Message TryParseToObject(MDictionary <MString, Message> obj)
    {
        if (obj.ContainsKey("Type"))
        {
            Guid guid = new Guid(((MString)obj["Type"]).Value);
            if (_types.ContainsKey(guid))
            {
                Message mobj = (Message)Activator.CreateInstance(_types[guid]);
                mobj.FromDictionary(obj);

                return(mobj);
            }
        }

        return(obj);
    }
Esempio n. 17
0
 private bool IsExistsDbNameWithCache(string dbName)
 {
     try
     {
         string key = DataBaseType.ToString() + "." + dbName;
         if (dbList.ContainsKey(key))
         {
             return(dbList[key]);
         }
         bool result = IsExistsDbName(dbName);
         dbList.Add(key, result);
         return(result);
     }
     catch
     {
         return(true);
     }
 }
Esempio n. 18
0
 private bool IsExistsDbNameWithCache(string dbName)
 {
     try
     {
         string key = dalType.ToString() + "." + dbName;
         if (dbList.ContainsKey(key))
         {
             return dbList[key];
         }
         bool result = IsExistsDbName(dbName);
         dbList.Add(key, result);
         return result;
     }
     catch
     {
         return true;
     }
 }
Esempio n. 19
0
        /// <summary>
        /// 开启加载一个配置。
        /// </summary>
        /// <param name="connName">Conn的名称</param>
        /// <param name="connPath">Conn指向的路径</param>
        /// <returns></returns>
        public static string Start(string connName, string connPath)
        {
            lock (o)
            {
                string path = AppConfig.RunPath + connPath;
                string json = JsonHelper.ReadJson(path);
                if (string.IsNullOrEmpty(json))
                {
                    return(connName);
                }
                WatchConfig config = JsonHelper.ToEntity <WatchConfig>(JsonHelper.GetValue(json, connName));
                if (config != null && !string.IsNullOrEmpty(config.Master))
                {
                    AppConfig.SetConn(connName, config.Master);
                    if (!string.IsNullOrEmpty(config.Backup))
                    {
                        AppConfig.SetConn(connName + "_Bak", config.Backup);
                    }
                    if (config.Slave != null && config.Slave.Length > 0)
                    {
                        for (int i = 0; i < config.Slave.Length; i++)
                        {
                            AppConfig.SetConn(connName + "_Slave" + (i + 1), config.Slave[i]);
                        }
                    }
                    if (!watchList.ContainsValue(connPath))
                    {
                        IOWatch.On(path, delegate(FileSystemEventArgs e)
                        {
                            fsy_Changed(e);
                        });
                    }
                    if (!watchList.ContainsKey(connName))
                    {
                        watchList.Add(connName, connPath);
                    }

                    return(config.Master);
                }
            }
            return(connName);
        }
Esempio n. 20
0
        public static void Add(SysLogs log)
        {
            long hash = log.Message.GetHashCode() + log.LogType.GetHashCode();

            if (hashObj.ContainsKey(hash))
            {
                if (hashObj[hash].AddMinutes(3) < DateTime.Now)
                {
                    hashObj.Remove(hash); //超过1分钟的,不再存档。
                }
                log = null;               //直接丢掉。
                return;
            }
            hashObj.Add(hash, DateTime.Now);
            _LogQueue.Enqueue(log);
            if (!threadIsWorking)
            {
                threadIsWorking = true;
                ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork), null);
            }
        }
Esempio n. 21
0
 private bool CreateHost()
 {
     if (hostList.Count == 0)
     {
         AddHost(watch.HostList);
     }
     else //处理变化的情况
     {
         //移除主机。
         foreach (string host in watch.HostRemoveList.List)
         {
             if (hostList.ContainsKey(host))
             {
                 hostList[host].Dispose(); //释放资源。
                 hostList.Remove(host);    //移除主机
             }
         }
         //添加主机
         AddHost(watch.HostAddList);
     }
     return(hostList.Count > 0);
 }
Esempio n. 22
0
 /// <summary>
 /// 检测文件是否已被修改过
 /// </summary>
 /// <param name="isNeedToReloadTable"></param>
 private void CheckFileChanged(bool isNeedToReloadTable)
 {
     if (!_isDeleteAll.Contains(_FileFullName))
     {
         DateTime lastWriteTime = _lastWriteTimeList[_FileFullName];
         if (IOHelper.IsLastFileWriteTimeChanged(_FileFullName, ref lastWriteTime))
         {
             _lastWriteTimeList[_FileFullName] = lastWriteTime;
             if (isNeedToReloadTable && _tableList.ContainsKey(_FileFullName))
             {
                 try
                 {
                     _tableList[_FileFullName].Rows.Clear();
                     _tableList.Remove(_FileFullName);
                 }
                 catch// (Exception err)
                 {
                 }
                 _Table = null;//需要重新加载数据。
             }
         }
     }
 }
Esempio n. 23
0
        /// <param name="fileName">文件依赖路径</param>
        public override void Set(string key, object value, double cacheMinutes, string fileName)
        {
            try
            {
                lock (lockObj)
                {
                    if (!theKey.Contains(key))
                    {
                        theKey.Add(key);//1:设置 key
                    }

                    if (theCache.ContainsKey(key))
                    {
                        theCache[key] = value;
                    }
                    else
                    {
                        theCache.Add(key, value);//2:设置value
                    }
                    double cacheTime = cacheMinutes;
                    if (cacheMinutes <= 0)
                    {
                        cacheTime = AppConfig.Cache.DefaultCacheTime;
                    }
                    DateTime cTime     = DateTime.Now.AddMinutes(cacheTime);
                    int      workCount = GetWorkCount(cTime);
                    if (theKeyTime.ContainsKey(key))
                    {
                        int wc = GetWorkCount(theKeyTime[key]);
                        if (wc != workCount && theTime.ContainsKey(wc))
                        {
                            if (theTime[wc].Contains(key))
                            {
                                theTime[wc].Remove(key); //移除旧值
                            }
                        }
                        theKeyTime[key] = cTime;
                    }
                    else
                    {
                        theKeyTime.Add(key, cTime);
                    }


                    if (theTime.ContainsKey(workCount))//3:设置time
                    {
                        if (!theTime[workCount].Contains(key))
                        {
                            theTime[workCount].Add(key);
                        }
                    }
                    else
                    {
                        List <string> list = new List <string>();
                        list.Add(key);
                        theTime.Add(workCount, list);
                    }

                    if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName))//3:设置file
                    {
                        if (!theFile.ContainsKey(key))
                        {
                            if (fileName.IndexOf("\\\\") > -1)
                            {
                                fileName = fileName.Replace("\\\\", "\\");
                            }
                            theFile.Add(key, CreateFileSystemWatcher(fileName));
                            if (theFileKeys.ContainsKey(fileName))
                            {
                                theFileKeys[fileName].Add(key);
                            }
                            else
                            {
                                List <string> list = new List <string>();
                                list.Add(key);
                                theFileKeys.Add(fileName, list);
                            }
                        }
                    }
                }
            }
            catch
            {
                errorCount++;
            }
        }
Esempio n. 24
0
        public static MDataColumn GetColumns(Type typeInfo)
        {
            string key = "ColumnCache_" + typeInfo.FullName;

            if (_ColumnCache.ContainsKey(key))
            {
                return(_ColumnCache[key].Clone());
            }
            else
            {
                #region 获取列结构
                MDataColumn mdc = new MDataColumn();
                mdc.TableName = typeInfo.Name;
                switch (StaticTool.GetSystemType(ref typeInfo))
                {
                case SysType.Base:
                case SysType.Enum:
                    mdc.Add(typeInfo.Name, DataType.GetSqlType(typeInfo), false);
                    return(mdc);

                case SysType.Generic:
                case SysType.Collection:
                    Type[] argTypes;
                    Tool.StaticTool.GetArgumentLength(ref typeInfo, out argTypes);
                    foreach (Type type in argTypes)
                    {
                        mdc.Add(type.Name, DataType.GetSqlType(type), false);
                    }
                    argTypes = null;
                    return(mdc);
                }

                List <PropertyInfo> pis = StaticTool.GetPropertyInfo(typeInfo);
                if (pis.Count > 0)
                {
                    for (int i = 0; i < pis.Count; i++)
                    {
                        SetStruct(mdc, pis[i], null, i, pis.Count);
                    }
                }
                else
                {
                    List <FieldInfo> fis = StaticTool.GetFieldInfo(typeInfo);
                    if (fis.Count > 0)
                    {
                        for (int i = 0; i < fis.Count; i++)
                        {
                            SetStruct(mdc, null, fis[i], i, fis.Count);
                        }
                    }
                }
                object[] tableAttr = typeInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);//看是否设置了表特性,获取表名和表描述
                if (tableAttr != null && tableAttr.Length == 1)
                {
                    DescriptionAttribute attr = tableAttr[0] as DescriptionAttribute;
                    if (attr != null && !string.IsNullOrEmpty(attr.Description))
                    {
                        mdc.Description = attr.Description;
                    }
                }
                pis = null;
                #endregion

                if (!_ColumnCache.ContainsKey(key))
                {
                    _ColumnCache.Set(key, mdc.Clone());
                }

                return(mdc);
            }
        }
Esempio n. 25
0
        public static MDataColumn GetColumns(string tableName, string conn)
        {
            string key = GetSchemaKey(tableName, conn);

            #region 缓存检测
            if (_ColumnCache.ContainsKey(key))
            {
                return(_ColumnCache[key].Clone());
            }
            if (!string.IsNullOrEmpty(AppConfig.DB.SchemaMapPath))
            {
                string fullPath = AppConfig.RunPath + AppConfig.DB.SchemaMapPath + key + ".ts";
                if (System.IO.File.Exists(fullPath))
                {
                    MDataColumn columns = MDataColumn.CreateFrom(fullPath);
                    if (columns.Count > 0)
                    {
                        CacheManage.LocalInstance.Set(key, columns.Clone(), 1440);
                        return(columns);
                    }
                }
            }
            #endregion
            string fixName;
            conn      = CrossDB.GetConn(tableName, out fixName, conn ?? AppConfig.DB.DefaultConn);
            tableName = fixName;
            if (conn == null)
            {
                return(null);
            }
            MDataColumn mdcs = null;
            using (DalBase dbHelper = DalCreate.CreateDal(conn))
            {
                DataBaseType dalType = dbHelper.DataBaseType;


                if (dalType == DataBaseType.Txt || dalType == DataBaseType.Xml)
                {
                    #region 文本数据库处理。
                    if (!tableName.Contains(" "))                                // || tableName.IndexOfAny(Path.GetInvalidPathChars()) == -1
                    {
                        tableName = SqlFormat.NotKeyword(tableName);             //处理database..tableName;
                        tableName = Path.GetFileNameWithoutExtension(tableName); //视图表,带“.“的,会出问题
                        string fileName = dbHelper.Con.DataSource + tableName + (dalType == DataBaseType.Txt ? ".txt" : ".xml");
                        mdcs = MDataColumn.CreateFrom(fileName);
                        mdcs.DataBaseType = dalType;
                        mdcs.Conn         = conn;
                    }

                    #endregion
                }
                else
                {
                    #region 其它数据库
                    mdcs              = new MDataColumn();
                    mdcs.Conn         = conn;
                    mdcs.TableName    = tableName;
                    mdcs.DataBaseType = dalType;

                    tableName = SqlFormat.Keyword(tableName, dbHelper.DataBaseType);//加上关键字:引号
                    //如果table和helper不在同一个库
                    DalBase helper = dbHelper.ResetDalBase(tableName);

                    helper.IsRecordDebugInfo = false || AppDebug.IsContainSysSql;//内部系统,不记录SQL表结构语句。
                    try
                    {
                        bool isView = tableName.Contains(" ");//是否视图。
                        if (!isView)
                        {
                            isView = CrossDB.Exists(tableName, "V", conn);
                        }
                        if (!isView)
                        {
                            TableInfo info = CrossDB.GetTableInfoByName(mdcs.TableName, conn);
                            if (info != null)
                            {
                                mdcs.Description = info.Description;
                            }
                        }
                        MCellStruct mStruct = null;
                        SqlDbType   sqlType = SqlDbType.NVarChar;
                        if (isView)
                        {
                            string sqlText = SqlFormat.BuildSqlWithWhereOneEqualsTow(tableName);// string.Format("select * from {0} where 1=2", tableName);
                            mdcs = GetViewColumns(sqlText, ref helper);
                        }
                        else
                        {
                            mdcs.AddRelateionTableName(SqlFormat.NotKeyword(tableName));
                            switch (dalType)
                            {
                            case DataBaseType.MsSql:
                            case DataBaseType.Oracle:
                            case DataBaseType.MySql:
                            case DataBaseType.Sybase:
                            case DataBaseType.PostgreSQL:
                                #region Sql
                                string sql = string.Empty;
                                if (dalType == DataBaseType.MsSql)
                                {
                                    #region Mssql
                                    string dbName = null;
                                    if (!helper.Version.StartsWith("08"))
                                    {
                                        //先获取同义词,检测是否跨库
                                        string realTableName = Convert.ToString(helper.ExeScalar(string.Format(MSSQL_SynonymsName, SqlFormat.NotKeyword(tableName)), false));
                                        if (!string.IsNullOrEmpty(realTableName))
                                        {
                                            string[] items = realTableName.Split('.');
                                            tableName = realTableName;
                                            if (items.Length > 0)    //跨库了
                                            {
                                                dbName = realTableName.Split('.')[0];
                                            }
                                        }
                                    }

                                    sql = GetMSSQLColumns(helper.Version.StartsWith("08"), dbName ?? helper.DataBaseName);
                                    #endregion
                                }
                                else if (dalType == DataBaseType.MySql)
                                {
                                    sql = GetMySqlColumns(helper.DataBaseName);
                                }
                                else if (dalType == DataBaseType.Oracle)
                                {
                                    tableName = tableName.ToUpper();    //Oracle转大写。
                                    //先获取同义词,不检测是否跨库
                                    string realTableName = Convert.ToString(helper.ExeScalar(string.Format(Oracle_SynonymsName, SqlFormat.NotKeyword(tableName)), false));
                                    if (!string.IsNullOrEmpty(realTableName))
                                    {
                                        tableName = realTableName;
                                    }

                                    sql = GetOracleColumns();
                                }
                                else if (dalType == DataBaseType.Sybase)
                                {
                                    tableName = SqlFormat.NotKeyword(tableName);
                                    sql       = GetSybaseColumns();
                                }
                                else if (dalType == DataBaseType.PostgreSQL)
                                {
                                    sql = GetPostgreColumns();
                                }
                                helper.AddParameters("TableName", SqlFormat.NotKeyword(tableName), DbType.String, 150, ParameterDirection.Input);
                                DbDataReader sdr = helper.ExeDataReader(sql, false);
                                if (sdr != null)
                                {
                                    long   maxLength;
                                    bool   isAutoIncrement = false;
                                    short  scale           = 0;
                                    string sqlTypeName     = string.Empty;
                                    while (sdr.Read())
                                    {
                                        short.TryParse(Convert.ToString(sdr["Scale"]), out scale);
                                        if (!long.TryParse(Convert.ToString(sdr["MaxSize"]), out maxLength))    //mysql的长度可能大于int.MaxValue
                                        {
                                            maxLength = -1;
                                        }
                                        else if (maxLength > int.MaxValue)
                                        {
                                            maxLength = int.MaxValue;
                                        }
                                        sqlTypeName             = Convert.ToString(sdr["SqlType"]);
                                        sqlType                 = DataType.GetSqlType(sqlTypeName);
                                        isAutoIncrement         = Convert.ToBoolean(sdr["IsAutoIncrement"]);
                                        mStruct                 = new MCellStruct(mdcs.DataBaseType);
                                        mStruct.ColumnName      = Convert.ToString(sdr["ColumnName"]).Trim();
                                        mStruct.OldName         = mStruct.ColumnName;
                                        mStruct.SqlType         = sqlType;
                                        mStruct.IsAutoIncrement = isAutoIncrement;
                                        mStruct.IsCanNull       = Convert.ToBoolean(sdr["IsNullable"]);
                                        mStruct.MaxSize         = (int)maxLength;
                                        mStruct.Scale           = scale;
                                        mStruct.Description     = Convert.ToString(sdr["Description"]);
                                        mStruct.DefaultValue    = SqlFormat.FormatDefaultValue(dalType, sdr["DefaultValue"], 0, sqlType);
                                        mStruct.IsPrimaryKey    = Convert.ToString(sdr["IsPrimaryKey"]) == "1";
                                        switch (dalType)
                                        {
                                        case DataBaseType.MsSql:
                                        case DataBaseType.MySql:
                                        case DataBaseType.Oracle:
                                            mStruct.IsUniqueKey  = Convert.ToString(sdr["IsUniqueKey"]) == "1";
                                            mStruct.IsForeignKey = Convert.ToString(sdr["IsForeignKey"]) == "1";
                                            mStruct.FKTableName  = Convert.ToString(sdr["FKTableName"]);
                                            break;
                                        }

                                        mStruct.SqlTypeName = sqlTypeName;
                                        mStruct.TableName   = SqlFormat.NotKeyword(tableName);
                                        mdcs.Add(mStruct);
                                    }
                                    sdr.Close();
                                    if (dalType == DataBaseType.Oracle && mdcs.Count > 0)    //默认没有自增概念,只能根据情况判断。
                                    {
                                        MCellStruct firstColumn = mdcs[0];
                                        if (firstColumn.IsPrimaryKey && firstColumn.ColumnName.ToLower().Contains("id") && firstColumn.Scale == 0 && DataType.GetGroup(firstColumn.SqlType) == 1 && mdcs.JointPrimary.Count == 1)
                                        {
                                            firstColumn.IsAutoIncrement = true;
                                        }
                                    }
                                }
                                #endregion
                                break;

                            case DataBaseType.SQLite:
                                #region SQlite
                                if (helper.Con.State != ConnectionState.Open)
                                {
                                    helper.Con.Open();
                                }
                                DataTable sqliteDt = helper.Con.GetSchema("Columns", new string[] { null, null, SqlFormat.NotKeyword(tableName) });
                                if (!helper.IsOpenTrans)
                                {
                                    helper.Con.Close();
                                }
                                int    size;
                                short  sizeScale;
                                string dataTypeName = string.Empty;

                                foreach (DataRow row in sqliteDt.Rows)
                                {
                                    object len = row["NUMERIC_PRECISION"];
                                    if (len == null || len == DBNull.Value)
                                    {
                                        len = row["CHARACTER_MAXIMUM_LENGTH"];
                                    }
                                    short.TryParse(Convert.ToString(row["NUMERIC_SCALE"]), out sizeScale);
                                    if (!int.TryParse(Convert.ToString(len), out size))    //mysql的长度可能大于int.MaxValue
                                    {
                                        size = -1;
                                    }
                                    dataTypeName = Convert.ToString(row["DATA_TYPE"]);
                                    if (dataTypeName == "text" && size > 0)
                                    {
                                        sqlType = DataType.GetSqlType("varchar");
                                    }
                                    else
                                    {
                                        sqlType = DataType.GetSqlType(dataTypeName);
                                    }
                                    //COLUMN_NAME,DATA_TYPE,PRIMARY_KEY,IS_NULLABLE,CHARACTER_MAXIMUM_LENGTH AUTOINCREMENT

                                    mStruct              = new MCellStruct(row["COLUMN_NAME"].ToString(), sqlType, Convert.ToBoolean(row["AUTOINCREMENT"]), Convert.ToBoolean(row["IS_NULLABLE"]), size);
                                    mStruct.Scale        = sizeScale;
                                    mStruct.Description  = Convert.ToString(row["DESCRIPTION"]);
                                    mStruct.DefaultValue = SqlFormat.FormatDefaultValue(dalType, row["COLUMN_DEFAULT"], 0, sqlType);    //"COLUMN_DEFAULT"
                                    mStruct.IsPrimaryKey = Convert.ToBoolean(row["PRIMARY_KEY"]);
                                    mStruct.SqlTypeName  = dataTypeName;
                                    mStruct.TableName    = SqlFormat.NotKeyword(tableName);
                                    mdcs.Add(mStruct);
                                }
                                #endregion
                                break;

                            case DataBaseType.Access:
                                #region Access
                                DataTable       keyDt, valueDt;
                                string          sqlText = SqlFormat.BuildSqlWithWhereOneEqualsTow(tableName);// string.Format("select * from {0} where 1=2", tableName);
                                OleDbConnection con     = new OleDbConnection(helper.Con.ConnectionString);
                                OleDbCommand    com     = new OleDbCommand(sqlText, con);
                                con.Open();
                                keyDt   = com.ExecuteReader(CommandBehavior.KeyInfo).GetSchemaTable();
                                valueDt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, SqlFormat.NotKeyword(tableName) });
                                con.Close();
                                con.Dispose();

                                if (keyDt != null && valueDt != null)
                                {
                                    string    columnName = string.Empty, sqlTypeName = string.Empty;
                                    bool      isKey = false, isCanNull = true, isAutoIncrement = false;
                                    int       maxSize      = -1;
                                    short     maxSizeScale = 0;
                                    SqlDbType sqlDbType;
                                    foreach (DataRow row in keyDt.Rows)
                                    {
                                        columnName      = row["ColumnName"].ToString();
                                        isKey           = Convert.ToBoolean(row["IsKey"]);       //IsKey
                                        isCanNull       = Convert.ToBoolean(row["AllowDBNull"]); //AllowDBNull
                                        isAutoIncrement = Convert.ToBoolean(row["IsAutoIncrement"]);
                                        sqlTypeName     = Convert.ToString(row["DataType"]);
                                        sqlDbType       = DataType.GetSqlType(sqlTypeName);
                                        short.TryParse(Convert.ToString(row["NumericScale"]), out maxSizeScale);
                                        if (Convert.ToInt32(row["NumericPrecision"]) > 0)    //NumericPrecision
                                        {
                                            maxSize = Convert.ToInt32(row["NumericPrecision"]);
                                        }
                                        else
                                        {
                                            long len = Convert.ToInt64(row["ColumnSize"]);
                                            if (len > int.MaxValue)
                                            {
                                                maxSize = int.MaxValue;
                                            }
                                            else
                                            {
                                                maxSize = (int)len;
                                            }
                                        }
                                        mStruct              = new MCellStruct(columnName, sqlDbType, isAutoIncrement, isCanNull, maxSize);
                                        mStruct.Scale        = maxSizeScale;
                                        mStruct.IsPrimaryKey = isKey;
                                        mStruct.SqlTypeName  = sqlTypeName;
                                        mStruct.TableName    = SqlFormat.NotKeyword(tableName);
                                        foreach (DataRow item in valueDt.Rows)
                                        {
                                            if (columnName == item[3].ToString())    //COLUMN_NAME
                                            {
                                                if (item[8].ToString() != "")
                                                {
                                                    mStruct.DefaultValue = SqlFormat.FormatDefaultValue(dalType, item[8], 0, sqlDbType);    //"COLUMN_DEFAULT"
                                                }
                                                break;
                                            }
                                        }
                                        mdcs.Add(mStruct);
                                    }
                                }

                                #endregion
                                break;
                            }
                        }
                    }
                    catch (Exception err)
                    {
                        Log.Write(err, LogType.DataBase);
                        //helper.DebugInfo.Append(err.Message);
                    }
                    #endregion
                }
            }
            if (mdcs.Count > 0)
            {
                //移除被标志的列:
                string[] fields = AppConfig.DB.HiddenFields.Split(',');
                foreach (string item in fields)
                {
                    string field = item.Trim();
                    if (!string.IsNullOrEmpty(field) & mdcs.Contains(field))
                    {
                        mdcs.Remove(field);
                    }
                }
            }
            #region 缓存设置

            if (!_ColumnCache.ContainsKey(key) && mdcs.Count > 0)
            {
                _ColumnCache.Add(key, mdcs.Clone());
                if (!string.IsNullOrEmpty(AppConfig.DB.SchemaMapPath))
                {
                    string folderPath = AppConfig.RunPath + AppConfig.DB.SchemaMapPath;

                    if (!System.IO.Directory.Exists(folderPath))
                    {
                        System.IO.Directory.CreateDirectory(folderPath);
                    }
                    mdcs.WriteSchema(folderPath + key + ".ts");
                }
            }
            #endregion
            return(mdcs);
        }
Esempio n. 26
0
        public static MDataColumn GetColumns(Type typeInfo)
        {
            string key = "ColumnCache:" + typeInfo.FullName;

            if (columnCache.ContainsKey(key))
            {
                return(columnCache[key].Clone());
            }
            else
            {
                #region 获取列结构
                MDataColumn mdc = new MDataColumn();
                switch (StaticTool.GetSystemType(ref typeInfo))
                {
                case SysType.Base:
                case SysType.Enum:
                    mdc.Add(typeInfo.Name, DataType.GetSqlType(typeInfo), false);
                    return(mdc);

                case SysType.Generic:
                case SysType.Collection:
                    Type[] argTypes;
                    Tool.StaticTool.GetArgumentLength(ref typeInfo, out argTypes);
                    foreach (Type type in argTypes)
                    {
                        mdc.Add(type.Name, DataType.GetSqlType(type), false);
                    }
                    argTypes = null;
                    return(mdc);
                }

                PropertyInfo[] pis = StaticTool.GetPropertyInfo(typeInfo);

                SqlDbType sqlType;
                for (int i = 0; i < pis.Length; i++)
                {
                    sqlType = SQL.DataType.GetSqlType(pis[i].PropertyType);
                    mdc.Add(pis[i].Name, sqlType);
                    MCellStruct column = mdc[i];
                    column.MaxSize = DataType.GetMaxSize(sqlType);
                    if (i == 0)
                    {
                        column.IsPrimaryKey = true;
                        column.IsCanNull    = false;

                        if (column.ColumnName.ToLower().Contains("id") && (column.SqlType == System.Data.SqlDbType.Int || column.SqlType == SqlDbType.BigInt))
                        {
                            column.IsAutoIncrement = true;
                        }
                    }
                    else if (i > pis.Length - 3 && sqlType == SqlDbType.DateTime && pis[i].Name.EndsWith("Time"))
                    {
                        column.DefaultValue = SqlValue.GetDate;
                    }
                }
                pis = null;
                #endregion

                if (!columnCache.ContainsKey(key))
                {
                    columnCache.Add(typeInfo.FullName, mdc.Clone());
                }

                return(mdc);
            }
        }
Esempio n. 27
0
 /// <summary>
 /// 是否存在缓存
 /// </summary>
 /// <param name="key">标识</param>
 /// <returns></returns>
 public override bool Contains(string key)
 {
     return(theCache.ContainsKey(key) && theKeyTime.ContainsKey(key) && theKeyTime[key] > DateTime.Now);
 }
Esempio n. 28
0
        /// <param name="fileName">文件依赖路径</param>
        public override bool Set(string key, object value, double cacheMinutes, string fileName)
        {
            try
            {
                if (string.IsNullOrEmpty(key))
                {
                    return(false);
                }
                if (value == null)
                {
                    return(Remove(key));
                }
                lock (lockObj)
                {
                    if (theCache.ContainsKey(key))
                    {
                        theCache[key] = value;
                    }
                    else
                    {
                        theCache.Add(key, value);//2:设置value
                    }
                    double cacheTime = cacheMinutes;
                    if (cacheMinutes <= 0)
                    {
                        cacheTime = AppConfig.Cache.DefaultCacheTime;
                    }
                    DateTime cTime     = DateTime.Now.AddMinutes(cacheTime);
                    int      workCount = GetWorkCount(cTime);
                    if (theKeyTime.ContainsKey(key))
                    {
                        int wc = GetWorkCount(theKeyTime[key]);
                        if (wc != workCount && theTime.ContainsKey(wc))
                        {
                            if (theTime[wc].Contains(key))
                            {
                                theTime[wc].Remove(key); //移除旧值
                            }
                        }
                        theKeyTime[key] = cTime;
                    }
                    else
                    {
                        theKeyTime.Add(key, cTime);
                    }

                    if (theTime.ContainsKey(workCount))//3:设置time
                    {
                        if (!theTime[workCount].Contains(key))
                        {
                            theTime[workCount].Add(key);
                        }
                    }
                    else
                    {
                        MList <string> list = new MList <string>();
                        list.Add(key);
                        theTime.Add(workCount, list);
                    }

                    if (!string.IsNullOrEmpty(fileName))//3:设置file
                    {
                        if (fileName.IndexOf("\\\\") > -1)
                        {
                            fileName = fileName.Replace("\\\\", "\\");
                        }
                        if (!theFileName.ContainsKey(key))
                        {
                            theFileName.Add(key, fileName);
                        }
                        string folder = Path.GetDirectoryName(fileName);
                        if (!theFolderWatcher.ContainsKey(folder) && Directory.Exists(folder))
                        {
                            theFolderWatcher.Add(folder, CreateFileSystemWatcher(folder));
                        }

                        if (theFolderKeys.ContainsKey(folder))
                        {
                            if (!theFolderKeys[folder].Contains(key))
                            {
                                theFolderKeys[folder].Add(key);
                            }
                        }
                        else
                        {
                            MList <string> list = new MList <string>();
                            list.Add(key);
                            theFolderKeys.Add(folder, list);
                        }
                    }
                }
                return(true);
            }
            catch (Exception err)
            {
                Log.Write(err, LogType.Cache);
                errorCount++;
                return(false);
            }
        }