示例#1
0
        public override async Task <Customer> Run(SOMEOBJECTWITHCUSTOMERDATA arg, CommercePipelineExecutionContext context)
        {
            var    propertiesPolicy = context.GetPolicy <CustomerPropertiesPolicy>();
            var    customer         = new Customer();
            string friendlyId       = Guid.NewGuid().ToString("N");

            customer.AccountNumber = friendlyId;
            customer.FriendlyId    = friendlyId;
            customer.Id            = $"{CommerceEntity.IdPrefix<Customer>()}{friendlyId}";

            customer.Email = arg.EmailAddress;



            //add customer to the entity index so that we can search later
            await this._persistEntityPipeline.Run(
                new PersistEntityArgument(
                    new EntityIndex
            {
                Id = $"{EntityIndex.IndexPrefix<Customer>("Id")}{customer.Id}",
                IndexKey = customer.Id,
                EntityId = customer.Id
            }),
                context);

            return(customer);
        }
示例#2
0
        /// <summary>
        /// Obtains reference information for a resource.
        /// </summary>
        /// <returns>
        /// "200 Ok" with reference info if successful.
        /// "404 Not Found" if no resource with the specified type and ID exists.
        /// </returns>
        public static IActionResult GetReferenceInfo(ResourceType type, int id, EntityIndex entityIndex, ReferencesIndex referencesIndex)
        {
            if (!entityIndex.Exists(type, id))
            {
                return(new NotFoundResult());
            }

            return(new OkObjectResult(new ReferenceInfoResult
            {
                OutgoingReferences = TransformToResult(referencesIndex.ReferencesOf(type, id)),
                IncomingReferences = TransformToResult(referencesIndex.ReferencesTo(type, id))
            }));

            IReadOnlyCollection <ReferenceInfoResult.ReferenceInfo> TransformToResult(IEnumerable <EntityId> refs)
            {
                return(refs
                       .GroupBy(entry => entry.Type)
                       .Select(group => new ReferenceInfoResult.ReferenceInfo
                {
                    Type = group.Key.Name,
                    Ids = group.Select(e => e.Id).OrderBy(i => i).ToList()
                })
                       .OrderBy(group => group.Type)
                       .ToList());
            }
        }
        public void IndexGetsLastComponentThatTriggeredAddingEntityToGroup()
        {
            _context = new MyTestContext();

            IComponent receivedComponent = null;

            _group = _context.GetGroup(Matcher <MyTestEntity> .AllOf(CID.ComponentA, CID.ComponentB));
            _index = new EntityIndex <MyTestEntity, string>("TestIndex", _group, (e, c) =>
            {
                receivedComponent = c;
                return(((NameAgeComponent)c).name);
            });

            var nameAgeComponent1 = new NameAgeComponent();

            nameAgeComponent1.name = "Max";

            var nameAgeComponent2 = new NameAgeComponent();

            nameAgeComponent2.name = "Jack";

            var entity = _context.CreateEntity();

            entity.AddComponent(CID.ComponentA, nameAgeComponent1);
            entity.AddComponent(CID.ComponentB, nameAgeComponent2);

            Assert.AreEqual(nameAgeComponent2, receivedComponent);
        }
示例#4
0
 public void DeleteEntityIndex(EntityIndex index)
 {
     foreach (var kw in index.Keywords.ToList())
     {
         EntityKeywords.Remove(kw);
     }
     //EntityIndexes.Remove(index);
 }
 public RoutesController(EventStoreService eventStore, CacheDatabaseManager db, IEnumerable <IDomainIndex> indices)
 {
     _eventStore      = eventStore;
     _db              = db;
     _mediaIndex      = indices.OfType <MediaIndex>().First();
     _entityIndex     = indices.OfType <EntityIndex>().First();
     _referencesIndex = indices.OfType <ReferencesIndex>().First();
     _ratingIndex     = indices.OfType <RatingIndex>().First();
 }
示例#6
0
        public override async Task <RenameCustomerArgument> Run(RenameCustomerArgument arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull($"{this.Name}: The argument can not be null");

            var oldCustomerIndexEntityId = $"{EntityIndex.IndexPrefix<Customer>("Id")}{arg.FromUsername}";
            var result = await Commander.DeleteEntity(context.CommerceContext, oldCustomerIndexEntityId);

            return(arg);
        }
示例#7
0
 public TagsController(EventStoreService eventStore, CacheDatabaseManager db, InMemoryCache cache)
 {
     _eventStore      = eventStore;
     _db              = db;
     _entityIndex     = cache.Index <EntityIndex>();
     _mediaIndex      = cache.Index <MediaIndex>();
     _tagIndex        = cache.Index <TagIndex>();
     _referencesIndex = cache.Index <ReferencesIndex>();
 }
示例#8
0
 public UsersController(EventStoreService eventStore, CacheDatabaseManager db, InMemoryCache cache,
                        IOptions <EndpointConfig> endpointConfig, ILogger <UsersController> logger)
 {
     _eventStore     = eventStore;
     _db             = db;
     _entityIndex    = cache.Index <EntityIndex>();
     _userIndex      = cache.Index <UserIndex>();
     _endpointConfig = endpointConfig.Value;
     _logger         = logger;
 }
 public void Setup0()
 {
     Pool  = new Pool <ITestSecondPool>(new NameTestComponent(), new IdTestComponent());
     Group = Pool.GetGroup(Matcher.AllOf(typeof(NameTestComponent)));
     Index = new EntityIndex <ITestSecondPool, string>(Group, (e, c) =>
     {
         var name = c as NameTestComponent;
         return(name != null
             ? name.Name
             : e.Get <NameTestComponent>().Name);
     });
 }
        public void has_existing_entity()
        {
            var newIndex = new EntityIndex <ITestSecondPool, string>(Group, (e, c) => {
                var nameAge = c as NameTestComponent;
                return(nameAge != null
                        ? nameAge.Name
                        : e.Get <NameTestComponent>().Name);
            });

            Assert.IsTrue(newIndex.HasEntities(Key));
            Assert.AreEqual(2, newIndex.GetEntities(Key).Count);
        }
示例#11
0
        /// <summary>
        /// Runs the specified argument.
        /// </summary>
        /// <param name="arg">The argument.</param>
        /// <param name="context">The context.</param>
        /// <returns>the Customer entity</returns>
        public override async Task <Customer> Run(Customer arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull($"{this.Name} The customer can not be null");

            var upgradePolicy = context.CommerceContext.GetPolicy <CustomersUpgradePolicy>();

            arg.UserName = string.Concat(upgradePolicy?.CustomersDomain, "\\", arg.Email);

            await this._deleteEntityPipeline.Run(new DeleteEntityArgument($"{EntityIndex.IndexPrefix<Customer>("Id")}{arg.Email}"), context).ConfigureAwait(false);

            return(arg);
        }
