Ejemplo n.º 1
0
        protected virtual void PreLoadExecute(IDictionary <string, IStorageContext> storageContexts)
        {
            foreach (KeyValuePair <string, IStorageContext> context in storageContexts)
            {
                IStorageContext storageContext = context.Value;
                string          sConnection    = StorageParser.BuildConnectionString(storageContext.Storage);
                storageContext.Connection =
                    storageContext.Storage.Pooling
                        ?
                    DbConnectionPoolManager.GetConnection(storageContext.StorageName, sConnection)
                        :
                    DatabaseFactory.GetDbConnection(storageContext.Storage.DatabaseStyle, sConnection);

                try
                {
                    if (ConnectionState.Open != storageContext.Connection.State)
                    {
                        storageContext.Connection.Open();
                    }
                }
                catch (Exception exc)
                {
                    IStorageAttribute storageAttr = (IStorageAttribute)StorageCache.Get(storageContext.StorageName);
                    storageAttr.IsHealth = false;
                    UnhealthyStorage.Add(storageAttr.Name);
                    if (null != Logger)
                    {
                        Logger.WarnFormat("Storage:{0} can not open.Set the health is false and it not used until the health set true.", storageAttr.Name);
                    }
                    IConnectionNotify notify = AlbianServiceRouter.GetService <IConnectionNotify>();
                    if (null != notify)
                    {
                        Logger.Info("send message when open database is error.");
                        string msg = string.Format("Server:{0},Database:{1},Exception Message:{2}.", storageContext.Storage.Server, storageContext.Storage.Database, exc.Message);
                        notify.SendMessage(msg);
                    }
                    throw exc;
                }
                if (storageContext.Storage.Transactional)
                {
                    storageContext.Transaction =
                        storageContext.Connection.BeginTransaction(IsolationLevel.ReadUncommitted);
                }
                foreach (IFakeCommandAttribute fc in storageContext.FakeCommand)
                {
                    IDbCommand cmd = storageContext.Connection.CreateCommand();
                    cmd.CommandText = fc.CommandText;
                    cmd.CommandType = CommandType.Text;
                    if (storageContext.Storage.Transactional)
                    {
                        cmd.Transaction = storageContext.Transaction;
                    }
                    foreach (DbParameter para in fc.Paras)
                    {
                        cmd.Parameters.Add(para);
                    }
                    storageContext.Command.Add(cmd);
                }
            }
        }
Ejemplo n.º 2
0
        public ITask BuildQueryTask <T>(string rountingName, int top, IFilterCondition[] where,
                                        IOrderByCondition[] orderby)
            where T : class, IAlbianObject, new()
        {
            ITask task = new Task();
            IFakeCommandBuilder    fakeBuilder                    = new FakeCommandBuilder();
            IStorageContextBuilder storageContextBuilder          = new StorageContextBuilder();
            IDictionary <string, IStorageContext> storageContexts =
                storageContextBuilder.GenerateStorageContexts <T>(rountingName, top, where, orderby);

            task.Context = storageContexts;
            foreach (KeyValuePair <string, IStorageContext> context in task.Context)
            {
                IStorageContext storageContext = context.Value;
                object          oStorage       = StorageCache.Get(context.Key);
                if (null == oStorage)
                {
                    if (null != Logger)
                    {
                        Logger.ErrorFormat("There is no {0} storage attribute in the storage cached.",
                                           storageContext.StorageName);
                    }
                    return(null);
                }
                IStorageAttribute storage = (IStorageAttribute)oStorage;
                storageContext.Storage = storage;
            }
            return(task);
        }
Ejemplo n.º 3
0
        public static string BuildConnectionString(IStorageAttribute storageAttribute)
        {
            var sbString = new StringBuilder(150);

            sbString.AppendFormat("Server={0};Initial Catalog={1};", storageAttribute.Server, storageAttribute.Database);
            if (storageAttribute.IntegratedSecurity)
            {
                sbString.Append("Integrated Security=SSPI;");
            }
            else
            {
                sbString.AppendFormat("User ID={0};Password={1};", storageAttribute.Uid, storageAttribute.Password);
            }
            if (0 != storageAttribute.Timeout)
            {
                sbString.AppendFormat("Connection Timeout={0};", storageAttribute.Timeout);
            }
            if (DatabaseStyle.MySql == storageAttribute.DatabaseStyle)             //chinese charset
            {
                sbString.AppendFormat("charset = {0};", storageAttribute.Charset); //chinese charset,and the space with both sides from = must exist
                //do not ask me why must exist space,then konwed by god only
                // if you have chinese,the chinese word with 2 char length
            }
            return(sbString.ToString());
        }
