Ejemplo n.º 1
0
        /// <summary>
        /// Initiates a new AnnotatedChildEntity instance that uses the provided {@code entityModel} to delegate command
        /// and event handling to an annotated child entity.
        /// </summary>
        /// <param name="entityModel">A {@link EntityModel} describing the entity.</param>
        /// <param name="forwardCommands">Flag indicating whether commands should be forwarded to the entity.</param>
        /// <param name="commandTargetResolver">Resolver for command handler methods on the target.</param>
        /// <param name="eventTargetResolver">Resolver for event handler methods on the target.</param>
        public AnnotatedChildEntity(
            IEntityModel <TChild> entityModel,
            bool forwardCommands,
            Func <ICommandMessage <object>, TParent, TChild> commandTargetResolver,
            Func <IEventMessage <object>, TParent, List <TChild> > eventTargetResolver
            )
        {
            _entityModel         = entityModel;
            _eventTargetResolver = eventTargetResolver;
            _commandHandlers     = new List <IMessageHandlingMember <TParent> >();
            if (forwardCommands)
            {
                var messageHandlingMembers =
                    entityModel.CommandHandlers <TChild>()
                    .Where(eh =>
                           eh.Unwrap <ICommandMessageHandlingMember <TParent> >() !=
                           null);

                foreach (var childHandler in messageHandlingMembers)
                {
                    _commandHandlers
                    .Add(new ChildForwardingCommandMessageHandlingMember <TParent, TChild>(
                             entityModel.CommandHandlerInterceptors <TChild>(),
                             childHandler,
                             commandTargetResolver
                             )
                         );
                }
            }
        }
Ejemplo n.º 2
0
 public MarketController(IEntityModel <MarketPriceModel> marketPrices, IEntityModel <MarketOrderModel> marketOrders, IEntityModel <MarketHistoryModel> marketHistory, IEntityModel <CharacterOrdersModel> marketCharacterOrders)
 {
     _marketPrices          = marketPrices;
     _marketOrders          = marketOrders;
     _marketHistory         = marketHistory;
     _marketCharacterOrders = marketCharacterOrders;
 }
Ejemplo n.º 3
0
    private void ExecuteAction(IEntityModel model, EActionCondition action)
    {
        switch (action)
        {
        case EActionCondition.COLLECT:
            Debug.Log("COLLECT");
            model.Collect();
            break;

        case EActionCondition.SCAN:
            Debug.Log("SCAN");
            model.Scan();
            break;

        case EActionCondition.FIND_NEW_PATH:
            model.MoveTo(_currentPath[0]);
            Debug.Log("FIND_NEW_PATH");

            break;

        case EActionCondition.MOVE_FORWARD:
            Debug.Log("MOVE_FORWARD");
            model.MoveForward();
            break;

        case EActionCondition.BACK_TO_BASE:
            Debug.Log("BACK_TO_BASE");

            break;

        default:
            break;
        }
    }
Ejemplo n.º 4
0
        public int Update(IEntityModel entity)
        {
            var columns = entity.Columns.Where(x => x != entity.PrivateKey);

            StringBuilder sql = new StringBuilder();

            sql.AppendFormat("UPDATE {0}", entity.TableName);
            sql.AppendFormat(" SET {0}", string.Join(" , ", columns.Select(x => x + " = ?")));
            sql.AppendFormat(" WHERE {0} = ?", entity.PrivateKey);

            SQLiteCommand cmd = _conn.Command as SQLiteCommand;

            cmd.CommandText = sql.ToString();
            cmd.Parameters.Clear();

            object[] values = entity.GetRow();
            for (int i = 0; i < values.Length; i++)
            {
                var param = cmd.CreateParameter();
                param.Value = values[i];

                cmd.Parameters.Add(param);
            }

            var keyparam = cmd.Parameters[0];

            cmd.Parameters.Add(keyparam);
            cmd.Parameters.RemoveAt(0);

            return(cmd.ExecuteNonQuery());
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Creates a new controller of tasks.
        /// </summary>
        /// <param name="model"></param>
        /// <param name="baseFolderPath">The base folder path to put task folders.</param>
        /// <param name="taskFolderNameFormatString"></param>
        /// <param name="taskFolderNameWildcardPattern"></param>
        public AppTaskController(IEntityModel model
                                 , string baseFolderPath
                                 , string taskFolderNameFormatString    = "taskdir.{0:D7}"
                                 , string taskFolderNameWildcardPattern = "taskdir.*"
                                 )
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }
            if (String.IsNullOrEmpty(baseFolderPath))
            {
                throw new ArgumentNullException("model");
            }
            if (String.IsNullOrEmpty(taskFolderNameFormatString))
            {
                throw new ArgumentNullException("taskFolderNameFormatString");
            }
            if (String.IsNullOrEmpty(taskFolderNameWildcardPattern))
            {
                throw new ArgumentNullException("taskFolderNameWildcardPattern");
            }

            MaxConcurrentTasks = 1; // Default to sequential execution
            _model             = model;

            BaseFolderPath                = baseFolderPath;
            TaskFolderNameFormatString    = taskFolderNameFormatString;
            TaskFolderNameWildcardPattern = taskFolderNameWildcardPattern;
        }
