Example #1
0
        /// <summary>
        /// Equalses the specified entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns>A <see cref="System.Boolean"/></returns>
        public virtual bool Equals( Entity entity )
        {
            if ( ReferenceEquals ( null, entity ) )
            {
                return false;
            }
            if ( ReferenceEquals ( this, entity ) )
            {
                return true;
            }
            if ( GetType () != entity.GetType () )
            {
                return false;
            }

            var otherIsTransient = Equals ( entity.Key, ( long )0 );
            var thisIsTransient = Equals ( Key, ( long )0 );

            if ( otherIsTransient && thisIsTransient )
            {
                return ReferenceEquals ( entity, this );
            }

            return entity.Key.Equals ( Key );
        }
 protected void ValidateId(string id, [CallerLineNumber] int lineNumber = 0, [CallerFilePath] string caller = "", [CallerMemberName] string memberName = "")
 {
     if (string.IsNullOrWhiteSpace(id))
     {
         throw new Exception($"Invalid {Entity?.GetType()?.Name} parameter, method name:{caller}, class name: {memberName}, line number: {lineNumber}");
     }
 }
 protected virtual void ValidateId(long?id, [CallerLineNumber] int lineNumber = 0, [CallerFilePath] string caller = "", [CallerMemberName] string memberName = "")
 {
     if (id < 1)
     {
         throw new Exception($"Invalid {Entity?.GetType()?.Name} parameter, method name:{caller}, class name: {memberName}, line number: {lineNumber}");
     }
 }
Example #4
0
        /// <summary>
        /// Constructor referencing an <see cref="Entity"/>
        /// </summary>
        /// <param name="entity"><see cref="Entity"/> reference to be offlined</param>
        /// <param name="addedEntity">Conditional <see cref="Boolean"/> to specify whether or not the <see cref="Entity"/> is Added</param>
        public OfflinableEntity(Entity entity, bool addedEntity = false)
        {
            this.OriginalEntity = entity.GetOriginal();
            this.CurrentEntity = entity;

            if (addedEntity)
            {
                foreach (var collection in entity.GetType().GetProperties().Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(EntityCollection<>)))
                {
                    List<Entity> entities = new List<Entity>();
                    foreach (var entityRef in collection.GetValue(entity, null) as IEnumerable<Entity>)
                    {
                       entities.Add(entityRef);
                    }
                    if (entities.Any())
                    {
                        if (EntityRefs == null)
                        {
                            EntityRefs = new Dictionary<string, List<Entity>>();
                        }
                        this.EntityRefs.Add(collection.Name, entities);
                    }
                }
            }
            this.EntityState = entity.EntityState;
            this.EntityActions = ConvertToOfflinableEntityActions(entity.EntityActions);
        }
 protected void ValidateId(bool?IsDeleted, [CallerLineNumber] int lineNumber = 0, [CallerFilePath] string caller = "", [CallerMemberName] string memberName = "")
 {
     if (IsDeleted.HasValue && IsDeleted == false)
     {
         throw new Exception($"Invalid {Entity?.GetType()?.Name} parameter, method name:{caller}, class name: {memberName}, line number: {lineNumber}");
     }
 }
        public override async Task <List <Organisation> > ListAsync(int pageNumber)
        {
            try
            {
                CurrentPageNumber = pageNumber;

                using (var context = new VTestsContext(OptionsBuilder.Options))
                {
                    List <Organisation> result = await context.Set <Organisation>().AsNoTracking()
                                                 .Where(e => e.IsDeleted == false || e.IsDeleted == null)
                                                 .OrderBy(r => r.Id)
                                                 .Skip(SkippedDbRecordSize)
                                                 .Take(MaxPageSize)
                                                 .ToListAsync();

                    var typeName = Entity?.GetType()?.Name;
                    VLogger.LogInformation($" Successfully retrieved {typeName}'s List with page number {pageNumber} ");
                    CurrentPageNumber = 0;

                    return(result);
                }
            }
            catch (SqlNullValueException s)
            {
                LogError(s, null, pageNumber);

                throw s;
            }
            catch (Exception ex)
            {
                LogError(ex, null, pageNumber);

                throw ex;
            }
        }
 protected void CheckIfNull(TEntity item)
 {
     if (item == null)
     {
         var typeName = Entity?.GetType()?.Name;
         throw new NullReferenceException($"Invalid {typeName} item");
     }
 }
