Esempio n. 1
0
        /// <summary>
        /// Performs the add or update.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <param name="transaction"></param>
        public void PerformAddOrUpdate(AbstractEntity entity, ExamineTransaction transaction)
        {
            Mandate.ParameterNotNull(entity, "entity");

            //use the mappers to map this entity (whatever it might be) to an IndexCategoryOperation
            var indexOperation = _frameworkContext.TypeMappers.MapToIntent <NestedHiveIndexOperation>(entity);

            if (TypeFinder.IsTypeAssignableFrom <TypedEntity>(entity.GetType()))
            {
                //since we're updating the schema when its an entity, need to ensure associations are removed
                RemoveSchemaAssociations(((TypedEntity)entity).EntitySchema, ExamineManager, transaction);
            }
            if (TypeFinder.IsTypeAssignableFrom <EntitySchema>(entity.GetType()))
            {
                //need to ensure schema associations are removed
                RemoveSchemaAssociations((EntitySchema)entity, ExamineManager, transaction);
            }

            transaction.EnqueueIndexOperation(indexOperation);

            //we need to recursively add all operations and sub operations to the queue
            foreach (var operation in indexOperation.SubIndexOperations.SelectRecursive(x => x.SubIndexOperations))
            {
                transaction.EnqueueIndexOperation(operation);
            }
        }
Esempio n. 2
0
        private bool TryUpdateExisting(AbstractEntity persistedEntity)
        {
            var mappers = FrameworkContext.TypeMappers;

            // Get the entity with matching Id, provided the incoming Id is not null / empty
            if (!persistedEntity.Id.IsNullValueOrEmpty())
            {
                Type rdbmsType;
                if (mappers.TryGetDestinationType(persistedEntity.GetType(), typeof(IReferenceByGuid), out rdbmsType))
                {
                    //// Temp hack for testing
                    //if (typeof(NodeVersion) == rdbmsType && typeof(TypedEntity) == persistedEntity.GetType())
                    //{
                    //    rdbmsType = typeof(Node);

                    //    var nodeVersions = global::NHibernate.Linq.LinqExtensionMethods.Query<NodeVersion>(InnerDataContext.NhibernateSession).Where(x => x.Node.Id == persistedEntity.Id.AsGuid);
                    //    var firstOrDefault = nodeVersions.FirstOrDefault();
                    //    if (firstOrDefault == null) return false;

                    //    var latest = GetMostRecentVersionFromQuery(firstOrDefault.Node);
                    //    if (latest != null)
                    //    {
                    //        mappers.Map(persistedEntity, latest, persistedEntity.GetType(), latest.GetType());
                    //        //InnerDataContext.NhibernateSession.Evict(latest);
                    //        latest = InnerDataContext.NhibernateSession.Merge(latest) as NodeVersion;
                    //        //InnerDataContext.NhibernateSession.SaveOrUpdate(existingEntity);
                    //        mappers.Map(latest, persistedEntity, latest.GetType(), persistedEntity.GetType());
                    //        SetOutgoingId(persistedEntity);
                    //        //_trackNodePostCommits.Add((IReferenceByGuid)existingEntity, persistedEntity);
                    //        return true;
                    //    }
                    //}

                    var existingEntity = Helper.NhSession.Get(rdbmsType, (Guid)persistedEntity.Id.Value);
                    if (existingEntity != null)
                    {
                        mappers.Map(persistedEntity, existingEntity, persistedEntity.GetType(), existingEntity.GetType());
                        existingEntity = Helper.NhSession.Merge(existingEntity);
                        //InnerDataContext.NhibernateSession.SaveOrUpdate(existingEntity);
                        mappers.Map(existingEntity, persistedEntity, existingEntity.GetType(), persistedEntity.GetType());
                        // ##API2: Disabled: SetOutgoingId(persistedEntity);
                        //_trackNodePostCommits.Add((IReferenceByGuid)existingEntity, persistedEntity);
                        return(true);
                    }
                }
            }
            return(false);
        }
Esempio n. 3
0
        /// <summary>
        /// 创建主键
        /// </summary>
        /// <param name="Generator"></param>
        public virtual void CreatePrimaryKey(IPKGenerator Generator)
        {
            AbstractEntity Entity = m_Entity as AbstractEntity;

            //创建主键
            if (Generator == null)
            {
                throw new MappingException("创建主键生成器失败,主键生成器必须实现Draco.DB.ORM.AutoSQL.PKGenerator.IPKGenerator接口,请检查映射文件中主键生成器的配置信息!");
            }
            Hashtable Next = Generator.GeneratNextPrimaryKey(m_Mapping);

            if (Next != null && Next.Count > 0)
            {
                foreach (string PropertyName in Next.Keys)
                {
                    object       NextValue = Next[PropertyName];
                    PropertyInfo Property  = Entity.GetType().GetProperty(PropertyName);
                    if (Property != null)
                    {
                        object _value = Convert.ChangeType(NextValue, Property.PropertyType);
                        Property.SetValue(Entity, _value, null);
                    }
                }
            }
        }