Ejemplo n.º 6
0
 public void Initialize(PropertyInfo property, IEntityModel childEntity)
 {
     _childEntity = childEntity;
     _routingKey  = AnnotationUtils.FindAnnotationAttributes(property, typeof(AggregateMemberAttribute))
                    .Map(map => (string)map.GetValueOrDefault("routingKey"))
                    .Filter(key => !string.IsNullOrEmpty(key))
                    .OrElse(childEntity.RoutingKey);
 }
Ejemplo n.º 7
0
		static ResolveResult GetResolveResultFromEntityModel(IEntityModel entityModel)
		{
			IEntity entity = entityModel.Resolve();
			if (entity is IMember)
				return new MemberResolveResult(null, (IMember) entity);
			if (entity is ITypeDefinition)
				return new TypeResolveResult((ITypeDefinition) entity);
			return ErrorResolveResult.UnknownError;
		}
		static ResolveResult GetResolveResultFromEntityModel(IEntityModel entityModel)
		{
			IEntity entity = entityModel.Resolve();
			if (entity is IMember)
				return new MemberResolveResult(null, (IMember) entity);
			if (entity is ITypeDefinition)
				return new TypeResolveResult((ITypeDefinition) entity);
			return ErrorResolveResult.UnknownError;
		}
Ejemplo n.º 9
0
        public IResponseViewModel Convert(IEntityModel model)
        {
            var modelType = model.GetType();

            if (!Cache.ContainsKey(modelType))
            {
                Cache.Add(modelType, CreateFunc(modelType));
            }

            return((IResponseViewModel)Cache[modelType](model));
        }
Ejemplo n.º 10
0
        protected override IEntityModel ExtractChildEntityModel(IEntityModel declaringEntity, IDictionary <string, object> attributes, PropertyInfo field)
        {
            var entityType = attributes.GetValueOrDefault("type") as Type;

            if (entityType == null)
            {
                entityType = field.ResolveGenericType(1).OrElseThrow(
                    () => new AxonConfigurationException($"Unable to resolve entity type of field {field.Name}. Please provide type explicitly in @AggregateMember annotation."));
            }

            return(declaringEntity.ModelOf(entityType));
        }
Ejemplo n.º 11
0
        public EntityBuilderBase(IEntityModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException();
            }

            Model = model;

            _entityByXName = new Dictionary <XName, Func <XElement, EntityBase> >();

            OnRegisterKnownEntities();
        }
Ejemplo n.º 12
0
        public EntityListViewModel(IEntityModel entityModel) : base() 
        {
            _entityModel = entityModel;

            NewEntityCommand = new RelayCommand(() =>
            {
                Messenger.Default.Send<WindowNavigationArgs>(new WindowNavigationArgs()
                {
                    WindowName = "EditEntity",
                    Parameter = null
                });
            });
        }
Ejemplo n.º 13
0
        public EntityListViewModel(IEntityModel entityModel) : base()
        {
            _entityModel = entityModel;

            NewEntityCommand = new RelayCommand(() =>
            {
                Messenger.Default.Send <WindowNavigationArgs>(new WindowNavigationArgs()
                {
                    WindowName = "EditEntity",
                    Parameter  = null
                });
            });
        }
