Esempio n. 1
0
        /// <inheritdoc />
        protected override async Task <Result <Unit, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            var script = await Script.Run(stateMonad, cancellationToken).Map(x => x.GetStringAsync());

            if (script.IsFailure)
            {
                return(script.ConvertFailure <Unit>());
            }

            Entity?vars = null;

            if (Variables != null)
            {
                var variables = await Variables.Run(stateMonad, cancellationToken);

                if (variables.IsFailure)
                {
                    return(variables.ConvertFailure <Unit>());
                }

                vars = variables.Value;
            }

            await PwshRunner.RunScript(script.Value, stateMonad.Logger, vars);

            return(Unit.Default);
        }
Esempio n. 2
0
        public void EntitiesNode_creates_EntityNodeValue_with_tags_attached()
        {
            // ARRANGE

            var tag = DefaultTag();

            this.ProviderContextMock
            .Setup(c => c.Persistence)
            .Returns(this.PersistenceMock.Object);

            this.ProviderContextMock
            .Setup(c => c.DynamicParameters)
            .Returns(new EntitiesNode.NewItemParametersDefinition
            {
                Tags = new[] { "t" }
            });

            this.PersistenceMock
            .Setup(m => m.Entities)
            .Returns(this.EntityRepositoryMock.Object);

            Entity?entity = null;

            this.EntityRepositoryMock
            .Setup(r => r.Upsert(It.Is <Entity>(t => t.Name.Equals("ee"))))
            .Callback <Entity>(e => entity = e)
            .Returns <Entity>(e => e);

            this.PersistenceMock
            .Setup(m => m.Categories)
            .Returns(this.CategoryRepositoryMock.Object);

            var rootCategory = DefaultCategory(AsRoot);

            this.CategoryRepositoryMock
            .Setup(r => r.Root())
            .Returns(rootCategory);

            this.CategoryRepositoryMock
            .Setup(r => r.FindByParentAndName(rootCategory, "ee"))
            .Returns((Category?)null);

            this.PersistenceMock
            .Setup(p => p.Tags)
            .Returns(this.TagRepositoryMock.Object);

            this.TagRepositoryMock
            .Setup(r => r.FindByName("t"))
            .Returns(tag);

            var node = new EntitiesNode();

            // ACT

            var result = node.NewItem(this.ProviderContextMock.Object, newItemName: "ee", itemTypeName: nameof(TreeStoreItemType.Entity), newItemValue: null !);

            // ASSERT

            Assert.Equal(tag, entity !.Tags.Single());
        }
Esempio n. 3
0
        private static IEnumerable <EmailMessageEntity> CreateEmailMessage(EmailTemplateEntity template, ModifiableEntity?modifiableEntity, ref IEmailModel?model, CultureInfo?cultureInfo = null)
        {
            Entity?entity = null;

            if (template.Model != null)
            {
                if (model == null)
                {
                    model = EmailModelLogic.CreateModel(template.Model, modifiableEntity);
                }
                else if (template.Model.ToType() != model.GetType())
                {
                    throw new ArgumentException("model should be a {0} instead of {1}".FormatWith(template.Model.FullClassName, model.GetType().FullName));
                }
            }
            else
            {
                entity = modifiableEntity as Entity ?? throw new InvalidOperationException("Model should be an Entity");
            }

            using (template.DisableAuthorization ? ExecutionMode.Global() : null)
            {
                var emailBuilder = new EmailMessageBuilder(template, entity, model, cultureInfo);
                return(emailBuilder.CreateEmailMessageInternal().ToList());
            }
        }
Esempio n. 4
0
        public void ExecuteInDatastore()
        {
            if (Relationship is not null)
            {
                InDatastoreLogic(Relationship);
            }
            else
            {
                /*
                 *       Parent Nullable       0 to Many
                 *  (Account)-[HAS_EXTERNAL_REF]->(ExternalReference)
                 *
                 *       0 to Many      NOT NULL
                 *  (Account)-[HAS_PARENT]-(Account)
                 *
                 * Transaction:
                 *  - Delete Account
                 *  - Delete External References
                 *  - Commit
                 */

                Entity?entity = InItem?.GetEntity();
                if (entity is not null)
                {
                    foreach (var relationship in entity.Parent.Relations)
                    {
                        InDatastoreLogic(relationship);
                    }
                }
            }
        }
    private void Update()
    {
        _hoveredEntity.Set(FindHoveredEntity());

        if (Input.GetMouseButtonDown(0) && _hoveredEntity.Get() != null)
        {
            _selectedEntity = _hoveredEntity.Get().SimEntity;
            _hoveredEntity.Set(null);
        }

        // update higlight
        if (_hoveredEntity.ClearDirty())
        {
            if (_hoveredEntity.GetPrevious())
            {
                var sprRenderer = _hoveredEntity.GetPrevious().GetComponentInChildren <SpriteRenderer>();
                if (sprRenderer)
                {
                    HighlightService.StopHighlight(sprRenderer);
                }
            }

            if (_hoveredEntity.Get())
            {
                var sprRenderer = _hoveredEntity.Get().GetComponentInChildren <SpriteRenderer>();
                if (sprRenderer)
                {
                    HighlightService.HighlightSprite(sprRenderer, _highlightSettings);
                }
            }
        }

        UpdateRangeFeedback();
    }