Esempio n. 4
0
        /// <summary>
        /// 确认主键是否有值
        /// </summary>
        /// <returns></returns>
        public virtual bool CheckePrimaryKey()
        {
            AbstractEntity Entity = m_Entity as AbstractEntity;

            if (Entity.ChangedProperties != null && m_Mapping.PrimaryKeyCollection.Count > 0)
            {
                bool HasValue = true;
                foreach (IPrimaryKeyMapping mapping in m_Mapping.PrimaryKeyCollection)
                {
                    if (!Entity.ChangedProperties.ContainsKey(mapping.PropertyName))
                    {
                        //进一步检查主键属性是否有值,因为如果对象是由Handle查询创建的,那么修改的属性中是没有主键的
                        PropertyInfo property = Entity.GetType().GetProperty(mapping.PropertyName);
                        object       val      = property.GetValue(Entity, null);
                        if (val == null || val == DBNull.Value || Convert.ToString(val) == "" || Convert.ToString(val) == "0")
                        {
                            HasValue = false;//有一个主键没有值就要重新生成主键
                        }
                    }
                }
                if (HasValue)//所有的主键都有值,那就返回了
                {
                    return(true);
                }
            }
            return(false);
        }
Esempio n. 5
0
 /// <summary>
 /// 处理传出参数
 /// </summary>
 /// <param name="paras"></param>
 public virtual void ProcessOutputParameters(IDataParameter[] paras)
 {
     if (paras != null && paras.Length > 0)
     {
         foreach (IDataParameter para in paras)
         {
             if (para.Direction == ParameterDirection.Output || para.Direction == ParameterDirection.InputOutput)
             {
                 PropertyInfo Property = m_Entity.GetType().GetProperty(para.ParameterName);
                 if (Property != null)
                 {
                     object _value = Convert.ChangeType(para.Value, Property.PropertyType);
                     Property.SetValue(m_Entity, _value, null);
                 }
             }
         }
     }
 }
Esempio n. 6
0
 private void OnChangedNotify(AbstractEntity sender, CacheItemEventArgs e)
 {
     if (sender != null)
     {
         //这里处理Model更新通知
         Console.WriteLine("update:{0},{1},{2}", sender.GetType().Name, e.ChangeType, e.PropertyName);
         EntitySyncManger.OnChange(sender, e);
     }
 }
Esempio n. 7
0
        private static string GetQueueFormatKey(AbstractEntity entity)
        {
            if (entity == null)
            {
                return(string.Empty);
            }

            return(string.Format("{0}_{1}|{2}",
                                 RedisConnectionPool.EncodeTypeName(entity.GetType().FullName),
                                 entity.GetIdentityId(),
                                 entity.GetKeyCode()));
        }