Ejemplo n.º 14
0
        public IEntityController GetController(IEntityModel model)
        {
            if (model == null)
            {
                return(null);
            }

            if (!_map.ContainsKey(model))
            {
                return(null);
            }

            return(_map[model]);
        }
 public AnnotatedChildEntity(IEntityModel entityModel, bool forwardCommands,
                             Func <ICommandMessage, object, object> commandTargetResolver,
                             Func <IEventMessage, object, IEnumerable <object> > eventTargetResolver)
 {
     _entityModel         = entityModel;
     _eventTargetResolver = eventTargetResolver;
     _commandHandlers     = new Dictionary <string, IMessageHandlingMember>();
     if (forwardCommands)
     {
         _entityModel.CommandHandlers.ForEach(kv =>
                                              _commandHandlers.Add(kv.Key,
                                                                   new ChildForwardingCommandMessageHandlingMember(entityModel.CommandHandlerInterceptors, kv.Value, commandTargetResolver)));
     }
 }
Ejemplo n.º 16
0
        private IProperty <Object> ExtractCommandHandlerRoutingKey(IEntityModel childEntityModel,
                                                                   ICommandMessageHandlingMember commandHandler,
                                                                   PropertyInfo field)
        {
            var routingKey = commandHandler.RoutingKey.GetOrDefault(childEntityModel.RoutingKey);

            var property = GetProperty <object>(commandHandler.PayloadType, routingKey);

            if (property == null)
            {
                throw new AxonConfigurationException(
                          $"Command of type {commandHandler.PayloadType} doesn't have a property matching the routing key {routingKey} necessary to route through field {field}");
            }
            return(property);
        }
Ejemplo n.º 17
0
        public EditEntityViewModel(IEntityModel entityModel) : base()
        {
            _entityModel = entityModel;

            SaveEntityCommand = new RelayCommand(() =>
            {
                //_entityModel.SaveEntity(this.Entity);

                Messenger.Default.Send <WindowNavigationArgs>(new WindowNavigationArgs()
                {
                    WindowName = "EntitiesList",
                    Parameter  = null
                });
            });
        }
Ejemplo n.º 18
0
        public EditEntityViewModel(IEntityModel entityModel) : base() 
        {
            _entityModel = entityModel;

            SaveEntityCommand = new RelayCommand(() =>
            {
                //_entityModel.SaveEntity(this.Entity);

                Messenger.Default.Send<WindowNavigationArgs>(new WindowNavigationArgs()
                {
                    WindowName = "EntitiesList",
                    Parameter = null
                });
            });
        }
Ejemplo n.º 19
0
        public void EntityFired(IEntityModel model)
        {
            if (FieldModel.BonusEntities.Contains(model))
            {
                FieldModel.BonusEntities.Remove(model);
                var entityController = MapperService.GetController(model);
                entityController.SetBonus(false);
            }

            if (isFiring)
            {
                return;
            }

            isFiring = true;

            var hasBonus = false;

            var bonusEntitiesSnapshot = FieldModel.BonusEntities.ToList();

            foreach (var fieldModelBonusEntity in bonusEntitiesSnapshot)
            {
                var firedEntityPosition = FieldDimensionModel.GetFieldPositionFromWorld(model.WorldPosition);
                var position            = FieldDimensionModel.GetFieldPositionFromWorld(fieldModelBonusEntity.WorldPosition);
                if ((position + new Vector2Int(0, 1)) != firedEntityPosition)
                {
                    continue;
                }

                hasBonus = true;
            }

            if (hasBonus)
            {
                var bottomRow = FieldModel.GetRow(0).ToList();

                MessageSender.Send(new ActivateBonusMessage {
                    FiredEntitiesByBonus = bottomRow
                });

                foreach (var fireEntity in bottomRow)
                {
                    FieldController.FireEntity(fireEntity);
                }
            }

            isFiring = false;
        }
Ejemplo n.º 20
0
        public void AssignEntityBonus(IEntityModel model)
        {
            if (FieldModel.BonusEntities.Contains(model))
            {
                return;
            }

            FieldModel.BonusEntities.Add(model);
            var entityController = MapperService.GetController(model);

            entityController.SetBonus(true);

            MessageSender.Send(new AssignEntityBonusMessage {
                EntityModel = model
            });
        }