Esempio n. 6
0
        internal Entity(DatastoreModel parent, string name, string label, FunctionalId?functionalId, Entity?inherits)
        {
            Properties = new PropertyCollection(this);

            Parent     = parent;
            Name       = name;
            IsAbstract = false;
            IsVirtual  = false;
            Guid       = parent.GenerateGuid(name);

            Inherits = inherits;

            Parent.Labels.New(label);
            Label = Parent.Labels[label];

            if (inherits?.FunctionalId != null && functionalId != null)
            {
                throw new InvalidOperationException($"The entity '{name}' already inherited a functional id '{(inherits?.FunctionalId ?? functionalId).Prefix} ({(inherits?.FunctionalId ?? functionalId).Label})', you cannot assign another one.");
            }

            this.functionalId = functionalId;

            key        = new Lazy <Property>(delegate() { return(GetPropertiesOfBaseTypesAndSelf().SingleOrDefault(x => x.IsKey)); }, true);
            nodeType   = new Lazy <Property>(delegate() { return(GetPropertiesOfBaseTypesAndSelf().SingleOrDefault(x => x.IsNodeType)); }, true);
            rowVersion = new Lazy <Property>(delegate() { return(GetPropertiesOfBaseTypesAndSelf().SingleOrDefault(x => x.IsRowVersion)); }, true);

            Parent.SubModels["Main"].AddEntityInternal(this);
        }
Esempio n. 7
0
        void IRefactorEntity.ChangeInheritance(Entity newParentEntity)
        {
            Parent.EnsureSchemaMigration();

            Entity?originalParent = this.Inherits;

            if (originalParent != null)
            {
                bool   hasMandatoryProperty = false;
                Entity?newParent            = newParentEntity;
                while (newParent != null && newParent != originalParent)
                {
                    if (newParent.Properties.Any(prop => !prop.Nullable))
                    {
                        hasMandatoryProperty = true;
                    }

                    newParent = newParent.Inherits;
                }

                if (newParent == null)
                {
                    throw new NotSupportedException();
                }

                if (hasMandatoryProperty)
                {
                    throw new NotSupportedException();
                }
            }

            Inherits = newParentEntity;
            CheckProperties();
        }
Esempio n. 8
0
        private void VerifyFromInheritedProperties(string propertyName, bool excludeThis = false)
        {
            Entity?item = this;

            while (item != null && item.Name != "Neo4jBase")
            {
                if (excludeThis && item == this)
                {
                    item = item.Inherits;
                    continue;
                }

                if (item.Properties.Contains(propertyName))
                {
                    if (item == this)
                    {
                        throw new NotSupportedException(string.Format("Property with the name {0} already exists on Entity {1}", propertyName, item.Name));
                    }
                    else
                    {
                        throw new NotSupportedException(string.Format("Property with the name {0} already exists on base class Entity {1}", propertyName, item.Name));
                    }
                }
                item = item.Inherits;
            }
        }
        private void KeyPressedHandler(KeyPressed message)
        {
            Entity?playerEntity = World.Entities.FirstOrDefault(f => f.Has <Player>());

            if (playerEntity is null)
            {
                return;
            }

            var transform = playerEntity.Get <Transform>();
            var rigidbody = playerEntity.Get <Rigidbody>();
            var player    = playerEntity.Get <Player>();

            switch (message.Key)
            {
            case Keys.Z:
                rigidbody.Velocity -= new Vector2(0f, -1f).Rotate(transform.Rotation) * ShootImpact;
                World.Send(new SpawnBullet
                {
                    Position = transform.Position,
                    Rotation = transform.Rotation
                });
                break;

            case Keys.X when player.LasersCount > 0:
                player.LasersCount--;
                World.Send(new SpawnBullet
                {
                    BulletType = BulletType.Laser,
                    Position   = transform.Position,
                    Rotation   = transform.Rotation
                });
                break;
            }
        }