示例#12
0
 public MediaController(EventStoreService eventStore, CacheDatabaseManager db, InMemoryCache cache,
                        IOptions <UploadFilesConfig> uploadConfig, IOptions <EndpointConfig> endpointConfig,
                        ILogger <MediaController> logger)
 {
     _logger          = logger;
     _eventStore      = eventStore;
     _db              = db;
     _entityIndex     = cache.Index <EntityIndex>();
     _mediaIndex      = cache.Index <MediaIndex>();
     _referencesIndex = cache.Index <ReferencesIndex>();
     _uploadConfig    = uploadConfig.Value;
     _endpointConfig  = endpointConfig.Value;
 }
示例#13
0
    public UpdateUnitShooting(UnitContext unitContext)
    {
        var idx = new EntityIndex <UnitEntity, int>(
            unitContext.GetGroup(UnitMatcher.Team),
            (entity, component) => {
            var team = component as Team;
            return(team != null ? team.id : entity.team.id);
        });

        unitContext.AddEntityIndex(TARGETS_INDEX_NAME, idx);

        _units    = unitContext;
        _shooters = unitContext.GetGroup(UnitMatcher.Team);
    }
    public static void AddEntityIndices(this Contexts contexts)
    {
        var positionIndex = new EntityIndex <GameEntity, int>(
            contexts.game.GetGroup(GameMatcher.Position),
            (e, c) => {
            var positionComponent = c as PositionComponent;
            return(positionComponent != null
                    ? (positionComponent.x << shiftX) + positionComponent.y
                    : (e.position.x << shiftX) + e.position.y);
        }
            );

        contexts.game.AddEntityIndex(PositionKey, positionIndex);
    }
示例#15
0
    public static void AddEntityIndices(this Pools pools)
    {
        var positionIndex = new EntityIndex <string>(
            pools.core.GetGroup(CoreMatcher.Position),
            (e, c) => {
            var positionComponent = c as PositionComponent;
            return(positionComponent != null
                    ? positionComponent.x + "," + positionComponent.y
                    : e.position.x + "," + e.position.y);
        }
            );

        pools.core.AddEntityIndex(PositionKey, positionIndex);
    }
示例#16
0
文件: UIPool.cs 项目: pandey623/ReUI
        public UIPool() : base(RentitasUtility.CollectComponents <IUIPool>().Build())
        {
            Index = new PrimaryEntityIndex <IUIPool, Guid>(
                GetGroup(Matcher.AllOf(typeof(Element))),
                (e, c) => ((Element)c).Id);

            Children = new EntityIndex <IUIPool, Guid>(
                GetGroup(Matcher.AllOf(typeof(Parent))),
                (e, c) => ((Parent)c).Id);

            Scope = new EntityIndex <IUIPool, Guid>(
                GetGroup(Matcher.AllOf(typeof(Scope))),
                (e, c) => ((Scope)c).Id);
        }
示例#17
0
 public ExhibitPagesController(
     IOptions <ExhibitPagesConfig> exhibitPagesConfig,
     EventStoreService eventStore,
     CacheDatabaseManager db,
     InMemoryCache cache)
 {
     _exhibitPagesConfig = exhibitPagesConfig;
     _eventStore         = eventStore;
     _db               = db;
     _mediaIndex       = cache.Index <MediaIndex>();
     _entityIndex      = cache.Index <EntityIndex>();
     _referencesIndex  = cache.Index <ReferencesIndex>();
     _exhibitPageIndex = cache.Index <ExhibitPageIndex>();
 }
        public void SetupMultipleKeyEntityIndex()
        {
            _context = new MyTestContext();
            _group   = _context.GetGroup(Matcher <MyTestEntity> .AllOf(CID.ComponentA));
            _index   = new EntityIndex <MyTestEntity, string>("TestIndex", _group, (e, c) =>
            {
                return(e == _entity1
                                        ? new[] { "1", "2" }
                                        : new[] { "2", "3" });
            });

            _entity1 = _context.CreateEntity();
            _entity1.AddComponentA();
            _entity2 = _context.CreateEntity();
            _entity2.AddComponentA();
        }
示例#19
0
        public List <T> GetItemVersionsById(string entityKPID)
        {
            // get teamId from index
            EntityIndex index = this.dataAccess.GetLookupObjectByID <EntityIndex>("EntityIndex", Int32.Parse(entityKPID));
            // get team url
            Team team = this.dataAccess.Teams.Find(t => t.KPID == index.KPTeamId.Value);

            if (team == null)
            {
                throw new Exception(string.Format("Entity index lookup failed: KPID {0} not found. Endpoint pattern '/Entity/[entityName]/[entityKPID]' expected. Exception thrown at EntityRepository.GetItemById", entityKPID));
            }
            // get item from team list
            List <T> items = this.dataAccess.GetEntityObjectVersionsByKPID <T>(team.SiteUrl, this.ListName, index.ID);

            EventLogger.WriteLine("Found object");
            return(items);
        }
        public void SetupActivatedSingleKeyEntityIndex()
        {
            _context = new MyTestContext();
            _group   = _context.GetGroup(Matcher <MyTestEntity> .AllOf(CID.ComponentA));
            _index   = new EntityIndex <MyTestEntity, string>("TestIndex", _group, (e, c) =>
            {
                return(c is NameAgeComponent nameAge
                                        ? nameAge.name
                                        : ((NameAgeComponent)e.GetComponent(CID.ComponentA)).name);
            });

            _nameAgeComponent      = new NameAgeComponent();
            _nameAgeComponent.name = NAME;
            _entity1 = _context.CreateEntity();
            _entity1.AddComponent(CID.ComponentA, _nameAgeComponent);
            _entity2 = _context.CreateEntity();
            _entity2.AddComponent(CID.ComponentA, _nameAgeComponent);
        }
        public void Setup4()
        {
            GroupAll  = Pool.GetGroup(Matcher.AllOf(typeof(NameTestComponent), typeof(IdTestComponent)));
            GroupAny  = Pool.GetGroup(Matcher.AnyOf(typeof(NameTestComponent), typeof(IdTestComponent)));
            GroupNone = Pool.GetGroup(Matcher.AllOf(typeof(IdTestComponent)).NoneOf(typeof(NameTestComponent)));

            Entity3 = Pool.CreateEntity().Add <IdTestComponent>(id => id.Id = Id1);
            Entity4 = Pool.CreateEntity().Add <NameTestComponent>(n => n.Name = Key2).Add <IdTestComponent>(id => id.Id = Id2);

            IndexAll = new EntityIndex <ITestSecondPool, string>(GroupAll, (e, c) => e.Get <NameTestComponent>().Name);
            IndexAny = new EntityIndex <ITestSecondPool, string>(GroupAny, (e, c) =>
            {
                if (e.Has <NameTestComponent>())
                {
                    return(e.Get <NameTestComponent>().Name);
                }
                else
                {
                    return(e.Get <IdTestComponent>().Id.ToString());
                }
            });

            IndexNone = new EntityIndex <ITestSecondPool, int>(GroupNone, (e, c) => e.Get <IdTestComponent>().Id);
        }
        public void IndexOfMultipleComponentsWorksWithNoneOf()
        {
            _context = new MyTestContext();

            var receivedComponents = new List <IComponent>();

            var nameAgeComponent1 = new NameAgeComponent();

            nameAgeComponent1.name = "Max";

            var nameAgeComponent2 = new NameAgeComponent();

            nameAgeComponent2.name = "Jack";

            _group = _context.GetGroup(Matcher <MyTestEntity> .AllOf(CID.ComponentA).NoneOf(CID.ComponentB));
            _index = new EntityIndex <MyTestEntity, string>("TestIndex", _group, (e, c) =>
            {
                receivedComponents.Add(c);

                if (c == nameAgeComponent1)
                {
                    return(((NameAgeComponent)c).name);
                }

                return(((NameAgeComponent)e.GetComponent(CID.ComponentA)).name);
            });

            var entity = _context.CreateEntity();

            entity.AddComponent(CID.ComponentA, nameAgeComponent1);
            entity.AddComponent(CID.ComponentB, nameAgeComponent2);

            Assert.AreEqual(2, receivedComponents.Count);
            Assert.AreEqual(nameAgeComponent1, receivedComponents[0]);
            Assert.AreEqual(nameAgeComponent2, receivedComponents[1]);
        }