Ejemplo n.º 21
0
        public void FireEntity(IEntityModel entity)
        {
            var controller = EntityMapperService.GetController(entity);

            if (controller == null)
            {
                return;
            }

            controller.Fire();

            MessageSender.Send(new EntityFireMessage {
                Entity = entity
            });
            FieldModel.Entities.Remove(entity);
            EntityMapperService.Remove(entity);
        }
Ejemplo n.º 22
0
        private IForwardingMode InstantiateForwardingMode(PropertyInfo field,
                                                          IEntityModel childEntityModel,
                                                          Type forwardingModeClass)
        {
            IForwardingMode forwardingMode;

            try
            {
                forwardingMode = (IForwardingMode)Activator.CreateInstance(forwardingModeClass);
                forwardingMode.Initialize(field, childEntityModel);
            }
            catch (Exception ex) when(ex is MissingMethodException)
            {
                throw new AxonConfigurationException($"Failed to instantiate ForwardingMode of type {forwardingModeClass}.");
            }

            return(forwardingMode);
        }
Ejemplo n.º 23
0
        public IEntityModel[,] GenerateEntityMap()
        {
            var map       = new IEntityModel[FieldDimension.Colls, FieldDimension.Rows];
            var dimension = GetMapDimensions(map);

            foreach (var entityController in Entities)
            {
                var fieldPosition = FieldDimension.GetFieldPositionFromWorld(entityController.WorldPosition);
                if (!IsPointInField(fieldPosition, dimension))
                {
                    throw new Exception("Сущность находится вне игрового поля");
                }

                map[fieldPosition.x, fieldPosition.y] = entityController;
            }

            return(map);
        }
Ejemplo n.º 24
0
        private TypedRelations GetGenericRelations(RelationType relationType, Entity entity)
        {
            Expression <Func <Relation, bool> > relationSelector = r => r.SubjectiveEntityId == entity.Id;

            if (relationType.IsSymmetric)
            {
                relationSelector = r => r.SubjectiveEntityId == entity.Id || r.ObjectiveEntityId == entity.Id;
            }
            else if (relationType.IsInverse)
            {
                relationSelector = r => r.ObjectiveEntityId == entity.Id;
            }

            // The relationType.Id may be nagative in case of inverse relations, but it is positive in the database.
            IQueryable <Relation> relationsQuery = Db.Relations.Where(r => r.RelationTypeId == Math.Abs(relationType.Id));

            relationsQuery = relationsQuery.Where(relationSelector);

            // Retrieve all the relations and store them into the helper structure.
            Dictionary <long, List <Relation> > relationsByRelatedEntityIds = new Dictionary <long, List <Relation> > ();

            foreach (Relation relation in relationsQuery)
            {
                long relatedEntityId = relation.SubjectiveEntityId == entity.Id ? relation.ObjectiveEntityId : relation.SubjectiveEntityId;
                if (!relationsByRelatedEntityIds.ContainsKey(relatedEntityId))
                {
                    relationsByRelatedEntityIds[relatedEntityId] = new List <Relation> ();
                }
                relationsByRelatedEntityIds[relatedEntityId].Add(relation);
            }

            TypedRelations genericRelations = new TypedRelations(relationType);
            IEntityModel   entityModel      = RemoteFacade.Instance.GetEntityModel(relationType.ObjectiveEntityType, Db);

            foreach (Entity relatedEntity in entityModel.GetEntitiesByIds(relationsByRelatedEntityIds.Keys))
            {
                foreach (Relation relation in relationsByRelatedEntityIds[relatedEntity.Id])
                {
                    genericRelations.Relations[relation] = relatedEntity;
                }
            }
            return(genericRelations);
        }
Ejemplo n.º 25
0
        public static string ToJson(this IEntityModel entity, JsonSerializerSettings settings = null, [CallerMemberName] string callername = "", [CallerFilePath] string filename = "")
        {
#if DEBUG
            var str = JsonConvert.SerializeObject(entity, Formatting.Indented, settings);

            if (!string.IsNullOrEmpty(callername))
            {
                Debug.WriteLine("{1} in {3}:{0}{2}", Environment.NewLine, callername, str, filename);
            }
            else
            {
                Debug.WriteLine(str);
            }
#else
            var str = JsonConvert.SerializeObject(entity, settings);
#endif

            return(str);
        }