Example #8
0
 private void NewBuildOrder(ActionType actionType, Entity target)
 {
     if (actionType == ActionType.Build)
     {
         if (target != null)
             if (target.GetType() == typeof(Building))
                 _buildingToBuild = target as Building;
     }
 }
        public virtual async Task <long> AddAsync(TEntity item)
        {
            CheckIfNull(item);

            if (item?.Id > 0)
            {
                var typeName = Entity?.GetType()?.Name;
                throw new Exception($"Invalid {typeName}Id");
            }

            item.IsDeleted = false;
            var id = await RepositoryManager.AddAsync(item);

            return(id);
        }
Example #10
0
    // returns callable methods, for triggers etc
    public static string[] GetMethodList(Entity ent)
    {
        string [] tempMethods =
            ent.GetType()
            .GetMethods(BindingFlags.Instance| BindingFlags.Public | BindingFlags.NonPublic |  BindingFlags.FlattenHierarchy)
            .Where(m => m.GetCustomAttributes(typeof(Callable), false).Length > 0)
            .Where(x => !ignoreMethods.Any(n => n == x.Name)) // Don't list methods in the ignoreMethods array (so we can exclude Unity specific methods, etc.)
            .Select(x => x.Name)
            .ToArray();

        if (tempMethods.Length > 0) {
            // sort the list
            Array.Sort<string> (tempMethods);
        }

        return tempMethods;
    }
    private void SetEntity(Entity entity)
    {
        this.entity = entity;

        switch (type)
        {
            case StatBarType.Health:
                entity.OnSelect += ShowStatBar;
                entity.OnDeselect += HideStatBar;
                entity.OnDamageReceive += UpdateStatBar;
                break;
            case StatBarType.BuildProgress:
                entity.OnConstructionProgress += UpdateStatBar;
                if (entity.GetType() == typeof(Building))
                    ((Building)entity).OnPlace += ShowStatBar;
                break;
        }
    }
        public void TestLinqCount()
        {
            var collection = Configuration.GetTestCollection<Entity>();
            if (collection.Exists()) { collection.Drop(); }

            for (int i = 0; i < 100; ++i)
            {
                var e = new Entity() { Name = "Name_" + i };
                collection.Insert(e.GetType(), e, WriteConcern.Acknowledged);
            }

            var query = (from e in collection.AsQueryable<Entity>()
                         where true || e.Name == "Name_22"
                         select e);
            var count = query.Count();

            Assert.AreEqual(100, count);
        }
Example #13
0
        public Task StoreAsync(Page localizedPage, CancellationToken token = default(CancellationToken))
        {
            if (localizedPage == null)
            {
                return(null);
            }

            var page = Page ?? new Page();

            //page.Acl = localizedPage.Acl;

            localizedPage.Acl = null;

            _session.StoreAsync(page, token).Wait(token);

            Task <Site> siteTask = _session.LoadAsync <Site>("sites/" + _requestCulture.Culture.TwoLetterISOLanguageName, token);

            return(Task.WhenAll(siteTask).ContinueWith(task =>
            {
                if (!string.IsNullOrEmpty(Key))
                {
                    var trie = siteTask.Result.Trie;

                    // Update an existing item
                    if (trie.Any(x => x.Value.PageId == page.Id))
                    {
                        var nodeToRemove = trie.SingleOrDefault(x => x.Value.PageId == page.Id);
                        trie.Remove(nodeToRemove.Key);
                        trie.Add(Key, new TrieNode(page.Id, nodeToRemove.Value.ControllerName));
                    }

                    // Don't add the same key
                    else if (!trie.ContainsKey(Key))
                    {
                        trie.Add(Key, new TrieNode(page.Id, Entity.GetType().Name));
                    }
                }

                _session.StoreAsync(localizedPage, string.Join("/", page.Id, _requestCulture.Culture.TwoLetterISOLanguageName), token);

                _session.StoreAsync(Entity, string.Join("/", page.Id, _requestCulture.Culture.TwoLetterISOLanguageName, "content"), token);
            }, token));
        }