示例#23
0
        /// <summary>
        /// The run.
        /// </summary>
        /// <param name="arg">
        /// The argument.
        /// </param>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public override async Task <string> Run(string arg, CommercePipelineExecutionContext context)
        {
            var artifactSet = "GiftCards.TestGiftCards-1.0";

            // Check if this environment has subscribed to this Artifact Set
            if (!context.GetPolicy <EnvironmentInitializationPolicy>().InitialArtifactSets.Contains(artifactSet))
            {
                return(arg);
            }

            context.Logger.LogInformation($"{this.Name}.InitializingArtifactSet: ArtifactSet={artifactSet}");

            // Add stock gift cards for testing
            await this._persistEntityPipeline.Run(
                new PersistEntityArgument(
                    new GiftCard
            {
                Id = $"{CommerceEntity.IdPrefix<GiftCard>()}GC1000000",
                Name = "Test Gift Card ($1,000,000)",
                Balance = new Money("USD", 1000000M),
                ActivationDate = DateTimeOffset.UtcNow,
                Customer = new EntityReference {
                    EntityTarget = "DefaultCustomer"
                },
                OriginalAmount = new Money("USD", 1000000M),
                GiftCardCode = "GC1000000",
                Components = new List <Component>
                {
                    new ListMembershipsComponent {
                        Memberships = new List <string> {
                            CommerceEntity.ListName <Entitlement>(), CommerceEntity.ListName <GiftCard>()
                        }
                    }
                }
            }),
                context);

            await this._persistEntityPipeline.Run(
                new PersistEntityArgument(
                    new EntityIndex
            {
                Id = $"{EntityIndex.IndexPrefix<GiftCard>("Id")}GC1000000",
                IndexKey = "GC1000000",
                EntityId = $"{CommerceEntity.IdPrefix<GiftCard>()}GC1000000"
            }),
                context);

            await this._persistEntityPipeline.Run(
                new PersistEntityArgument(
                    new GiftCard
            {
                Id = $"{CommerceEntity.IdPrefix<GiftCard>()}GC100B",
                Name = "Test Gift Card ($100,000,000,000,000)",
                Balance = new Money("USD", 100000000000000M),
                ActivationDate = DateTimeOffset.UtcNow,
                Customer = new EntityReference {
                    EntityTarget = "DefaultCustomer"
                },
                OriginalAmount = new Money("USD", 100000000000000M),
                GiftCardCode = "GC100B",
                Components = new List <Component>
                {
                    new ListMembershipsComponent {
                        Memberships = new List <string> {
                            CommerceEntity.ListName <Entitlement>(), CommerceEntity.ListName <GiftCard>()
                        }
                    }
                }
            }),
                context);

            await this._persistEntityPipeline.Run(
                new PersistEntityArgument(
                    new EntityIndex
            {
                Id = $"{EntityIndex.IndexPrefix<GiftCard>("Id")}GC100B",
                IndexKey = "GC100B",
                EntityId = $"{CommerceEntity.IdPrefix<GiftCard>()}GC100B"
            }),
                context);

            await this._persistEntityPipeline.Run(
                new PersistEntityArgument(
                    new GiftCard
            {
                Id = $"{CommerceEntity.IdPrefix<GiftCard>()}GC100",
                Name = "Test Gift Card ($100)",
                Balance = new Money("USD", 100M),
                ActivationDate = DateTimeOffset.UtcNow,
                Customer = new EntityReference {
                    EntityTarget = "DefaultCustomer"
                },
                OriginalAmount = new Money("USD", 100M),
                GiftCardCode = "GC100",
                Components = new List <Component>
                {
                    new ListMembershipsComponent {
                        Memberships = new List <string> {
                            CommerceEntity.ListName <Entitlement>(), CommerceEntity.ListName <GiftCard>()
                        }
                    }
                }
            }),
                context);

            await this._persistEntityPipeline.Run(
                new PersistEntityArgument(
                    new EntityIndex
            {
                Id = $"{EntityIndex.IndexPrefix<GiftCard>("Id")}GC100",
                IndexKey = "GC100",
                EntityId = $"{CommerceEntity.IdPrefix<GiftCard>()}GC100"
            }),
                context);

            return(arg);
        }
 public HistoryController(EventStoreService eventStore, InMemoryCache cache)
 {
     _eventStore  = eventStore;
     _entityIndex = cache.Index <EntityIndex>();
 }