Ejemplo n.º 4
0
        public ITask BuildSaveTask <T>(T target)
            where T : IAlbianObject
        {
            ITask task = new Task();
            IFakeCommandBuilder    fakeBuilder           = new FakeCommandBuilder();
            IStorageContextBuilder storageContextBuilder = new StorageContextBuilder();

            task.Context = storageContextBuilder.GenerateStorageContexts(target,
                                                                         fakeBuilder.GenerateFakeCommandByRoutings,
                                                                         fakeBuilder.BuildSaveFakeCommandByRouting);
            foreach (KeyValuePair <string, IStorageContext> context in task.Context)
            {
                IStorageContext storageContext = context.Value;
                object          oStorage       = StorageCache.Get(context.Key);
                if (null == oStorage)
                {
                    if (null != Logger)
                    {
                        Logger.ErrorFormat("There is no {0} storage attribute in the storage cached.",
                                           storageContext.StorageName);
                    }
                    return(null);
                }
                IStorageAttribute storage = (IStorageAttribute)oStorage;
                storageContext.Storage = storage;
            }
            return(task);
        }
Ejemplo n.º 5
0
        public bool Test(string storageName)
        {
            IStorageAttribute storageAttr = (IStorageAttribute)StorageCache.Get(storageName);
            string            sConnection = StorageParser.BuildConnectionString(storageAttr);
            IDbConnection     conn        =
                storageAttr.Pooling
                    ?
                DbConnectionPoolManager.GetConnection(storageName, sConnection)
                    :
                DatabaseFactory.GetDbConnection(storageAttr.DatabaseStyle, sConnection);

            try
            {
                if (ConnectionState.Open != conn.State)
                {
                    conn.Open();
                }
                IDbCommand cmd = conn.CreateCommand();
                cmd.CommandText = "SELECT 1 AS Row";
                cmd.CommandType = CommandType.Text;
                object oValue = cmd.ExecuteScalar();
                int    value;
                if (int.TryParse(oValue.ToString(), out value) && 1 == value)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception exc)
            {
                return(false);
            }
            finally
            {
                if (ConnectionState.Closed != conn.State)
                {
                    conn.Close();
                }
                if (storageAttr.Pooling)
                {
                    DbConnectionPoolManager.RetutnConnection(storageAttr.Name, conn);
                }
                else
                {
                    conn.Dispose();
                    conn = null;
                }
            }
        }
Ejemplo n.º 6
0
        protected override IStorageAttribute ParserStorage(XmlNode node)
        {
            if (null == node)
            {
                throw new ArgumentNullException("node");
            }
            IStorageAttribute storageAttribute = GenerateStorageAttribute(node);

            if (string.IsNullOrEmpty(storageAttribute.Uid) && !storageAttribute.IntegratedSecurity)
            {
                throw new Exception("the database authentication mechanism is error.");
            }
            StorageCache.InsertOrUpdate(storageAttribute.Name, storageAttribute);
            return(storageAttribute);
        }
Ejemplo n.º 7
0
 public void Check()
 {
     while (true)
     {
         Hashtable ht = UnhealthyStorage.UnhealthyStorages;
         if (0 != ht.Count)
         {
             foreach (KeyValuePair <string, string> kv in ht)
             {
                 if (Test(kv.Value))
                 {
                     IStorageAttribute storageAttr = (IStorageAttribute)StorageCache.Get(kv.Value);
                     storageAttr.IsHealth = true;
                 }
             }
         }
         Thread.Sleep(300 * 1000);
     }
 }
Ejemplo n.º 8
0
        protected override IDictionary <string, IStorageAttribute> ParserStorages(XmlNode node)
        {
            if (null == node)
            {
                throw new ArgumentNullException("node");
            }
            XmlNodeList nodes = node.SelectNodes("Storage");

            if (null == nodes || 0 == nodes.Count)
            {
                throw new Exception("the Storage node is empty in the Storage..config");
            }
            IDictionary <string, IStorageAttribute> dic = new Dictionary <string, IStorageAttribute>();
            int idx = 0;

            foreach (XmlNode n in nodes)
            {
                IStorageAttribute storageAttribute = ParserStorage(n);
                if (null != storageAttribute)
                {
                    dic.Add(storageAttribute.Name, storageAttribute);
                    if (0 == idx)
                    {
                        //insert the default storage
                        //the default is the first storage
                        StorageCache.InsertOrUpdate(DefaultStorageName, storageAttribute);
                    }
                    idx++;
                }
            }

            if (0 == dic.Count)
            {
                throw new Exception("the error in the storage.config");
            }
            return(dic);
        }