Example #14
0
        // Objects
        public void RegisterObject(Entity o)
        {
            objects.Add(o);
            if (o.GetType().GetTypeInfo().IsSubclassOf(typeof(Foliage)) || o.GetType() == typeof(Foliage))
            {
                foliage.Add((Foliage)o);
            }
            else if (o.GetType().GetTypeInfo().IsSubclassOf(typeof(Actor)) || o.GetType() == typeof(Actor))
            {
                actors.Add((Actor)o);
            }

            if (o.GetType().GetTypeInfo().IsSubclassOf(typeof(ShopKeeper)) || o.GetType() == typeof(ShopKeeper))
            {
                MatchShopKeeper = (ShopKeeper)o;
            }
            if (o.GetType().GetTypeInfo().IsSubclassOf(typeof(Snake)) || o.GetType() == typeof(Snake))
            {
                Snakes.Add((Snake)o);
            }
        }
        public void Update()
        {
            Entity.Nom      = Nom;
            Entity.Page_Max = Page_Max;
            Entity.Page_Min = Page_Min;
            C.TypeDeProjet Type = Service.GetOne(Entity);

            if (Type != null)
            {
                foreach (PropertyInfo item in Type.GetType().GetProperties())
                {
                    if (Entity.GetType().GetProperty(item.Name).GetValue(Entity) != item.GetValue(item))
                    {
                        Type.GetType().GetProperty(item.Name).SetValue(Type, item.GetValue(item));
                    }
                }
                Service.Update(Type);
            }
        }
Example #16
0
        public void TestGetEntity()
        {
            var entity = _recorder.TraceContext.GetEntity();

            Assert.AreEqual(entity.GetType(), typeof(FacadeSegment));
            Assert.AreNotEqual(entity.GetType(), typeof(Subsegment));
            Assert.AreNotEqual(entity.GetType(), typeof(Segment));

            _recorder.BeginSubsegment("subsegment1");
            Subsegment subsegment1   = (Subsegment)AWSXRayRecorder.Instance.TraceContext.GetEntity();
            Entity     facadeSegment = subsegment1.RootSegment;

            _recorder.EndSubsegment();

            Assert.AreEqual(facadeSegment.GetType(), typeof(FacadeSegment));
            Assert.IsFalse(facadeSegment.Subsegments.Contains(subsegment1));         // only subsegment is streamed
            Assert.IsFalse(AWSXRayRecorder.Instance.TraceContext.IsEntityPresent()); // facade segment is cleared from AWSXRayRecorder.Instance.TraceContext
            Assert.AreEqual(typeof(LambdaContextContainer), AWSXRayRecorder.Instance.TraceContext.GetType());
        }
Example #17
0
        public bool Equals(Entity other)
        {
            if ((object)other == null)
            {
                return(false);
            }

            if ((object)this == other)
            {
                return(true);
            }

            if (other.Id == Id)
            {
                return(other.GetType() == GetType());
            }

            return(false);
        }
Example #18
0
    public override bool Add(Entity ent, bool makeActive = false)
    {
        var player  = Owner as DeathmatchPlayer;
        var weapon  = ent as BaseDmWeapon;
        var notices = !player.SupressPickupNotices;

        //
        // We don't want to pick up the same weapon twice
        // But we'll take the ammo from it Winky Face
        //
        if (weapon != null && IsCarryingType(ent.GetType()))
        {
            var ammo     = weapon.AmmoClip;
            var ammoType = weapon.AmmoType;

            if (ammo > 0)
            {
                player.GiveAmmo(ammoType, ammo);

                if (notices)
                {
                    Sound.FromWorld("dm.pickup_ammo", ent.WorldPos);
                    PickupFeed.OnPickup(player, $"+{ammo} {ammoType}");
                }
            }

            ItemRespawn.Taken(ent);

            // Despawn it
            ent.Delete();
            return(false);
        }

        if (weapon != null && notices)
        {
            Sound.FromWorld("dm.pickup_weapon", ent.WorldPos);
            PickupFeed.OnPickup(player, $"{ent.ClassInfo.Title}");
        }


        ItemRespawn.Taken(ent);
        return(base.Add(ent, makeActive));
    }