示例#25
0
        public GameEngine(string snapshotJson, string templateJson) {
            _templateJson = templateJson;

            // Create our own little island of references with its own set of templates
            GameSnapshotRestorer restorer = GameSnapshotRestorer.Restore(
                snapshotJson, templateJson, Maybe.Just(this));
            GameSnapshot snapshot = restorer.GameSnapshot;

            EntityIdGenerator = snapshot.EntityIdGenerator;

            _systems = snapshot.Systems;
            _entityIndex = new EntityIndex();

            // TODO: ensure that when correctly restore UpdateNumber
            //UpdateNumber = updateNumber;

            _globalEntity = (RuntimeEntity)snapshot.GlobalEntity;

            EventNotifier.Submit(EntityAddedEvent.Create(_globalEntity));

            foreach (var entity in snapshot.AddedEntities) {
                AddEntity((RuntimeEntity)entity);
            }

            foreach (var entity in snapshot.ActiveEntities) {
                RuntimeEntity runtimeEntity = (RuntimeEntity)entity;

                // add the entity
                InternalAddEntity(runtimeEntity);

                // TODO: verify that if the modification notifier is already triggered, we can
                // ignore this
                //if (((ContentEntity)entity).HasModification) {
                //    runtimeEntity.ModificationNotifier.Notify();
                //}

                // done via InternalAddEntity
                //if (deserializedEntity.HasStateChange) {
                //    deserializedEntity.Entity.DataStateChangeNotifier.Notify();
                //}
            }

            foreach (var entity in snapshot.RemovedEntities) {
                RuntimeEntity runtimeEntity = (RuntimeEntity)entity;

                // add the entity
                InternalAddEntity(runtimeEntity);

                // TODO: verify that if the modification notifier is already triggered, we can
                // ignore this
                //if (((ContentEntity)entity).HasModification) {
                //    runtimeEntity.ModificationNotifier.Notify();
                //}

                // done via InternalAddEntity
                //if (deserializedEntity.HasStateChange) {
                //    deserializedEntity.Entity.DataStateChangeNotifier.Notify();
                //}

                RemoveEntity(runtimeEntity);
            }

            TemplateIndex templateIndex = new TemplateIndex(restorer.Templates.Templates);

            _executionGroups = new List<ExecutionGroup>();
            var executionGroups = SystemExecutionGroup.GetExecutionGroups(snapshot.Systems);
            foreach (var executionGroup in executionGroups) {
                List<MultithreadedSystem> multithreadedSystems = new List<MultithreadedSystem>();
                foreach (var system in executionGroup.Systems) {
                    MultithreadedSystem multithreaded = CreateMultithreadedSystem(system, templateIndex);
                    multithreadedSystems.Add(multithreaded);
                }
                _executionGroups.Add(new ExecutionGroup(multithreadedSystems));
            }

            _nextState = GameEngineNextState.SynchronizeState;
            SynchronizeState().Wait();

            // call of the engine loaded systems
            foreach (var group in _executionGroups) {
                foreach (var system in group.Systems) {
                    var onLoaded = system.System as Trigger.OnEngineLoaded;
                    if (onLoaded != null) {
                        onLoaded.OnEngineLoaded(EventNotifier);

                        // TODO: verify that OnEngineLoaded didn't change any state (via hashing)
                    }
                }
            }
        }
        /// <summary>
        /// Runs the specified argument.
        /// </summary>
        /// <param name="arg">The argument.</param>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public override async Task <CommerceEntity> Run(CommerceEntity arg, CommercePipelineExecutionContext context)
        {
            if (arg == null)
            {
                return(arg);
            }

            if (!(arg is Order))
            {
                return(arg);
            }

            var migrationPolicy = context.CommerceContext?.GetPolicy <MigrationPolicy>();

            if (migrationPolicy == null)
            {
                await context.CommerceContext.AddMessage(
                    context.CommerceContext.GetPolicy <KnownResultCodes>().Error,
                    "InvalidOrMissingPropertyValue",
                    new object[] { "MigrationPolicy" },
                    $"{this.GetType()}. Missing MigrationPolicy").ConfigureAwait(false);

                return(arg);
            }

            Guid id;

            if (!Guid.TryParse(arg.Id, out id))
            {
                context.Logger.LogInformation($"{this.Name} - Invalid Order Id:{arg.Id}");
                return(arg);
            }

            arg.Id = $"{CommerceEntity.IdPrefix<Order>()}{id:N}";

            var targetOrder = await _findEntityCommand.Process(context.CommerceContext, typeof(Order), arg.Id).ConfigureAwait(false);

            if (targetOrder != null)
            {
                arg.IsPersisted = true;
                arg.Version     = targetOrder.Version;
                return(arg);
            }

            if (arg.HasComponent <ContactComponent>())
            {
                var indexByCustomerId = new EntityIndex
                {
                    Id       = $"{EntityIndex.IndexPrefix<Order>("Id")}{arg.Id}",
                    IndexKey = arg.GetComponent <ContactComponent>()?.CustomerId,
                    EntityId = arg.Id
                };

                if (!migrationPolicy.ReviewOnly)
                {
                    await this._persistEntityPipeline.Run(new PersistEntityArgument(indexByCustomerId), context).ConfigureAwait(false);
                }
            }

            var order = (Order)arg;
            var indexByConfirmationId = new EntityIndex
            {
                Id       = $"{EntityIndex.IndexPrefix<Order>("Id")}{order?.OrderConfirmationId}",
                IndexKey = order?.OrderConfirmationId,
                EntityId = arg.Id
            };

            if (!migrationPolicy.ReviewOnly)
            {
                await this._persistEntityPipeline.Run(new PersistEntityArgument(indexByConfirmationId), context).ConfigureAwait(false);
            }

            return(arg);
        }
        public override async Task <Order> Run(OfflineStoreOrderArgument arg, CommercePipelineExecutionContext context)
        {
            CreateOfflineOrderBlock createOrderBlock = this;

            Condition.Requires(arg).IsNotNull($"{createOrderBlock.Name}: arg can not be null");

            CommercePipelineExecutionContext executionContext;

            if (string.IsNullOrEmpty(arg.Email))
            {
                executionContext = context;
                executionContext.Abort(await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().Error, "EmailIsRequired", new object[1], "Can not create order, email address is required.").ConfigureAwait(false), context);
                executionContext = null;
                return(null);
            }

            if (!arg.Lines.Any())
            {
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          error           = context.GetPolicy <KnownResultCodes>().Error;
                string          commerceTermKey = "OrderHasNoLines";
                string          defaultMessage  = "Can not create order, cart  has no lines";
                executionContext.Abort(await commerceContext.AddMessage(error, commerceTermKey, null, defaultMessage).ConfigureAwait(false), context);
                executionContext = null;
                return(null);
            }

            // Find contact using email
            string           email            = arg.Email;
            ContactComponent contactComponent = new ContactComponent();
            EntityIndex      entityIndex      = await createOrderBlock._findEntityPipeline
                                                .Run(new FindEntityArgument(typeof(EntityIndex), string.Format("{0}{1}\\{2}", EntityIndex.IndexPrefix <Customer>("Id"), arg.Domain, arg.Email)), context)
                                                .ConfigureAwait(false)
                                                as EntityIndex;

            if (entityIndex != null)
            {
                var      customerEntityId = entityIndex.EntityId;
                Customer entityCustomer   = await createOrderBlock._findEntityPipeline
                                            .Run(new FindEntityArgument(typeof(Customer), customerEntityId), context)
                                            .ConfigureAwait(false)
                                            as Customer;

                if (entityCustomer != null)
                {
                    contactComponent.IsRegistered = true;
                    contactComponent.CustomerId   = entityCustomer.Id;
                    contactComponent.ShopperId    = entityCustomer.Id;
                    contactComponent.Name         = entityCustomer.Name;
                }
            }

            contactComponent.Email = email;
            KnownOrderListsPolicy policy1 = context.GetPolicy <KnownOrderListsPolicy>();
            string orderId    = string.Format("{0}{1:N}", CommerceEntity.IdPrefix <Order>(), Guid.NewGuid());
            Order  storeOrder = new Order();

            storeOrder.Components = new List <Component>();
            storeOrder.Id         = orderId;

            Totals totals = new Totals()
            {
                GrandTotal       = new Money(arg.CurrencyCode, arg.GrandTotal),
                SubTotal         = new Money(arg.CurrencyCode, arg.SubTotal),
                AdjustmentsTotal = new Money(arg.CurrencyCode, arg.Discount),
                PaymentsTotal    = new Money(arg.CurrencyCode, arg.GrandTotal)
            };

            storeOrder.Totals = totals;
            IList <CartLineComponent> lines = new List <CartLineComponent>();

            foreach (var line in arg.Lines)
            {
                var            items  = line.ItemId.Split('|');
                CommerceEntity entity = await createOrderBlock._findEntityPipeline
                                        .Run(new FindEntityArgument(typeof(SellableItem), "Entity-SellableItem-" + (items.Count() > 2 ? items[1] : line.ItemId), false), context)
                                        .ConfigureAwait(false);

                CartLineComponent lineComponent = new CartLineComponent
                {
                    ItemId   = line.ItemId,
                    Quantity = line.Quantity,
                    Totals   = new Totals()
                    {
                        SubTotal = new Money(arg.CurrencyCode, line.SubTotal), GrandTotal = new Money(arg.CurrencyCode, line.SubTotal)
                    },
                    UnitListPrice = new Money()
                    {
                        CurrencyCode = arg.CurrencyCode, Amount = line.UnitListPrice
                    },
                    Id = Guid.NewGuid().ToString("N"),
                    //Policies = new List<Policy>() //todo: determine if this is required
                };
                lineComponent.Policies.Add(new PurchaseOptionMoneyPolicy()
                {
                    PolicyId = "c24f0ed4f2f1449b8a488403b6bf368a", SellPrice = new Money()
                    {
                        CurrencyCode = arg.CurrencyCode, Amount = line.SubTotal
                    }
                });

                if (entity is SellableItem)
                {
                    SellableItem sellableItem = entity as SellableItem;
                    lineComponent.ChildComponents.Add(new CartProductComponent()
                    {
                        DisplayName = line.ProductName,
                        Id          = items.Count() > 2 ? items[1] : line.ItemId,
                        Image       = new Image()
                        {
                            ImageName  = line.ProductName,
                            AltText    = line.ProductName,
                            Height     = 50, Width = 50,
                            SitecoreId = sellableItem.GetComponent <ImagesComponent>().Images.FirstOrDefault()
                        }
                    });
                }
                // if it has a variant

                if (items.Count() > 2)
                {
                    // Set VariantionId
                    lineComponent.ChildComponents.Add(new ItemVariationSelectedComponent()
                    {
                        VariationId = items[2]
                    });
                }

                lines.Add(lineComponent);
            }

            storeOrder.Lines = lines;


            IList <AwardedAdjustment> adjustments = new List <AwardedAdjustment>();

            if (arg.Discount > 0)
            {
                var discountAdjustment = new CartLevelAwardedAdjustment
                {
                    AdjustmentType      = "Discount",
                    Adjustment          = new Money(arg.CurrencyCode, -arg.Discount),
                    IsTaxable           = false,
                    IncludeInGrandTotal = true,
                    Name          = "Discount",
                    AwardingBlock = "In Store Discount"
                };
                adjustments.Add(discountAdjustment);
            }

            if (arg.TaxTotal > 0)
            {
                var taxAdjustment = new CartLevelAwardedAdjustment
                {
                    AdjustmentType      = "Tax",
                    Adjustment          = new Money(arg.CurrencyCode, arg.TaxTotal),
                    IsTaxable           = false,
                    IncludeInGrandTotal = true,
                    Name          = "TaxFee",
                    AwardingBlock = "Tax:block:calculatecarttax"
                };
                adjustments.Add(taxAdjustment);
            }

            storeOrder.Adjustments = adjustments;

            // Payment
            FederatedPaymentComponent paymentComponent = new FederatedPaymentComponent(new Money(arg.CurrencyCode, arg.GrandTotal))
            {
                PaymentInstrumentType = arg.PaymentInstrumentType,
                CardType          = arg.CardType,
                ExpiresMonth      = arg.ExpiresMonth,
                ExpiresYear       = arg.ExpiresYear,
                TransactionId     = arg.TransactionId,
                TransactionStatus = arg.TransactionStatus,
                MaskedNumber      = arg.MaskedNumber,
                Amount            = new Money(arg.CurrencyCode, arg.GrandTotal),
                Comments          = "Store Payment",
                PaymentMethod     = new EntityReference("Card", new Guid().ToString()),
                BillingParty      = new Party(),
                Name = "Store Payment"
            };

            storeOrder.Components.Add(paymentComponent);


            // Fulfillment
            PhysicalFulfillmentComponent physicalFulfillmentComponent = new PhysicalFulfillmentComponent
            {
                //ShippingParty = new Party() { AddressName = arg.StoreDetails.Name, Address1 = arg.StoreDetails.Address, City = arg.StoreDetails.City, State = arg.StoreDetails.State,
                //                              StateCode = arg.StoreDetails.State, Country =arg.StoreDetails.Country, CountryCode = arg.StoreDetails.Country, ZipPostalCode = arg.StoreDetails.ZipCode.ToString(), ExternalId = "0" },
                FulfillmentMethod = new EntityReference()
                {
                    Name = "Offline Store Order By Customer", EntityTarget = "b146622d-dc86-48a3-b72a-05ee8ffd187a"
                }
            };


            var shippingParty = new FakeParty()
            {
                AddressName   = arg.StoreDetails.Name,
                Address1      = arg.StoreDetails.Address,
                City          = arg.StoreDetails.City,
                State         = arg.StoreDetails.State,
                StateCode     = arg.StoreDetails.State,
                Country       = arg.StoreDetails.Country,
                CountryCode   = arg.StoreDetails.Country,
                ZipPostalCode = arg.StoreDetails.ZipCode.ToString(),
                ExternalId    = "0"
            };

            // Have to do the following because we cannot set external id on party directly
            var   tempStorage = JsonConvert.SerializeObject(shippingParty);
            Party party       = JsonConvert.DeserializeObject <Party>(tempStorage);

            physicalFulfillmentComponent.ShippingParty = party;

            storeOrder.Components.Add(physicalFulfillmentComponent);


            storeOrder.Components.Add(contactComponent);
            storeOrder.Name = "InStoreOrder";

            storeOrder.ShopName            = arg.ShopName;
            storeOrder.FriendlyId          = orderId;
            storeOrder.OrderConfirmationId = arg.OrderConfirmationId;
            storeOrder.OrderPlacedDate     = Convert.ToDateTime(arg.OrderPlacedDate);
            //string createdOrderStatus = policy2.CreatedOrderStatus;
            storeOrder.Status = arg.Status;
            Order  order = storeOrder;
            string str3  = contactComponent.IsRegistered ? policy1.AuthenticatedOrders : policy1.AnonymousOrders;
            ListMembershipsComponent membershipsComponent1 = new ListMembershipsComponent()
            {
                Memberships = new List <string>()
                {
                    CommerceEntity.ListName <Order>(),
                    str3
                }
            };


            if (contactComponent.IsRegistered && !string.IsNullOrEmpty(contactComponent.CustomerId))
            {
                membershipsComponent1.Memberships.Add(string.Format(context.GetPolicy <KnownOrderListsPolicy>().CustomerOrders, contactComponent.CustomerId));
            }
            order.SetComponent(membershipsComponent1);


            Order order2 = order;
            TransientListMembershipsComponent membershipsComponent2 = new TransientListMembershipsComponent();

            membershipsComponent2.Memberships = new List <string>()
            {
                policy1.PendingOrders
            };


            context.Logger.LogInformation(string.Format("Offline Orders.ImportOrder: OrderId={0}|GrandTotal={1} {2}", orderId, order.Totals.GrandTotal.CurrencyCode, order.Totals.GrandTotal.Amount), Array.Empty <object>());
            context.CommerceContext.AddModel(new CreatedOrder()
            {
                OrderId = orderId
            });


            Dictionary <string, double> dictionary = new Dictionary <string, double>()
            {
                {
                    "GrandTotal",
                    Convert.ToDouble(order.Totals.GrandTotal.Amount, System.Globalization.CultureInfo.InvariantCulture)
                }
            };

            createOrderBlock._telemetryClient.TrackEvent("OrderCreated", null, dictionary);
            int orderTotal = Convert.ToInt32(Math.Round(order.Totals.GrandTotal.Amount, 0), System.Globalization.CultureInfo.InvariantCulture);

            if (context.GetPolicy <PerformancePolicy>().WriteCounters)
            {
                int num1 = await createOrderBlock._performanceCounterCommand.IncrementBy("SitecoreCommerceMetrics", "MetricCount", string.Format("Orders.GrandTotal.{0}", order.Totals.GrandTotal.CurrencyCode), orderTotal, context.CommerceContext).ConfigureAwait(false) ? 1 : 0;

                int num2 = await createOrderBlock._performanceCounterCommand.Increment("SitecoreCommerceMetrics", "MetricCount", "Orders.Count", context.CommerceContext).ConfigureAwait(false) ? 1 : 0;
            }
            return(order);
        }
    void when_index_multiple_components()
    {
        #pragma warning disable
        EntityIndex<string> index = null;
        Context ctx = null;
        Group group = null;

        before = () => {
            ctx = new Context(CID.TotalComponents);
        };

        it["gets last component that triggered adding entity to group"] = () => {

            IComponent receivedComponent = null;

            group = ctx.GetGroup(Matcher.AllOf(CID.ComponentA, CID.ComponentB));
            index = new EntityIndex<string>(group, (e, c) => {
                receivedComponent = c;
                return ((NameAgeComponent)c).name;
            });

            var nameAgeComponent1 = new NameAgeComponent();
            nameAgeComponent1.name = "Max";

            var nameAgeComponent2 = new NameAgeComponent();
            nameAgeComponent2.name = "Jack";

            ctx.CreateEntity().AddComponent(CID.ComponentA, nameAgeComponent1)
                               .AddComponent(CID.ComponentB, nameAgeComponent2);

            receivedComponent.should_be_same(nameAgeComponent2);
        };

        it["works with NoneOf"] = () => {

            var receivedComponents = new List<IComponent>();

            var nameAgeComponent1 = new NameAgeComponent();
            nameAgeComponent1.name = "Max";

            var nameAgeComponent2 = new NameAgeComponent();
            nameAgeComponent2.name = "Jack";

            group = ctx.GetGroup(Matcher.AllOf(CID.ComponentA).NoneOf(CID.ComponentB));
            index = new EntityIndex<string>(group, (e, c) => {
                receivedComponents.Add(c);

                if(c == nameAgeComponent1) {
                    return ((NameAgeComponent)c).name;
                }

                return ((NameAgeComponent)e.GetComponent(CID.ComponentA)).name;
            });

            ctx.CreateEntity().AddComponent(CID.ComponentA, nameAgeComponent1)
                               .AddComponent(CID.ComponentB, nameAgeComponent2);

            receivedComponents.Count.should_be(2);
            receivedComponents[0].should_be(nameAgeComponent1);
            receivedComponents[1].should_be(nameAgeComponent2);
        };
    }
    void when_index()
    {
        EntityIndex<string> index = null;
        Context ctx = null;
        Group group = null;

        before = () => {
            ctx = new Context(CID.TotalComponents);
            group = ctx.GetGroup(Matcher.AllOf(CID.ComponentA));
            index = new EntityIndex<string>(group, (e, c) => {
                var nameAge = c as NameAgeComponent;
                return nameAge != null
                    ? nameAge.name
                    : ((NameAgeComponent)e.GetComponent(CID.ComponentA)).name;
            });
        };

        context["when entity for key doesn't exist"] = () => {

            it["has no entities"] = () => {
                index.GetEntities("unknownKey").should_be_empty();
            };
        };

        context["when entity for key exists"] = () => {

            const string name = "Max";
            NameAgeComponent nameAgeComponent = null;
            Entity entity1 = null;
            Entity entity2 = null;

            before = () => {
                nameAgeComponent = new NameAgeComponent();
                nameAgeComponent.name = name;
                entity1 = ctx.CreateEntity().AddComponent(CID.ComponentA, nameAgeComponent);
                entity2 = ctx.CreateEntity().AddComponent(CID.ComponentA, nameAgeComponent);
            };

            it["gets entities for key"] = () => {
                var entities = index.GetEntities(name);
                entities.Count.should_be(2);
                entities.should_contain(entity1);
                entities.should_contain(entity2);
            };

            it["retains entity"] = () => {
                entity1.retainCount.should_be(3); // Context, Group, EntityIndex
                entity2.retainCount.should_be(3); // Context, Group, EntityIndex
            };

            it["has existing entities"] = () => {
                var newIndex = new EntityIndex<string>(group, (e, c) => {
                    var nameAge = c as NameAgeComponent;
                    return nameAge != null
                        ? nameAge.name
                        : ((NameAgeComponent)e.GetComponent(CID.ComponentA)).name;
                });
                newIndex.GetEntities(name).Count.should_be(2);
            };

            it["releases and removes entity from index when component gets removed"] = () => {
                entity1.RemoveComponent(CID.ComponentA);
                index.GetEntities(name).Count.should_be(1);
                entity1.retainCount.should_be(1); // Context
            };

            context["when deactivated"] = () => {

                before = () => {
                    index.Deactivate();
                };

                it["clears index and releases entity"] = () => {
                    index.GetEntities(name).should_be_empty();
                    entity1.retainCount.should_be(2); // Context, Group
                    entity2.retainCount.should_be(2); // Context, Group
                };

                it["doesn't add entities anymore"] = () => {
                    ctx.CreateEntity().AddComponent(CID.ComponentA, nameAgeComponent);
                    index.GetEntities(name).should_be_empty();
                };

                context["when actrivated"] = () => {

                    before = () => {
                        index.Activate();
                    };

                    it["has existing entities"] = () => {
                        var entities = index.GetEntities(name);
                        entities.Count.should_be(2);
                        entities.should_contain(entity1);
                        entities.should_contain(entity2);
                    };

                    it["adds new entities"] = () => {
                        var entity3 = ctx.CreateEntity().AddComponent(CID.ComponentA, nameAgeComponent);

                        var entities = index.GetEntities(name);
                        entities.Count.should_be(3);
                        entities.should_contain(entity1);
                        entities.should_contain(entity2);
                        entities.should_contain(entity3);
                    };
                };
            };
        };
    }