Ejemplo n.º 9
0
 public static string BuildConnectionString(IStorageAttribute storageAttribute)
 {
     var sbString = new StringBuilder(150);
     sbString.AppendFormat("Server={0};Initial Catalog={1};", storageAttribute.Server, storageAttribute.Database);
     if (storageAttribute.IntegratedSecurity)
     {
         sbString.Append("Integrated Security=SSPI;");
     }
     else
     {
         sbString.AppendFormat("User ID={0};Password={1};", storageAttribute.Uid, storageAttribute.Password);
     }
     if (0 != storageAttribute.Timeout)
     {
         sbString.AppendFormat("Connection Timeout={0};", storageAttribute.Timeout);
     }
     if (DatabaseStyle.MySql == storageAttribute.DatabaseStyle)//chinese charset
     {
         sbString.AppendFormat("charset = {0};",storageAttribute.Charset);//chinese charset,and the space with both sides from = must exist
                                             //do not ask me why must exist space,then konwed by god only
                                             // if you have chinese,the chinese word with 2 char length
     }
     return sbString.ToString();
 }
Ejemplo n.º 10
0
        public IFakeCommandAttribute BuildCreateFakeCommandByRouting <T>(PermissionMode permission, T target,
                                                                         IRoutingAttribute routing,
                                                                         IObjectAttribute objectAttribute,
                                                                         PropertyInfo[] properties)
            where T : IAlbianObject
        {
            if (null == routing)
            {
                throw new ArgumentNullException("routing");
            }
            if (null == properties || 0 == properties.Length)
            {
                throw new ArgumentNullException("properties");
            }
            if (null == objectAttribute)
            {
                throw new ArgumentNullException("objectAttribute");
            }
            if (0 == (permission & routing.Permission))
            {
                if (null != Logger)
                {
                    Logger.WarnFormat("The routing permission {0} is no enough.", permission);
                }
                return(null);
            }



            //create the connection string
            IStorageAttribute storageAttr = (IStorageAttribute)StorageCache.Get(routing.StorageName);

            if (null == storageAttr)
            {
                if (null != Logger)
                {
                    Logger.WarnFormat(
                        "No {0} rounting mapping storage attribute in the sotrage cache.Use default storage.",
                        routing.Name);
                }
                storageAttr = (IStorageAttribute)StorageCache.Get(StorageParser.DefaultStorageName);
            }

            if (!storageAttr.IsHealth)
            {
                if (null != Logger)
                {
                    Logger.WarnFormat("Routing:{0},Storage:{1} is not health.", routing.Name, storageAttr.Name);
                }
                return(null);
            }

            var sbInsert = new StringBuilder();
            var sbCols   = new StringBuilder();
            var sbValues = new StringBuilder();

            IList <DbParameter> paras = new List <DbParameter>();

            //create the hash table name
            string tableFullName = Utils.GetTableFullName(routing, target);

            //build the command text
            IDictionary <string, IMemberAttribute> members = objectAttribute.MemberAttributes;

            foreach (PropertyInfo property in properties)
            {
                object value = property.GetValue(target, null);
                if (null == value)
                {
                    continue;
                }
                IMemberAttribute member = members[property.Name];
                if (!member.IsSave)
                {
                    continue;
                }
                sbCols.AppendFormat("{0},", member.FieldName);
                string paraName = DatabaseFactory.GetParameterName(storageAttr.DatabaseStyle, member.FieldName);
                sbValues.AppendFormat("{0},", paraName);
                paras.Add(DatabaseFactory.GetDbParameter(storageAttr.DatabaseStyle, paraName, member.DBType, value,
                                                         member.Length));
            }
            int colsLen = sbCols.Length;

            if (0 < colsLen)
            {
                sbCols.Remove(colsLen - 1, 1);
            }
            int valLen = sbValues.Length;

            if (0 < valLen)
            {
                sbValues.Remove(valLen - 1, 1);
            }
            sbInsert.AppendFormat("INSERT INTO {0} ({1}) VALUES({2}) ", tableFullName, sbCols, sbValues);
            IFakeCommandAttribute fakeCmd = new FakeCommandAttribute
            {
                CommandText = sbInsert.ToString(),
                Paras       = ((List <DbParameter>)paras).ToArray(),
                StorageName = routing.StorageName
            };

            return(fakeCmd);
        }