Example #19
0
        protected internal void AddEntityWithDefaults(Entity e, bool clone = false, bool usePluginPipeline = false)
        {
            // Create the entity with defaults
            AddEntityDefaultAttributes(e);

            if (usePluginPipeline)
            {
                ExecutePipelineStage("Create", ProcessingStepStage.Preoperation, ProcessingStepMode.Synchronous, e);
                ExecutePipelineStage("Create", ProcessingStepStage.Postoperation, ProcessingStepMode.Synchronous, e);
            }

            // Store
            AddEntity(clone ? e.Clone(e.GetType()) : e);

            if (usePluginPipeline)
            {
                ExecutePipelineStage("Create", ProcessingStepStage.Postoperation, ProcessingStepMode.Asynchronous, e);
            }
        }
Example #20
0
        public static void Error(Exception exception, Entity entity, string info = null, ErrorLevel level = ErrorLevel.Error)
        {
            if (entity != null)
            {
                exception.Data[entity.GetType().Name] = new EntityLogData(entity);
            }
            else
            {
                exception.Data["Entity"] = "null";
            }

            if (!string.IsNullOrEmpty(info))
            {
                exception.Data["Info"] = info;
            }

            LogManager.Error(exception);
            //CaptureException(exception, Assembly.GetCallingAssembly(), level);
        }
Example #21
0
    public bool Equals(Entity <TPrimaryKey>?other)
    {
        if (other is null)
        {
            return(false);
        }

        if (ReferenceEquals(this, other))
        {
            return(true);
        }

        if (GetType() != other.GetType())
        {
            return(false);
        }

        return(Id.Equals(other.Id));
    }
        /// <summary>
        /// Get figure type of figure text and object ids of nearby text
        /// </summary>
        /// <param name="dbtFigIn"></param>
        /// <param name="dbIn"></param>
        /// <param name="transIn"></param>
        /// <returns></returns>
        private Tuple <FigType, ObjectIdCollection, ObjectId> getFigInfo(DBText dbtFigIn, Database dbIn, Transaction transIn)
        {
            ObjectIdCollection oidc       = new ObjectIdCollection();
            FigType            figType    = FigType.fig;
            DBText             topmostDBT = dbtFigIn;

            using (BlockTableRecord btr2 = transIn.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(dbIn), OpenMode.ForRead) /*acTrans.GetObject(oid2, OpenMode.ForWrite)*/ as BlockTableRecord)
            {
                foreach (ObjectId oid in btr2)
                {
                    Entity ent = transIn.GetObject(oid, OpenMode.ForRead) as Entity;

                    if (ent.GetType() == typeof(DBText))
                    {
                        DBText dbt = ent as DBText;

                        if (dbt.IsPositionInRect(dbtFigIn.Position.X - LeftOfX, dbtFigIn.Position.Y - AboveY, dbtFigIn.Position.X + RightOfX, dbtFigIn.Position.Y + BelowY /*.006*/))
                        {
                            if (dbt.Position.Y > topmostDBT.Position.Y)
                            {
                                topmostDBT = dbt;
                            }

                            if (!oidc.Contains(dbt.ObjectId))
                            {
                                oidc.Add(dbt.ObjectId);
                            }

                            if (figsheetRegex.IsMatch(dbt.TextString))
                            {
                                figType = FigType.sheet;
                            }

                            if (figzoneRegex.IsMatch(dbt.TextString))
                            {
                                figType = FigType.zone;
                            }
                        }
                    }
                }
            }
            return(new Tuple <FigType, ObjectIdCollection, ObjectId>(figType, oidc, topmostDBT.Id));
        }
        //Todo: umschreiben und SQLiteParameter nutzen um sqlinjection zu verhindern
        public override int SaveEntity(Entity e)
        {
            Type   eType = e.GetType();
            string sql   = "REPLACE INTO " + eType.Name + "(";
            List <PropertyInfo> properties = eType.GetProperties().ToList().GroupBy(p => p.DeclaringType)
                                             .Reverse()
                                             .SelectMany(g => g)
                                             .ToList();

            foreach (PropertyInfo property in properties)
            {
                sql += property.Name.ToLower() + ",";
            }
            sql = sql.Substring(0, sql.Length - 1) + ") VALUES(";
            foreach (PropertyInfo property in properties)
            {
                object v = property.GetValue(e, null);

                if (null == v)
                {
                    sql += "null" + ",";
                }
                else if (v is Entity)
                {
                    sql += "'" + ((Entity)v).id + "',";
                }
                else
                {
                    sql += "'" + v.ToString() + "',";
                }
            }

            sql = sql.Substring(0, sql.Length - 1) + ");";
            query(sql);
            if (e.id == null)
            {
                return(Int32.Parse(query("SELECT id FROM " + eType.Name + " WHERE id = (SELECT MAX(id) FROM " + eType.Name + ");").Single().First()));
            }
            else
            {
                return((int)e.id);
            }
        }