Esempio n. 10
0
        private static Relation ParseRelation(RelationDocument relationDocument, Layer layer, Graph graph)
        {
            Relation relation = new (relationDocument.id,
                                     relationDocument.name,
                                     new List <Entity>(),
                                     layer,
                                     new ());

            if (relationDocument.referenced_entities != null)
            {
                foreach (Guid refEntityGuid in relationDocument.referenced_entities)
                {
                    Entity?refEntity = graph.GetEntity(refEntityGuid);
                    if (refEntity != null)
                    {
                        relation.Entities.Add(refEntity);
                    }
                    else
                    {
                        Console.Error.WriteLine($"Could not find entity for guid: {refEntityGuid}");
                    }
                }
            }

            if (relationDocument.properties != null)
            {
                foreach (var propertyDocument in relationDocument.properties)
                {
                    var property = ParseProperty(propertyDocument);
                    relation.Properties.Add(property.Name, property);
                }
            }

            return(relation);
        }
Esempio n. 11
0
        /// <summary>
        /// Returns a list of linear children over sum
        /// where at most one term doesn't contain x, e. g.
        /// x2 + x + a + b + x
        /// =>
        /// [x2, x, a + b, x]
        /// </summary>
        internal static List <Entity>?GatherLinearChildrenOverSumAndExpand(Entity expr, Func <Entity, bool> conditionForUniqueTerms)
        {
            if (expr is not(Sumf or Minusf))
            {
                return(SmartExpandOver(expr, conditionForUniqueTerms));
            }
            var    res      = new List <Entity>();
            Entity?freeTerm = null;

            foreach (var child in Sumf.LinearChildren(expr))
            {
                if (conditionForUniqueTerms(child))
                {
                    var expanded = SmartExpandOver(child, conditionForUniqueTerms);
                    if (expanded is null)
                    {
                        return(null);
                    }
                    res.AddRange(expanded);
                }
                else
                {
                    freeTerm = freeTerm is { }
                }
            }
Esempio n. 12
0
        /// <summary>
        /// Run a powershell script
        /// </summary>
        public static async IAsyncEnumerable <PSObject> RunScriptAsync(
            string script,
            ILogger logger,
            Entity?variables = null,
            PSDataCollection <PSObject>?input = null)
        {
            using var ps = CreateRunspace(script, logger, variables);

            var output = new PSDataCollection <PSObject>();
            var buffer = new BufferBlock <PSObject>();

            output.DataAdded += (sender, ev) =>
                                ProcessData <PSObject>(sender, ev.Index, pso => buffer.Post(pso));

            var psTask = Task.Factory.FromAsync(
                ps.BeginInvoke(input, output),
                end =>
            {
                ps.EndInvoke(end);
                buffer.Complete();
            }
                );

            while (await buffer.OutputAvailableAsync())
            {
                yield return(await buffer.ReceiveAsync());
            }

            await psTask;
        }
Esempio n. 13
0
        public void Initialize(Entity e1, Entity?e2, Entity?e3, Entity?e4, Entity?e5)
        {
            FirstEntity  = e1;
            SecondEntity = e2;
            ThirdEntity  = e3;
            FourthEntity = e4;
            FifthEntity  = e5;

            if (e3.HasValue && !e2.HasValue)
            {
                throw new InvalidOperationException("There can be no gaps in used entities");
            }
            if (e4.HasValue && !e3.HasValue)
            {
                throw new InvalidOperationException("There can be no gaps in used entities");
            }
            if (e5.HasValue && !e4.HasValue)
            {
                throw new InvalidOperationException("There can be no gaps in used entities");
            }

            FirstEntity  = e1;
            SecondEntity = e2;
            ThirdEntity  = e3;
            FourthEntity = e4;
            FifthEntity  = e5;
        }
Esempio n. 14
0
        public void Add(Entity item, bool isMain)
        {
            Items.Add(item);
            if (item is EntityLiving living)
            {
                // AI を初期化する
                living.MainAi?.OnInit();
                foreach (var ai in living.CollisionAIs)
                {
                    ai.OnInit();
                }
            }

            if (item is EntityVisible visible)
            {
                // IDrawable のマッピングを行う
                drawablesMap[visible] = visible.OnSpawn();
                visible.OnUpdate(visible.Location, drawablesMap[visible]);
            }

            if (isMain)
            {
                MainEntity = item;
            }

            EntityAdded?.Invoke(this, item);
        }
        protected virtual void Remove(Transaction trans, Relationship relationship, OGM?inItem, OGM?outItem)
        {
            string cypher;
            Dictionary <string, object?> parameters = new Dictionary <string, object?>();

            if (inItem is not null)
            {
                parameters.Add("inKey", inItem !.GetKey());
            }
            if (outItem is not null)
            {
                parameters.Add("outKey", outItem !.GetKey());
            }

            Entity?inEntity  = inItem?.GetEntity();
            Entity?outEntity = outItem?.GetEntity();

            string inLabel  = (inEntity is null) ? "in" : $"in:{inEntity.Label.Name} {{ {inEntity.Key.Name}: $inKey }}";
            string outLabel = (outEntity is null) ? "out" : $"out:{outEntity.Label.Name} {{ {outEntity.Key.Name}: $outKey }}";

            cypher = $"MATCH ({inLabel})-[r:{relationship.Neo4JRelationshipType}]->({outLabel}) DELETE r";

            relationship.RaiseOnRelationDelete(trans);

            RawResult result = trans.Run(cypher, parameters);
        }
 public PoissonLocationsAsEntitiesPipelineStep(float radius, Vector2 offset, Vector2 sampleRegionSize, Entity?parent, int rejectionThreshold = 30)
 {
     _radius             = radius;
     _offset             = offset;
     _sampleRegionSize   = sampleRegionSize;
     _parent             = parent;
     _rejectionThreshold = rejectionThreshold;
 }
Esempio n. 17
0
        public Entity New(string name, string label, FunctionalId functionId, Entity?inherits = null)
        {
            Entity value = new Entity(Parent, name, label, functionId, inherits);

            collection.Add(name, value);

            return(value);
        }
Esempio n. 18
0
        public Entity New(string name, string label, string?prefix, Entity?inherits = null)
        {
            Entity value = new Entity(Parent, name, label, prefix, inherits);

            collection.Add(name, value);

            return(value);
        }
Esempio n. 19
0
        private void Reset(Entity?destroyerEntity, Direction direction)
        {
            destroyerEntity.Value.Enable();
            var destroyer = destroyerEntity.Value.Get <Destroyer>();

            destroyer.Direction = direction;
            destroyerEntity.Value.Set(destroyer);
        }
Esempio n. 20
0
 private static void WalkBaseTypes(Entity?item, Action <Entity> action)
 {
     while (item != null)
     {
         action.Invoke(item);
         item = item.Inherits;
     }
 }
Esempio n. 21
0
        private void Reset(Entity?cellEntity, Cell cell)
        {
            cellEntity.Value.Enable();
            var newCell = cellEntity.Value.Get <Cell>();

            newCell.PositionInGrid = cell.PositionInGrid;
            cellEntity.Value.Set(newCell);
        }
        private static void SetAttack(Entity entity, EntityType attackedEntityType, int attackedEntitySize, HashSet <Entity> enemiesUnderAttack, Dictionary <int, EntityAction> entityActions)
        {
            if (entityActions.ContainsKey(entity.Id))
            {
                return;
            }

            Entity?bestEnemy = null;
            var    enemies   = enemiesUnderAttack.Where(e => e.EntityType == attackedEntityType).ToList();

            foreach (var enemy in enemies)
            {
                if (bestEnemy == null ||
                    enemy.Health < bestEnemy.Value.Health)
                {
                    bestEnemy = enemy;
                }

                if (enemy.Health == bestEnemy.Value.Health &&
                    entity.Position.Distance(enemy.Position) > entity.Position.Distance(bestEnemy.Value.Position))
                {
                    bestEnemy = enemy;
                }
            }

            if (bestEnemy != null)
            {
                var attackAction = new AttackAction(bestEnemy.Value.Id, null);
                entityActions.Add(entity.Id, new EntityAction(null, null, attackAction, null));

                var newEnemyEntity = bestEnemy.Value.Health > 5
                    ? new Entity
                {
                    Active     = bestEnemy.Value.Active,
                    EntityType = bestEnemy.Value.EntityType,
                    Health     = bestEnemy.Value.Health - 5,
                    Id         = bestEnemy.Value.Id,
                    Position   = bestEnemy.Value.Position,
                    PlayerId   = bestEnemy.Value.PlayerId
                }
                    : (Entity?)null;

                if (attackedEntitySize > 1)
                {
                    for (int y = 0; y < attackedEntitySize; y++)
                    {
                        for (int x = 0; x < attackedEntitySize; x++)
                        {
                            ScoreMap.Set(bestEnemy.Value.Position.X + x, bestEnemy.Value.Position.Y + y, newEnemyEntity);
                        }
                    }
                }
                else
                {
                    ScoreMap.Set(bestEnemy.Value.Position, newEnemyEntity);
                }
            }
        }
Esempio n. 23
0
        public static bool PassableInFuture(int x, int y)
        {
            Entity?entity = Map[x, y].Entity;

            return(entity == null ||
                   entity.Value.EntityType == EntityType.BuilderUnit ||
                   entity.Value.EntityType == EntityType.MeleeUnit ||
                   entity.Value.EntityType == EntityType.RangedUnit);
        }
Esempio n. 24
0
        public void LinkTo(EntitySetBuilder builder)
        {
            Entity?entity = builder.AsSet().First();

            if (entity != null)
            {
                LinkTo((Entity)entity);
            }
        }
Esempio n. 25
0
 internal HighlevelMove(State state, Entity moveThis, Point toHere, Entity?usingThisAgent, Point?agentFinalPos, Point?uTurnPos)
 {
     this.CurrentState   = state;
     this.MoveThis       = moveThis;
     this.ToHere         = toHere;
     this.UsingThisAgent = usingThisAgent;
     this.AgentFinalPos  = agentFinalPos;
     this.UTurnPos       = uTurnPos;
 }
Esempio n. 26
0
        private void PlaceDestroyer(Entity?destroyerEntity, Point spawnPositionInGrid, Transform parent)
        {
            var destroyerTransform = new Transform();

            destroyerTransform.Parent        = parent;
            destroyerTransform.LocalPosition = spawnPositionInGrid.ToVector2() * PlayerPrefs.Get <int>("CellSize");
            destroyerTransform.Origin        = new Vector2(40, 40);
            destroyerEntity.Value.Set(destroyerTransform);
        }
Esempio n. 27
0
        /// <inheritdoc />
        protected override async Task <Result <Array <Entity>, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            var script = await Script.Run(stateMonad, cancellationToken).Map(x => x.GetStringAsync());

            if (script.IsFailure)
            {
                return(script.ConvertFailure <Array <Entity> >());
            }

            Entity?vars = null;

            if (Variables != null)
            {
                var variables = await Variables.Run(stateMonad, cancellationToken);

                if (variables.IsFailure)
                {
                    return(variables.ConvertFailure <Array <Entity> >());
                }

                vars = variables.Value;
            }

            PSDataCollection <PSObject>?input = null;

        #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
            async ValueTask <Result <Unit, IError> > AddObject(Entity x, CancellationToken ct)
            {
                input.Add(PwshRunner.PSObjectFromEntity(x));
                return(Unit.Default);
            }

        #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously

            if (Input != null)
            {
                var inputStream = await Input.Run(stateMonad, cancellationToken);

                if (inputStream.IsFailure)
                {
                    return(inputStream.ConvertFailure <Array <Entity> >());
                }

                input = new PSDataCollection <PSObject>();

                _ = inputStream.Value.ForEach(AddObject, cancellationToken)
                    .ContinueWith(_ => input.Complete(), cancellationToken);
            }

            var stream = PwshRunner.GetEntityEnumerable(script.Value, stateMonad.Logger, vars, input)
                         .ToSCLArray();

            return(stream);
        }