Ejemplo n.º 11
0
        public IFakeCommandAttribute GenerateQuery <T>(string rountingName, int top, IFilterCondition[] where,
                                                       IOrderByCondition[] orderby)
            where T : class, IAlbianObject, new()
        {
            Type   type        = typeof(T);
            string fullName    = AssemblyManager.GetFullTypeName(type);
            object oProperties = PropertyCache.Get(fullName);

            PropertyInfo[] properties;
            if (null == oProperties)
            {
                if (null != Logger)
                {
                    Logger.Error("Get the object property info from cache is null.Reflection now and add to cache.");
                }
                throw new PersistenceException("object property is null in the cache.");
            }
            properties = (PropertyInfo[])oProperties;
            object oAttribute = ObjectCache.Get(fullName);

            if (null == oAttribute)
            {
                if (null != Logger)
                {
                    Logger.ErrorFormat("The {0} object attribute is null in the object cache.", fullName);
                }
                throw new Exception("The object attribute is null");
            }
            StringBuilder     sbSelect        = new StringBuilder();
            StringBuilder     sbCols          = new StringBuilder();
            StringBuilder     sbWhere         = new StringBuilder();
            StringBuilder     sbOrderBy       = new StringBuilder();
            IObjectAttribute  objectAttribute = (IObjectAttribute)oAttribute;
            IRoutingAttribute routing;

            if (!objectAttribute.RoutingAttributes.TryGetValue(rountingName, out routing))
            {
                if (null != Logger)
                {
                    Logger.WarnFormat("There is not routing of the {} object.Albian use the default routing tempate.",
                                      rountingName);
                }
                routing = objectAttribute.RountingTemplate;
            }

            if (0 == (PermissionMode.R & routing.Permission))
            {
                if (null != Logger)
                {
                    Logger.WarnFormat("The routing permission {0} is no enough.", routing.Permission);
                }
                return(null);
            }

            IStorageAttribute storageAttr = (IStorageAttribute)StorageCache.Get(routing.StorageName);

            if (null == storageAttr)
            {
                if (null != Logger)
                {
                    Logger.WarnFormat(
                        "No {0} rounting mapping storage attribute in the sotrage cache.Use default storage.",
                        routing.Name);
                }
                storageAttr = (IStorageAttribute)StorageCache.Get(StorageParser.DefaultStorageName);
            }

            if (!storageAttr.IsHealth)
            {
                if (null != Logger)
                {
                    Logger.WarnFormat("Routing:{0},Storage:{1} is not health.", routing.Name, storageAttr.Name);
                }
                return(null);
            }

            IDictionary <string, IMemberAttribute> members = objectAttribute.MemberAttributes;
            T target = AlbianObjectFactory.CreateInstance <T>();

            foreach (PropertyInfo property in properties)
            {
                IMemberAttribute member = members[property.Name];
                if (!member.IsSave)
                {
                    continue;
                }
                sbCols.AppendFormat("{0},", member.FieldName);

                if (null != where)
                {
                    foreach (IFilterCondition condition in where) //have better algorithm??
                    {
                        if (condition.PropertyName == property.Name)
                        {
                            property.SetValue(target, condition.Value, null); //Construct the splite object
                            break;
                        }
                    }
                }
                if (null != orderby)
                {
                    foreach (IOrderByCondition order in orderby)
                    {
                        if (order.PropertyName == property.Name)
                        {
                            sbOrderBy.AppendFormat("{0} {1},", member.FieldName,
                                                   System.Enum.GetName(typeof(SortStyle), order.SortStyle));
                            break;
                        }
                    }
                }
            }
            if (0 != sbOrderBy.Length)
            {
                sbOrderBy.Remove(sbOrderBy.Length - 1, 1);
            }
            if (0 != sbCols.Length)
            {
                sbCols.Remove(sbCols.Length - 1, 1);
            }
            IList <DbParameter> paras = new List <DbParameter>();

            if (null != where && 0 != where.Length)
            {
                foreach (IFilterCondition condition in where)
                {
                    IMemberAttribute member = members[condition.PropertyName];
                    if (!member.IsSave)
                    {
                        continue;
                    }
                    sbWhere.AppendFormat(" {0} {1} {2} {3} ", Utils.GetRelationalOperators(condition.Relational),
                                         member.FieldName, Utils.GetLogicalOperation(condition.Logical),
                                         DatabaseFactory.GetParameterName(storageAttr.DatabaseStyle, member.FieldName));
                    paras.Add(DatabaseFactory.GetDbParameter(storageAttr.DatabaseStyle, member.FieldName, member.DBType,
                                                             condition.Value, member.Length));
                }
            }
            string tableFullName = Utils.GetTableFullName(routing, target);

            switch (storageAttr.DatabaseStyle)
            {
            case DatabaseStyle.MySql:
            {
                sbSelect.AppendFormat("SELECT {0} FROM {1} WHERE 1=1 {2} {3} {4}",
                                      sbCols, tableFullName, sbWhere,
                                      0 == sbOrderBy.Length ? string.Empty : string.Format("ORDER BY {0}", sbOrderBy),
                                      0 == top ? string.Empty : string.Format("LIMIT {0}", top)
                                      );
                break;
            }

            case DatabaseStyle.Oracle:
            {
                if (0 == top)
                {
                    sbSelect.AppendFormat("SELECT {0} FROM {1} WHERE 1=1 {2} {3}",
                                          sbCols, tableFullName, sbWhere,
                                          0 == sbOrderBy.Length ? string.Empty : string.Format("ORDER BY {0}", sbOrderBy));
                }
                else
                {
                    sbSelect.AppendFormat("SELECT A.* FROM (SELECT {0} FROM {1} WHERE 1=1 {2} {3})A WHERE ROWNUM <= {4}",
                                          sbCols, tableFullName, sbWhere,
                                          0 == sbOrderBy.Length ? string.Empty : string.Format("ORDER BY {0}", sbOrderBy),
                                          top);
                }

                break;
            }

            case DatabaseStyle.SqlServer:
            default:
            {
                sbSelect.AppendFormat("SELECT {0} {1} FROM {2} WHERE 1=1 {3} {4}",
                                      0 == top ? string.Empty : string.Format("TOP {0}", top),
                                      sbCols, tableFullName, sbWhere,
                                      0 == sbOrderBy.Length ? string.Empty : string.Format("ORDER BY {0}", sbOrderBy));
                break;
            }
            }

            IFakeCommandAttribute fakeCommand = new FakeCommandAttribute
            {
                CommandText = sbSelect.ToString(),
                Paras       = ((List <DbParameter>)paras).ToArray(),
                StorageName = storageAttr.Name,
            };

            return(fakeCommand);
        }