Example #24
0
        public virtual IEntity GetTarget(OpenComment c)
        {
            if (strUtil.IsNullOrEmpty(c.TargetDataType))
            {
                return(null);
            }
            if (c.TargetDataId <= 0)
            {
                return(null);
            }

            Type targetType = Entity.GetType(c.TargetDataType);

            if (targetType == null)
            {
                return(null);
            }
            return(ndb.findById(targetType, c.TargetDataId));
        }
        // ===================================================================================
        //                                                                             Execute
        //                                                                             =======
        public Object Execute(Object[] args)
        {
            ConditionBean cb     = extractConditionBeanWithCheck(args);
            Entity        entity = extractEntityWithCheck(args);

            String[] argNames  = new String[] { "pmb", "entity" };
            Type[]   argTypes  = new Type[] { cb.GetType(), entity.GetType() };
            String   twoWaySql = buildQueryUpdateTwoWaySql(cb, entity);

            if (twoWaySql == null)
            {
                return(0);// No execute!
            }
            ICommandContext context = createCommandContext(twoWaySql, argNames, argTypes, args);
            InternalCommandContextHandler handler = createCommandContextHandler(context);

            handler.LoggingMessageSqlArgs = context.BindVariables;
            return(handler.Execute(args));
        }
        protected void AddEntityDefaultAttributes(Entity e)
        {
            //Validate primary key for dynamic entities
            var primaryKey = string.Format("{0}id", e.LogicalName);

            if (ProxyTypesAssembly == null &&
                !e.GetType().IsSubclassOf(typeof(Entity)) &&
                !e.Attributes.ContainsKey(primaryKey))
            {
                e[primaryKey] = e.Id;
            }

            //Add createdon, modifiedon, createdby, modifiedby properties
            if (CallerId == null)
            {
                CallerId = new EntityReference("systemuser", Guid.NewGuid()); //Create a new instance by default
            }
            if (!e.Attributes.ContainsKey("createdon"))
            {
                e["createdon"] = DateTime.UtcNow;
            }

            if (!e.Attributes.ContainsKey("modifiedon"))
            {
                e["modifiedon"] = DateTime.UtcNow;
            }

            if (!e.Attributes.ContainsKey("createdby"))
            {
                e["createdby"] = CallerId;
            }

            if (!e.Attributes.ContainsKey("modifiedby"))
            {
                e["modifiedby"] = CallerId;
            }

            if (!e.Attributes.ContainsKey("statecode"))
            {
                e["statecode"] = new OptionSetValue(0); //Active by default
            }
        }
Example #27
0
        private void parse(String strOne)
        {
            if (strUtil.IsNullOrEmpty(strOne))
            {
                return;
            }
            strOne = strOne.TrimEnd(roleSeperator);
            String[] arrItem = strOne.Split(itemSeperator);
            if (arrItem.Length != 3)
            {
                return;
            }

            String typeFullName = arrItem[0].Trim();
            Type   roleType     = Entity.GetType(typeFullName);

            if (roleType == null || !rft.IsInterface(roleType, typeof(IRole)))
            {
                return;
            }

            int roleId = cvt.ToInt(arrItem[1].Trim());

            if (roleId < 0)
            {
                return;
            }

            long[] Ids = cvt.ToLongArray(arrItem[2].Trim().Replace('_', ','));
            foreach (int intOne in Ids)
            {
                if (intOne <= 0)
                {
                    return;
                }
            }

            this.RoleType     = roleType;
            this.TypeFullName = typeFullName;
            this.RoleId       = roleId;
            this.ActionIds    = Ids;
        }
        // 处理其他没有 EntityData 的物体
        private static void EntityOnAdded(On.Monocle.Entity.orig_Added orig, Entity self, Scene scene)
        {
            orig(self, scene);

            Type type = self.GetType();

            if (!(scene is Level))
            {
                return;
            }
            if (self.IsGlobalButNotCassetteManager())
            {
                return;
            }
            if (self.HasEntityId2())
            {
                return;
            }
            if (ExcludeTypes.Contains(type))
            {
                return;
            }

            string entityIdParam = self.Position.ToString();

            if (type.IsNestedPrivate)
            {
                if (!SpecialNestedPrivateTypes.Contains(type.FullName))
                {
                    return;
                }
                entityIdParam = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
                                .Where(info => info.FieldType.IsSimple() && info.DeclaringType.IsNestedPrivate).Aggregate(
                    entityIdParam,
                    (current, fieldInfo) => current + (fieldInfo.GetValue(self)?.ToString() ?? "null"));
            }

            EntityId2 entityId2 = self.CreateEntityId2(entityIdParam);

            self.SetEntityId2(entityId2);
            self.SetStartPosition(self.Position);
        }