Esempio n. 28
0
 public WordTemplateRenderer(OpenXmlPackage document, QueryDescription queryDescription, CultureInfo culture, WordTemplateEntity template, IWordModel?model, Entity?entity, TextTemplateParser.BlockNode?fileNameBlock)
 {
     this.document         = document;
     this.culture          = culture;
     this.queryDescription = queryDescription;
     this.template         = template;
     this.entity           = entity;
     this.model            = model;
     this.fileNameBlock    = fileNameBlock;
 }
Esempio n. 29
0
        public EmailMessageBuilder(EmailTemplateEntity template, Entity?entity, IEmailModel?systemEmail)
        {
            this.template = template;
            this.entity   = entity;
            this.model    = systemEmail;

            this.queryName  = QueryLogic.ToQueryName(template.Query.Key);
            this.qd         = QueryLogic.Queries.QueryDescription(queryName);
            this.smtpConfig = EmailTemplateLogic.GetSmtpConfiguration?.Invoke(template, (systemEmail?.UntypedEntity as Entity ?? entity)?.ToLite());
        }
Esempio n. 30
0
        private MeshCollider.Collision MapCollision(Collision collision)
        {
            Entity?e = null;

            if (ApiProviderData.GameObjects.TryGetValue(collision.collider.transform.gameObject, out Entity otherE))
            {
                e = otherE;
            }
            return(new MeshCollider.Collision(collision.impulse.Map(), collision.relativeVelocity.Map(), e));
        }