示例#30
0
    void when_index_multiple_components()
    {
        #pragma warning disable
        EntityIndex <string> index = null;
        Pool  pool  = null;
        Group group = null;

        before = () => {
            pool = new Pool(CID.TotalComponents);
        };

        it["gets last component that triggered adding entity to group"] = () => {
            IComponent receivedComponent = null;

            group = pool.GetGroup(Matcher.AllOf(CID.ComponentA, CID.ComponentB));
            index = new EntityIndex <string>(group, (e, c) => {
                receivedComponent = c;
                return(((NameAgeComponent)c).name);
            });

            var nameAgeComponent1 = new NameAgeComponent();
            nameAgeComponent1.name = "Max";

            var nameAgeComponent2 = new NameAgeComponent();
            nameAgeComponent2.name = "Jack";

            pool.CreateEntity().AddComponent(CID.ComponentA, nameAgeComponent1)
            .AddComponent(CID.ComponentB, nameAgeComponent2);

            receivedComponent.should_be_same(nameAgeComponent2);
        };

        it["works with NoneOf"] = () => {
            var receivedComponents = new List <IComponent>();

            var nameAgeComponent1 = new NameAgeComponent();
            nameAgeComponent1.name = "Max";

            var nameAgeComponent2 = new NameAgeComponent();
            nameAgeComponent2.name = "Jack";

            group = pool.GetGroup(Matcher.AllOf(CID.ComponentA).NoneOf(CID.ComponentB));
            index = new EntityIndex <string>(group, (e, c) => {
                receivedComponents.Add(c);

                if (c == nameAgeComponent1)
                {
                    return(((NameAgeComponent)c).name);
                }

                return(((NameAgeComponent)e.GetComponent(CID.ComponentA)).name);
            });

            pool.CreateEntity().AddComponent(CID.ComponentA, nameAgeComponent1)
            .AddComponent(CID.ComponentB, nameAgeComponent2);

            receivedComponents.Count.should_be(2);
            receivedComponents[0].should_be(nameAgeComponent1);
            receivedComponents[1].should_be(nameAgeComponent2);
        };
    }