Example #29
0
        public void     PrintoutEmployee()
        {
            Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            //int nEmployeeCount= 0;

            //int nEmployeeDataCount;
            //Declare the tool//s we//ll use throughout...
            Database    db    = HostApplicationServices.WorkingDatabase;
            Transaction trans = db.TransactionManager.StartTransaction();             //Start the transaction.

            try
            {
                //First, get at	the	BlockTable,	and	the	ModelSpace BlockTableRecord
                BlockTable       bt  = (BlockTable)trans.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead);
                BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);
                //Now, we need to be able to print to the commandline.	Here is	an object which	will help us:

                //Now, here	is the fun part.  This is where	we iterate through ModelSpace:
                foreach (ObjectId id in btr)
                {
                    Entity ent = (Entity)trans.GetObject(id, OpenMode.ForRead, false);                     //Use it	to open	the	current	object!
                    if (ent.GetType().FullName.Equals("Autodesk.AutoCAD.DatabaseServices.BlockReference")) //We use .NET//s RTTI to establish	type.
                    {
                        ArrayList saEmployeeList = new ArrayList();                                        // We use ArrayList which can have dynamic size in C#
                        ListEmployee(id, saEmployeeList);
                        //String sEmployeeData;

                        if (saEmployeeList.Count == 4)
                        {
                            ed.WriteMessage("Employee Name:	{0}", saEmployeeList[0]);
                            ed.WriteMessage("Employee Salary: {0}", saEmployeeList[1]);
                            ed.WriteMessage("Employee Division:	{0}", saEmployeeList[2]);
                            ed.WriteMessage("Division Manager: {0}", saEmployeeList[3]);
                        }
                    }
                }
            }
            catch
            {
            }
        }
Example #30
0
        /// <summary>
        /// 克隆实体
        /// </summary>
        /// <param name="oldEnt"></param>
        /// <returns></returns>
        public bool CloneEntity(Entity oldEnt)
        {
            if (oldEnt == null)
            {
                return(false);
            }
            Entity newEnt   = null;
            string TypeName = oldEnt.GetType().Name;

            switch (TypeName)
            {
            case "Polyline2d": newEnt = ClonePolyline2d((Polyline2d)oldEnt); break;

            case "DBText": newEnt = CloneDBText((DBText)oldEnt); break;

            case "BlockReference": newEnt = CloneBlockReference((BlockReference)oldEnt); break;

            case "Circle": newEnt = CloneCircle((Circle)oldEnt); break;

            case "Hatch": newEnt = CloneHatch((Hatch)oldEnt); break;

            case "DBPoint": newEnt = CloneDBPoint((DBPoint)oldEnt); break;

            case "Arc": newEnt = CloneArc((Arc)oldEnt); break;

            case "Wipeout": newEnt = CloneWipeout((Wipeout)oldEnt); break;
            }
            if (newEnt == null)
            {
                Logger.log("CloneEntity", string.Format("未处理的实体类型:【{0}】,或处理时出错!", TypeName));
                return(false);
            }
            else
            {
                newEnt.Color      = oldEnt.Color;      //颜色
                newEnt.LineWeight = oldEnt.LineWeight; //线宽
                newEnt.LayerId    = dwgHelper.LayerMgr.FindOrCloneLayer(oldEnt.LayerId);
                btRecord.AppendEntity(newEnt);
                Trans.AddNewlyCreatedDBObject(newEnt, true);
                return(true);
            }
        }