Ejemplo n.º 26
0
        public int Delete(IEntityModel entity)
        {
            StringBuilder sql = new StringBuilder();

            sql.AppendFormat("DELETE FROM {0}", entity.TableName);
            sql.AppendFormat(" WHERE {0} = ?", entity.PrivateKey);

            SQLiteCommand cmd = _conn.Command as SQLiteCommand;

            cmd.CommandText = sql.ToString();
            cmd.Parameters.Clear();

            var param = cmd.CreateParameter();

            param.Value = entity.Id.ToByteArray();

            cmd.Parameters.Add(param);

            return(cmd.ExecuteNonQuery());
        }
Ejemplo n.º 27
0
        private void initTreeNode(Dictionary <int, BaseEntity> entitiesDictionary)
        {
            //Поиск родительской сущности, которая содержит остальные сущности геометрии
            foreach (var item in entitiesDictionary)
            {
                //В качестве родительской выбрана сущность ADVANCED_BREP_SHAPE_REPRESENTATION
                if (item.Value.Name.Equals(AdvancedBrepShapeRepresentation.NAME))
                {
                    //Если название такой сущности найдено, то от этого узла начинаем инициализировать все сущности
                    mRootEntityABSR = new AdvancedBrepShapeRepresentation();
                    //Присвоение имени(title) сущности
                    mRootEntityABSR.Name = item.Value.ParsedParams[0][0].value;
                    //Инициализация вложенных параметров
                    mRootEntityABSR.Items = new List <RepresentationItem>(item.Value.ParsedParams[1].Count);

                    //Инициализация корневого узла дерева
                    mRootTreeNode = new TreeNode(mRootEntityABSR.StepName);
                    //Инициализация узла списка вложенных параметров (сущностей)
                    TreeNode paramsNode = new TreeNode("Items");
                    mRootTreeNode.Nodes.Add(paramsNode);

                    if (mCallback != null)
                    {
                        mCallback.extractionStep(70);
                    }

                    //Примерное условное вычисление прогресса
                    int step = 30 / entitiesDictionary.Count;
                    progressStep    = step < 30 ? step : entitiesDictionary.Count / 30;
                    currentProgress = 70;

                    //Запуск рекурсивной инициализации сущностей для каждого вложенного параметра родительской сущности
                    foreach (var itemParam in item.Value.ParsedParams[1])
                    {
                        IEntityModel param = parseItemParam(itemParam, entitiesDictionary, paramsNode);
                        mRootEntityABSR.Items.Add((RepresentationItem)param);
                    }
                }
            }
        }
Ejemplo n.º 28
0
        public Optional <IChildEntity> CreateChildDefinition(PropertyInfo field, IEntityModel declaringEntity)
        {
            var attributes = FindAnnotationAttributes(field, typeof(AggregateMemberAttribute)).OrElse(null);

            if (attributes == null || !IsFieldTypeSupported(field))
            {
                return(Optional <IChildEntity> .Empty);
            }

            var childEntityModel = ExtractChildEntityModel(declaringEntity, attributes, field);

            var eventForwardingMode = InstantiateForwardingMode(
                field, childEntityModel, (Type)attributes["eventForwardingMode"]
                );

            return(Optional <IChildEntity> .Of(new AnnotatedChildEntity(
                                                   childEntityModel,
                                                   (bool)attributes["forwardCommands"],
                                                   (msg, parent) => ResolveCommandTarget(msg, parent, field, childEntityModel),
                                                   (msg, parent) => ResolveEventTargets(msg, parent, field, eventForwardingMode)
                                                   )));
        }