Esempio n. 8
0
        internal static string GenerateEntityKey(AbstractEntity entity)
        {
            if (entity == null)
            {
                return(string.Empty);
            }

            return(string.Format("{0}_{1}|{2}",
                                 RedisConnectionPool.EncodeTypeName(entity.GetType().FullName),
                                 entity.PersonalId,
                                 entity.GetKeyCode()));
        }
        public void MapAndMerge(AbstractEntity entity, MappingEngineCollection mappers)
        {
            using (DisposableTimer.TraceDuration <NhSessionHelper>("Start MapAndMerge for entity " + entity.Id, "End MapAndMerge"))
                using (NhProfilerLogging.Start(NhSession, "MapAndMerge",
                                               new OdbcParameter("entity", entity)))
                {
                    var rdbmsEntity = mappers.MapToIntent <IReferenceByGuid>(entity);

                    // Track ID generation on the Rdbms object so that it can be pinged to the AbstractEntity upon Save/Update commit
                    rdbmsEntity = NhSession.Merge(rdbmsEntity) as IReferenceByGuid;

                    //InnerDataContext.NhibernateSession.SaveOrUpdate(rdbmsEntity);
                    mappers.Map(rdbmsEntity, entity, rdbmsEntity.GetType(), entity.GetType());
                }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static void TransSend(AbstractEntity entity)
        {
            //watch post entity changed times.
            ProfileManager.PostEntityOfMessageQueueTimes(entity.GetType().FullName, entity.GetKeyCode(), GetOperateMode(entity));

            entity.TempTimeModify = MathUtils.Now;
            string key = GetQueueFormatKey(entity);

            if (!entity.IsInCache)
            {
                CacheFactory.AddOrUpdateEntity(key, entity);
            }
            lock (entitySyncRoot)
            {
                _entitySet.Add(key);
                if (entity.IsDelete)
                {
                    _entityRemoteSet.Add(key);
                }
            }
        }
Esempio n. 11
0
 private bool FindClosestItem(AbstractEntity argEntity)
 {
     return argEntity.GetType() == typeof(Item);
 }
Esempio n. 12
0
        public void AddOrUpdate(AbstractEntity persistedEntity)
        {
            Mandate.That <ArgumentException>(typeof(File).IsAssignableFrom(persistedEntity.GetType()));
            var file = (File)persistedEntity;

            Mandate.That <ArgumentNullException>(!file.Name.IsNullOrWhiteSpace() || !file.Location.IsNullOrWhiteSpace());

            // Make sure that the incoming location has the root storage area prefixed if necessary
            file.Location = EnsureLocationRooted(string.IsNullOrEmpty(file.Location) ? file.Name : file.Location);

            //ensure the file name is set which should always be based on the location
            file.Name = Path.GetFileName(file.Location);

            // Ensure we have an id for the file
            if (HiveIdExtensions.IsNullValueOrEmpty(file.Id))
            {
                file.Id = GenerateId(file.Location);
            }

            // Ensure that the folder exists, if this item is a folder)
            if (file.IsContainer)
            {
                var dir = new DirectoryInfo(file.Location);
                if (!dir.Exists)
                {
                    dir.Create();
                }
            }
            else
            {
                var containerPath = Path.GetDirectoryName(file.Location);
                if (containerPath != null)
                {
                    var dir = new DirectoryInfo(containerPath);
                    if (!dir.Exists)
                    {
                        dir.Create();
                    }
                }
            }

            // Write the file, provided it's not a directory
            if (!file.IsContainer)
            {
                var physicalForWriting = new FileInfo(file.Location);
                if (physicalForWriting.Exists)
                {
                    physicalForWriting.Delete();
                }
                using (var writer = physicalForWriting.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read))
                {
                    writer.Write(file.ContentBytes, 0, file.ContentBytes.Length);
                }
            }

            //var physicalFile = new FileInfo(file.Location);
            //if (physicalFile.Name != file.Name)
            //{
            //    physicalFile.MoveTo(Path.Combine(physicalFile.Directory.FullName, file.Name));
            //}

            // Write relations to disc
            foreach (var relation in file.Relations)
            {
                if (relation.Type.RelationName != FixedRelationTypes.FileRelationType.RelationName)
                {
                    EnsureRelationsFolderExists();

                    var sourceMd5            = relation.SourceId.ToString().ToMd5();
                    var destMd5              = relation.DestinationId.ToString().ToMd5();
                    var relationPath         = Path.Combine(_relationsFolder, sourceMd5 + "-" + destMd5 + ".xml");
                    var relationFileInfo     = new FileInfo(relationPath);
                    var relationContent      = RelationSerializer.ToXml(relation);
                    var relationContentBytes = Encoding.UTF8.GetBytes(relationContent.ToString());

                    if (relationFileInfo.Exists)
                    {
                        relationFileInfo.Delete();
                    }

                    using (
                        var writer = relationFileInfo.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read))
                    {
                        writer.Write(relationContentBytes, 0, relationContentBytes.Length);
                    }
                }
            }
        }
Esempio n. 13
0
 private void OnChangedNotify(AbstractEntity sender, CacheItemEventArgs e)
 {
     if (sender != null)
     {
         //���ﴦ��Model����֪ͨ
         Console.WriteLine("update:{0},{1},{2}", sender.GetType().Name, e.ChangeType, e.PropertyName);
         EntitySyncManger.OnChange(sender, e);
     }
 }
Esempio n. 14
0
 protected bool FindClimbableSurface(AbstractEntity argEntity)
 {
     return argEntity.GetType() == typeof(IvyClimbingBox);
 }
Esempio n. 15
0
 /// <summary>
 /// 更新实体对象
 /// </summary>
 /// <param name="entity">实体对象</param>
 public void SetEntity(AbstractEntity entity)
 {
     this.Clear();
     m_Entity  = entity;
     m_Mapping = ORMAdapterCreator.MappingManager.GetMapping(entity.GetType());
 }
 /// <summary>
 /// 构造
 /// </summary>
 /// <param name="entity"></param>
 /// <param name="DbAdapter"></param>
 public ExpSQLBuilder(AbstractEntity entity, IORMAdapter DbAdapter)
 {
     m_DBAdapter = DbAdapter;
     m_Mapping   = ORMAdapterCreator.MappingManager.GetMapping(entity.GetType());
 }
 /// <summary>
 /// Determines what kind of entity it is and returns its base type
 /// </summary>
 /// <param name="e"></param>
 /// <returns></returns>
 public static Type GetEntityBaseType(this AbstractEntity e)
 {
     return(e.GetType().GetEntityBaseType());
 }