Example #31
0
        /// <summary>
        /// Renders the specified writer.
        /// </summary>
        /// <param name="badge">The badge.</param>
        /// <param name="writer">The writer.</param>
        public override void Render(BadgeCache badge, System.Web.UI.HtmlTextWriter writer)
        {
            var displayText = GetAttributeValue(badge, "DisplayText");

            if (Entity != null)
            {
                var mergeValues = new Dictionary <string, object>();

                // Always add Entity as a merge field so that lava badges that aren't tied to a particular model can have consistency
                mergeValues.Add("Entity", Entity);

                // Add a merge field by the model's name (Group, Person, FinancialAccount, etc)
                var modelTypeName = Entity.GetType()?.BaseType?.Name;
                if (!modelTypeName.IsNullOrWhiteSpace())
                {
                    mergeValues.Add(modelTypeName, Entity);
                }

                // Continue to provide the person merge field since this was originally a person badge and the lava would need to be updated to not break
                if (modelTypeName != "Person")
                {
                    mergeValues.Add("Person", Person);
                }

                // Resolve the merge fields and add debug info if requested
                displayText = displayText.ResolveMergeFields(mergeValues);

                if (GetAttributeValue(badge, "EnableDebug").AsBoolean())
                {
                    displayText +=
                        $@"<small><a data-toggle='collapse' data-parent='#accordion' href='#badge-debug'><i class='fa fa-eye'></i></a></small>
    <div id='badge-debug' class='collapse well badge-debug'>
        {mergeValues.lavaDebugInfo()}
    </div>";
                }
            }

            if (!displayText.IsNullOrWhiteSpace())
            {
                writer.Write(displayText);
            }
        }
Example #32
0
        public bool DuplicationChecking(Entity entity, string name)
        {
            var example = Activator.CreateInstance(entity.GetType()).As <TermStyle>();

            example.Name = name;
            var count = _termStyleRepository.Count(example);

            if (entity.IsNew())
            {
                return(0 < count);
            }
            else
            {
                if (entity.Name == name && 1 == count)
                {
                    return(false);
                }
                return(0 < count);
            }
        }
Example #33
0
        ////////////////

        public static string GetQualifiedName(Entity ent)
        {
            if (ent is Item)
            {
                return(ItemIdentityHelpers.GetQualifiedName((Item)ent));
            }
            if (ent is NPC)
            {
                return(NPCIdentityHelpers.GetQualifiedName((NPC)ent));
            }
            if (ent is Projectile)
            {
                return(ProjectileIdentityHelpers.GetQualifiedName((Projectile)ent));
            }
            if (ent is Player)
            {
                return(((Player)ent).name);
            }
            return("...a " + ent.GetType().Name);
        }
Example #34
0
        public void TestLinqCount()
        {
            var collection = LegacyTestConfiguration.GetCollection<Entity>();
            if (collection.Exists()) { collection.Drop(); }

            for (int i = 0; i < 100; ++i)
            {
                var e = new Entity() { Name = "Name_" + i };
                collection.Insert(e.GetType(), e, WriteConcern.Acknowledged);
            }

#pragma warning disable 429 // unreachable code
            var query = (from e in collection.AsQueryable<Entity>()
                         where true || e.Name == "Name_22"
                         select e);
#pragma warning restore
            var count = query.Count();

            Assert.Equal(100, count);
        }
Example #35
0
 public override bool CanShootEntity(Entity e)
 {
     System.Type entityType = e.GetType();
     if (entityType == typeof(PlayerControl))
     {
         // return reactions[PlayerControl] == HOSTILE
         return false;
     }
     else if (entityType == typeof(Enemy))
     {
         // return reactions[PlayerControl] == HOSTILE
         return true;
     }
     else if (entityType == typeof(NPC))
     {
         // return reactions[PlayerControl] == HOSTILE
         return false;
     }
     return false;
 }
Example #36
0
 override public bool CanShootEntity(Entity e)
 {
     System.Type entityType = e.GetType();
     if (entityType == typeof(PlayerControl))
     {
         // return reactions[PlayerControl] == HOSTILE
         return(false);
     }
     else if (entityType == typeof(Enemy))
     {
         // return reactions[PlayerControl] == HOSTILE
         return(true);
     }
     else if (entityType == typeof(NPC))
     {
         // return reactions[PlayerControl] == HOSTILE
         return(false);
     }
     return(false);
 }