Ejemplo n.º 29
0
        public IRelationalCommand Build <TEntity>(SqlStatementKind statementKind, IEntityModel model, TEntity entity, IEntityMapping entityMapping)
        {
            switch (statementKind)
            {
            case SqlStatementKind.CreateTable:

                ISqlStatementBuilder <CreateTableStatement> statementBuilder = new CreateTableStatementBuilder(model, entityMapping);

                ISqlStatement statement = statementBuilder.BuildStatement();

                return(new RelationalCommand(statement.GetText(), null));

            case SqlStatementKind.Insert:

                ISqlStatementBuilder <InsertStatement> insertStatementBuilder = new InsertStatementBuilder(entity, entityMapping);
                InsertStatement insertStatement = insertStatementBuilder.BuildStatement();

                return(new RelationalCommand(insertStatement.GetText(), insertStatement.Parameters));

            case SqlStatementKind.Update:

                ISqlStatementBuilder <UpdateStatement> updateStatementBuilder = new UpdateStatementBuilder(entity, entityMapping);
                UpdateStatement updateStatement = updateStatementBuilder.BuildStatement();

                return(new RelationalCommand(updateStatement.GetText(), updateStatement.Parameters));

            case SqlStatementKind.Delete:

                ISqlStatementBuilder <DeleteStatement> deleteStatementBuilder = new DeleteStatementBuilder(entity, entityMapping);
                DeleteStatement deleteStatement = deleteStatementBuilder.BuildStatement();

                return(new RelationalCommand(deleteStatement.GetText(), deleteStatement.Parameters));

            default:

                throw new NotImplementedException();
            }
        }
Ejemplo n.º 30
0
        public int Insert(IEntityModel entity)
        {
            StringBuilder sql = new StringBuilder();

            sql.AppendFormat("INSERT INTO {0}", entity.TableName);
            sql.AppendFormat(" VALUES ( {0} )", string.Join(" , ", entity.Columns.Select(x => "?")));

            SQLiteCommand cmd = _conn.Command as SQLiteCommand;

            cmd.CommandText = sql.ToString();
            cmd.Parameters.Clear();

            object[] values = entity.GetRow();
            for (int i = 0; i < values.Length; i++)
            {
                var param = cmd.CreateParameter();
                param.Value = values[i];

                cmd.Parameters.Add(param);
            }

            return(cmd.ExecuteNonQuery());
        }
Ejemplo n.º 31
0
        public IEnumerable <Entity> GetRelatableEntities(long relationTypeId, Entity entity, string needle)
        {
            RelationType relationType = GetRelationType(relationTypeId, entity);

            if (relationType == null)
            {
                return(Enumerable.Empty <Entity> ());
            }

            // Reflexive relations aren't supported so the entity id is initially added to the unrelatable entity ids.
            List <long> unrelatableEntityIds = new List <long> (new long[] { entity.Id });

            PredefinedRelationType predefinedRelationType = relationType as PredefinedRelationType;

            if (predefinedRelationType != null)
            {
                unrelatableEntityIds.AddRange(predefinedRelationType.GetRelatedEntities(entity).Select <Entity, long> (e => e.Id));
            }

            // Return the entities that are not unrelatable.
            IEntityModel entityModel = RemoteFacade.Instance.GetEntityModel(relationType.ObjectiveEntityType, Db);

            return(entityModel.GetEntitiesByIdsAndNeedle(unrelatableEntityIds, needle));
        }
Ejemplo n.º 32
0
 /// <summary>
 /// Конструктор класса AddDepartmentViewModel.
 /// </summary>
 /// <param name="departmentModel">Модель Отделение</param>
 public AddDepartmentViewModel(IEntityModel departmentModel)
 {
     deptModel     = departmentModel;
     insertCommand = new InsertCommand(this);
 }
Ejemplo n.º 33
0
 public int Delete(IEntityModel entity)
 {
     return(_conn.Delete(entity));
 }
Ejemplo n.º 34
0
		protected CodeElementsList<CodeAttribute2> GetAttributes(IEntityModel entityModel)
		{
			var list = new CodeElementsList<CodeAttribute2>();
			var td = entityModel.Resolve();
			if (td != null) {
				foreach (var attr in td.Attributes) {
					if (IsInFilter(attr.Region))
						list.Add(new CodeAttribute2(context, attr));
				}
			}
			return list;
		}
Ejemplo n.º 35
0
		internal static ProjectItem FindByEntity(IProject project, IEntityModel entity)
		{
			throw new NotImplementedException();
		}