示例#31
0
    void when_index()
    {
        context["single key"] = () => {
            EntityIndex <TestEntity, string> index = null;
            IContext <TestEntity>            ctx   = null;
            IGroup <TestEntity> group = null;

            before = () => {
                ctx   = new MyTestContext();
                group = ctx.GetGroup(Matcher <TestEntity> .AllOf(CID.ComponentA));
                index = new EntityIndex <TestEntity, string>("TestIndex", group, (e, c) => {
                    var nameAge = c as NameAgeComponent;
                    return(nameAge != null
                        ? nameAge.name
                        : ((NameAgeComponent)e.GetComponent(CID.ComponentA)).name);
                });
            };

            context["when entity for key doesn't exist"] = () => {
                it["has no entities"] = () => {
                    index.GetEntities("unknownKey").should_be_empty();
                };
            };

            context["when entity for key exists"] = () => {
                const string     name             = "Max";
                NameAgeComponent nameAgeComponent = null;
                TestEntity       entity1          = null;
                TestEntity       entity2          = null;

                before = () => {
                    nameAgeComponent      = new NameAgeComponent();
                    nameAgeComponent.name = name;
                    entity1 = ctx.CreateEntity();
                    entity1.AddComponent(CID.ComponentA, nameAgeComponent);
                    entity2 = ctx.CreateEntity();
                    entity2.AddComponent(CID.ComponentA, nameAgeComponent);
                };

                it["gets entities for key"] = () => {
                    var entities = index.GetEntities(name);
                    entities.Count.should_be(2);
                    entities.should_contain(entity1);
                    entities.should_contain(entity2);
                };

                it["retains entity"] = () => {
                    entity1.retainCount.should_be(3); // Context, Group, EntityIndex
                    entity2.retainCount.should_be(3); // Context, Group, EntityIndex
                };

                it["has existing entities"] = () => {
                    var newIndex = new EntityIndex <TestEntity, string>("TestIndex", group, (e, c) => {
                        var nameAge = c as NameAgeComponent;
                        return(nameAge != null
                            ? nameAge.name
                            : ((NameAgeComponent)e.GetComponent(CID.ComponentA)).name);
                    });
                    newIndex.GetEntities(name).Count.should_be(2);
                };

                it["releases and removes entity from index when component gets removed"] = () => {
                    entity1.RemoveComponent(CID.ComponentA);
                    index.GetEntities(name).Count.should_be(1);
                    entity1.retainCount.should_be(1); // Context
                };

                it["can ToString"] = () => {
                    index.ToString().should_be("EntityIndex(TestIndex)");
                };

                context["when deactivated"] = () => {
                    before = () => {
                        index.Deactivate();
                    };

                    it["clears index and releases entity"] = () => {
                        index.GetEntities(name).should_be_empty();
                        entity1.retainCount.should_be(2); // Context, Group
                        entity2.retainCount.should_be(2); // Context, Group
                    };

                    it["doesn't add entities anymore"] = () => {
                        ctx.CreateEntity().AddComponent(CID.ComponentA, nameAgeComponent);
                        index.GetEntities(name).should_be_empty();
                    };

                    context["when activated"] = () => {
                        before = () => {
                            index.Activate();
                        };

                        it["has existing entities"] = () => {
                            var entities = index.GetEntities(name);
                            entities.Count.should_be(2);
                            entities.should_contain(entity1);
                            entities.should_contain(entity2);
                        };

                        it["adds new entities"] = () => {
                            var entity3 = ctx.CreateEntity();
                            entity3.AddComponent(CID.ComponentA, nameAgeComponent);

                            var entities = index.GetEntities(name);
                            entities.Count.should_be(3);
                            entities.should_contain(entity1);
                            entities.should_contain(entity2);
                            entities.should_contain(entity3);
                        };
                    };
                };
            };
        };

        context["multiple keys"] = () => {
            EntityIndex <TestEntity, string> index = null;
            IContext <TestEntity>            ctx   = null;
            IGroup <TestEntity> group   = null;
            TestEntity          entity1 = null;
            TestEntity          entity2 = null;

            before = () => {
                ctx   = new MyTestContext();
                group = ctx.GetGroup(Matcher <TestEntity> .AllOf(CID.ComponentA));
                index = new EntityIndex <TestEntity, string>("TestIndex", group, (e, c) => {
                    return(e == entity1
                        ? new [] { "1", "2" }
                        : new [] { "2", "3" });
                });
            };

            context["when entity for key exists"] = () => {
                before = () => {
                    entity1 = ctx.CreateEntity();
                    entity1.AddComponentA();
                    entity2 = ctx.CreateEntity();
                    entity2.AddComponentA();
                };

                it["retains entity"] = () => {
                    entity1.retainCount.should_be(3);
                    entity2.retainCount.should_be(3);

                    var safeAerc1 = entity1.aerc as SafeAERC;
                    if (safeAerc1 != null)
                    {
                        safeAerc1.owners.should_contain(index);
                    }

                    var safeAerc2 = entity1.aerc as SafeAERC;
                    if (safeAerc2 != null)
                    {
                        safeAerc2.owners.should_contain(index);
                    }
                };

                it["has entity"] = () => {
                    index.GetEntities("1").Count.should_be(1);
                    index.GetEntities("2").Count.should_be(2);
                    index.GetEntities("3").Count.should_be(1);
                };

                it["gets entity for key"] = () => {
                    index.GetEntities("1").First().should_be_same(entity1);
                    index.GetEntities("2").should_contain(entity1);
                    index.GetEntities("2").should_contain(entity2);
                    index.GetEntities("3").First().should_be_same(entity2);
                };

                it["releases and removes entity from index when component gets removed"] = () => {
                    entity1.RemoveComponent(CID.ComponentA);
                    index.GetEntities("1").Count.should_be(0);
                    index.GetEntities("2").Count.should_be(1);
                    index.GetEntities("3").Count.should_be(1);

                    entity1.retainCount.should_be(1);
                    entity2.retainCount.should_be(3);

                    var safeAerc1 = entity1.aerc as SafeAERC;
                    if (safeAerc1 != null)
                    {
                        safeAerc1.owners.should_not_contain(index);
                    }

                    var safeAerc2 = entity2.aerc as SafeAERC;
                    if (safeAerc2 != null)
                    {
                        safeAerc2.owners.should_contain(index);
                    }
                };

                it["has existing entities"] = () => {
                    index.Deactivate();
                    index.Activate();
                    index.GetEntities("1").First().should_be_same(entity1);
                    index.GetEntities("2").should_contain(entity1);
                    index.GetEntities("2").should_contain(entity2);
                    index.GetEntities("3").First().should_be_same(entity2);
                };
            };
        };
    }