Example #37
0
        public async ETTask Handle(Entity entity, object actorMessage, Action <IActorResponse> reply)
        {
            Message msg = actorMessage as Message;

            if (msg == null)
            {
                Log.Error($"消息类型转换错误: {actorMessage.GetType().FullName} to {typeof (Message).Name}");
                return;
            }

            E e = entity as E;

            if (e == null)
            {
                Log.Error($"Actor类型转换错误: {entity.GetType().Name} to {typeof (E).Name} --{typeof (Message).Name}");
                return;
            }

            await this.Run(e, msg);
        }
Example #38
0
        protected TLookup GetLookup <TLookup>([CallerMemberName] string propertyName = null)
            where TLookup : class
        {
            //если свойство уже добавлено в словарь
            if (_complexProperties.ContainsKey(propertyName))
            {
                return((TLookup)_complexProperties[propertyName]);
            }

            var value = Entity.GetType().GetProperty(propertyName).GetValue(Entity);

            if (value == null)
            {
                return(null);
            }
            var lookup = (TLookup)Activator.CreateInstance(typeof(TLookup), value);

            _complexProperties.Add(propertyName, lookup);
            return(lookup);
        }
Example #39
0
 public void Update(Entity entity)
 {
     log.DebugFormat("{0} #{1} updated.", entity.GetType(), entity.Id);
 }
Example #40
0
 public void Insert(Entity entity)
 {
     log.DebugFormat("{0} #{1} inserted.", entity.GetType(), entity.Id);
 }
Example #41
0
 public void Delete(Entity entity)
 {
     log.DebugFormat("{0} #{1} deleted.", entity.GetType(), entity.Id);
 }
Example #42
0
 public static void SetIdOf(Entity entity, int id)
 {
     PropertyInfo idProperty = entity.GetType().GetProperty("Id",
       BindingFlags.Public | BindingFlags.Instance);
       idProperty.SetValue(entity, id, null);
 }
Example #43
0
        protected override void MarkEntityAsDeleted(Entity entity)
        {
            AttachIfNeeded(entity);

            _dbContext.Set(entity.GetType()).Remove(entity);
        }
Example #44
0
 private void AttachIfNeeded(Entity entity)
 {
     if (_dbContext.Entry(entity).State == EntityState.Detached)
         _dbContext.Set(entity.GetType()).Attach(entity);
 }
Example #45
0
	public void setInitialEntity(Entity entity) {
        removeEntity();
        entity.transform.parent = this.transform.parent;
        entity.transform.position = transform.position;
		this.entityPresent = entity;
		entity.setCurrentTile (this);
        if (entity.GetType() != typeof(Obstacle))
        {
            int type = (entity.getIsPlayer() ? 0 : 1);
            graphicTile = GetComponent<GraphicTile>();
            graphicTile.setAnim();
            setTileType(type);
        }
    }
Example #46
0
        public virtual void Populate(FieldMap fieldMap, Entity entity)
        {
            var fieldsWithNoValueOnEntity = new List<string>();

            var @class = new Class(GetType());
            @class.EachField(delegate(FieldInfo fieldInfo)
                                 {
                                     var uiItem = fieldInfo.GetValue(this) as UIItem;
                                     if (uiItem == null || !ControlDictionary.Instance.IsEditable(uiItem)) return;

                                     string fieldName = fieldMap.GetFieldNameFor(fieldInfo.Name, fieldInfo.FieldType);
                                     if (string.IsNullOrEmpty(fieldName)) return;

                                     try
                                     {
                                         EntityField entityField = entity.Field(fieldName);
                                         if (entityField == null)
                                             fieldsWithNoValueOnEntity.Add(fieldName);
                                         else
                                             entityField.SetValueOn(uiItem);
                                     }
                                     catch (TargetInvocationException e)
                                     {
                                         throw new AppScreenException(
                                             string.Format("Error assigning {0}.{1} to {2}.{3} ", entity.GetType(), fieldName, GetType(), fieldInfo.Name),
                                             e.InnerException);
                                     }
                                 });

            if (fieldsWithNoValueOnEntity.Count == 0) return;

            string message = string.Join(",", fieldsWithNoValueOnEntity.ToArray());
            WhiteLogger.Instance.WarnFormat("Mapping to screen: {0} with {1}, No value specified for fields {2}", this, entity.GetType(), message);
        }
Example #47
0
 private void UpdateEntityDetails(Entity entity)
 {
     this.updateMethods[entity.GetType()](entity);
 }