Ejemplo n.º 12
0
        public ITask BuildCreateTask <T>(IList <T> target)
            where T : IAlbianObject
        {
            ITask task = new Task();
            IFakeCommandBuilder    fakeBuilder           = new FakeCommandBuilder();
            IStorageContextBuilder storageContextBuilder = new StorageContextBuilder();

            foreach (T o in target)
            {
                IDictionary <string, IStorageContext> storageContexts = storageContextBuilder.GenerateStorageContexts(o,
                                                                                                                      fakeBuilder
                                                                                                                      .
                                                                                                                      GenerateFakeCommandByRoutings,
                                                                                                                      fakeBuilder
                                                                                                                      .
                                                                                                                      BuildCreateFakeCommandByRouting);
                if (null == storageContexts || 0 == storageContexts.Count)
                {
                    if (null != Logger)
                    {
                        Logger.Error("The storagecontexts is empty.");
                    }
                    throw new Exception("The storagecontexts is null.");
                }
                if (null == task.Context || 0 == task.Context.Count)
                {
                    task.Context = storageContexts;
                    continue;
                }
                foreach (KeyValuePair <string, IStorageContext> storageContext in storageContexts)
                {
                    if (task.Context.ContainsKey(storageContext.Key))
                    {
                        task.Context[storageContext.Key].FakeCommand = task.Context.ContainsKey(storageContext.Key)
                                                                           ? Utils.Concat(
                            task.Context[storageContext.Key].
                            FakeCommand,
                            storageContext.Value.FakeCommand)
                                                                           : storageContext.Value.FakeCommand;
                    }
                    else
                    {
                        task.Context.Add(storageContext);
                    }
                }
            }

            foreach (KeyValuePair <string, IStorageContext> context in task.Context)
            {
                IStorageContext storageContext = context.Value;
                object          oStorage       = StorageCache.Get(context.Key);
                if (null == oStorage)
                {
                    if (null != Logger)
                    {
                        Logger.ErrorFormat("There is no {0} storage attribute in the storage cached.",
                                           storageContext.StorageName);
                    }
                    return(null);
                }
                IStorageAttribute storage = (IStorageAttribute)oStorage;
                storageContext.Storage = storage;
            }
            return(task);
        }