示例#32
0
    void when_index_multiple_components()
    {
        #pragma warning disable
        EntityIndex <TestEntity, string> index = null;
        IContext <TestEntity>            ctx   = null;
        IGroup <TestEntity> group = null;

        before = () => {
            ctx = new MyTestContext();
        };

        it["gets last component that triggered adding entity to group"] = () => {
            IComponent receivedComponent = null;

            group = ctx.GetGroup(Matcher <TestEntity> .AllOf(CID.ComponentA, CID.ComponentB));
            index = new EntityIndex <TestEntity, string>("TestIndex", group, (e, c) => {
                receivedComponent = c;
                return(((NameAgeComponent)c).name);
            });

            var nameAgeComponent1 = new NameAgeComponent();
            nameAgeComponent1.name = "Max";

            var nameAgeComponent2 = new NameAgeComponent();
            nameAgeComponent2.name = "Jack";

            var entity = ctx.CreateEntity();
            entity.AddComponent(CID.ComponentA, nameAgeComponent1);
            entity.AddComponent(CID.ComponentB, nameAgeComponent2);

            receivedComponent.should_be_same(nameAgeComponent2);
        };

        it["works with NoneOf"] = () => {
            var receivedComponents = new List <IComponent>();

            var nameAgeComponent1 = new NameAgeComponent();
            nameAgeComponent1.name = "Max";

            var nameAgeComponent2 = new NameAgeComponent();
            nameAgeComponent2.name = "Jack";

            group = ctx.GetGroup(Matcher <TestEntity> .AllOf(CID.ComponentA).NoneOf(CID.ComponentB));
            index = new EntityIndex <TestEntity, string>("TestIndex", group, (e, c) => {
                receivedComponents.Add(c);

                if (c == nameAgeComponent1)
                {
                    return(((NameAgeComponent)c).name);
                }

                return(((NameAgeComponent)e.GetComponent(CID.ComponentA)).name);
            });

            var entity = ctx.CreateEntity();
            entity.AddComponent(CID.ComponentA, nameAgeComponent1);
            entity.AddComponent(CID.ComponentB, nameAgeComponent2);

            receivedComponents.Count.should_be(2);
            receivedComponents[0].should_be(nameAgeComponent1);
            receivedComponents[1].should_be(nameAgeComponent2);
        };
    }
        /// <summary>
        /// The execute.
        /// </summary>
        /// <param name="arg">The argument.</param>
        /// <param name="context">The context.</param>
        /// <returns>
        /// The data row for a customer<see cref="DataRow" />.
        /// </returns>
        public override async Task <DataRow> Run(DataRow arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull($"{this.Name} The data row can not be null");

            var email = arg["u_email_address"] as string;

            // verify if customer exists
            var result = await this._findEntityPipeline.Run(new FindEntityArgument(typeof(EntityIndex), $"{EntityIndex.IndexPrefix<Customer>("Id")}{email}"), context).ConfigureAwait(false);

            if (result is EntityIndex customerIndex)
            {
                context.Abort(
                    await context.CommerceContext.AddMessage(
                        context.GetPolicy <KnownResultCodes>().Warning,
                        "CustomerAlreadyExists",
                        new object[] { email, customerIndex.EntityId },
                        $"Customer { email } already exists.").ConfigureAwait(false),
                    context);
                return(null);
            }

            return(arg);
        }