public void Two_aggregates_with_same_id_should_be_equal()
        {
            object aggregate1 = new Aggregate("id");
            object aggregate2 = new Aggregate("id");

            aggregate1.Equals(aggregate2).Should().BeTrue();
        }
Exemplo n.º 2
0
        internal AggregateNode(DataTable table, FunctionId aggregateType, string columnName, bool local, string relationName) : base(table) {
            Debug.Assert(columnName != null, "Invalid parameter column name (null).");
            this.aggregate = (Aggregate)(int)aggregateType;

            if (aggregateType == FunctionId.Sum)
                this.type = AggregateType.Sum;
            else if (aggregateType == FunctionId.Avg)
                this.type = AggregateType.Mean;
            else if (aggregateType == FunctionId.Min)
                this.type = AggregateType.Min;
            else if (aggregateType == FunctionId.Max)
                this.type = AggregateType.Max;
            else if (aggregateType == FunctionId.Count)
                this.type = AggregateType.Count;
            else if (aggregateType == FunctionId.Var)
                this.type = AggregateType.Var;
            else if (aggregateType == FunctionId.StDev)
                this.type = AggregateType.StDev;
            else {
                throw ExprException.UndefinedFunction(Function.FunctionName[(Int32)aggregateType]);
            }

            this.local = local;
            this.relationName = relationName;
            this.columnName = columnName;
        }
        public void When_taking_uncommitted_events_then_original_version_should_equal_version()
        {
            var aggregate = new Aggregate("id");
            aggregate.Command();

            ((IAggregate)aggregate).TakeUncommittedEvents();
            ((IAggregate)aggregate).OriginalVersion.Should().Be(1);
        }
Exemplo n.º 4
0
 public void should_publish_events_from_internal_entities() {
   var aggregate = new Aggregate(Guid.Empty);
   var guid = Guid.NewGuid();
   aggregate.GenerateEntityEvent(new EntityCreated(guid));
   var events = aggregate.GetUncommittedChanges();
   Assert.That(
     events.Any(@event => @event.GetType() == typeof (EntityCreated)));
 }
        public void Should_not_require_an_explicit_handler()
        {
            var aggregate = new Aggregate("id");

            aggregate.Command();

            aggregate.Version.Should().Be(1);
        }
        public void When_applying_command_then_version_should_be_incremented()
        {
            var aggregate = new Aggregate("id");
            aggregate.Command();

            ((IAggregate)aggregate).OriginalVersion.Should().Be(0);
            aggregate.Version.Should().Be(1);
        }
        public void When_raising_null_event_then_should_have_no_uncommitted_events()
        {
            var aggregate = new Aggregate("id");
            aggregate.CommandThatDoesNothing();

            var uncommittedEvents = ((IAggregate)aggregate).TakeUncommittedEvents();

            uncommittedEvents.Count.Should().Be(0);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Returns an object that represents the aggregate of the items in an IEnumerable defined
        /// by the delegate supplied. An optional seed parameter is used as the aggregate collector.
        /// </summary>
        /// <param name="e">The IEnumerable to iterate.</param>
        /// <param name="seed">Optional. The object to seed the delegate.</param>
        /// <param name="a">The delegate which is applied to each element.</param>
        /// <returns>An object that is the result of the aggregate being applied to each element.</returns>
        public static object Aggregate(this IEnumerable e, object seed, Aggregate a)
        {
            foreach (var o in e)
            {
                seed = a(seed, o);
            }

            return seed;
        }
 private void writeAggregateDetails(Aggregate<IEventLogRecord> aggregate)
 {
     StreamWriter details =
         new StreamWriter(File.Open(_folder + "\\" + _fileNameGenerator.NextName, FileMode.Create));
     foreach (IEventLogRecord record in aggregate.Entries)
     {
         details.WriteLine(csv(record));
     }
     details.Close();
 }
        //this function computes the TeamBall Possession data for a specified time duration timeWindowInSec
        public static IObservable<TeamBallPossession> computeTeamBallPossessionTW(IObservable<PlayerBallPossession> src,int timeWindowInSec)
        {
            var timeWindowInPico = timeWindowInSec * MetaData.SECOND_TO_PICO;
               // List<PlayerBallPossession> list_of_values = new List<PlayerBallPossession>();
            Aggregate seed= new Aggregate { currTeam = "", pTimeA = 0.0, pTimeB = 0.0, ts = 0 };

            return src
            .TimeWindowForTsDataAggregate(timeWindowInPico, "ts", seed, aggregatorFunction)
            .Select(b => getTeamPossessionData(b));
        }
Exemplo n.º 11
0
        public void UsingDefaultConstructorReturnsInstanceWithExpectedProperties()
        {
            var id = Guid.NewGuid();
              var version = Aggregate.InitialVersion;
              var root = new DummyAggregateRootEntity();
              var sut = new Aggregate(id, version, root);

              Assert.That(sut.Id, Is.EqualTo(id));
              Assert.That(sut.Version, Is.EqualTo(version));
              Assert.That(sut.Root, Is.EqualTo(root));
        }
        public static ICollection<ServerModeSummaryDescriptor> AddSummaryDesciptor(this ICollection<ServerModeSummaryDescriptor> source, Aggregate summaryType, string propertyName)
        {
            var result = source != null
                             ? new List<ServerModeSummaryDescriptor>(source)
                             : new List<ServerModeSummaryDescriptor>();

            var summaryDescriptor = summaryType.CreateDescriptorFor(propertyName);

            result.Add(summaryDescriptor);

            return result;
        }
Exemplo n.º 13
0
        public void TestMethod1()
        {
            var value = new Aggregate { Base = new Derived() };
            using (var stream = new MemoryStream())
            {
                Serializer.Serialize(stream, value);
                stream.Position = 0;

                var obj = Serializer.Deserialize<Aggregate>(stream);
                Assert.AreEqual(typeof(Derived), obj.Base.GetType());
            }
        }
Exemplo n.º 14
0
        public void Should_route_event()
        {
            object @event = null;
            var aggregate = new Aggregate("id", e => @event = e);
            var eventThatIsRouted = new EventThatIsRouted();

            using (var rehydrate = ((IAggregate)aggregate).BeginRehydrate())
            {
                rehydrate.ApplyEvent(eventThatIsRouted);
            }

            @event.Should().Be(eventThatIsRouted);
        }
Exemplo n.º 15
0
        private static void replay(IEnumerable<Event> changeEvents, Aggregate aggregate)
        {
            foreach (var @event in changeEvents)
                try
                {
                    aggregate.AsDynamic().Receive(@event);
                }
                catch (ApplicationException e)
                {
                    if (e.Source == "ReflectionMagic")
                        throw new MissingMethodException(aggregate.GetType().FullName, "Receive(" + @event.GetType() + ")");

                    throw;
                }
        }
Exemplo n.º 16
0
        public EventHandlerDiscovery Scan(Aggregate aggregate)
        {
            var handlerInterface = typeof(IHandle<>);
            var aggType = aggregate.GetType();

            var interfaces = aggType.GetInterfaces();

            var instances = from i in aggType.GetInterfaces()
                            where (i.IsGenericType && handlerInterface.IsAssignableFrom(i.GetGenericTypeDefinition()))
                            select i.GenericTypeArguments[0];

            foreach (var i in instances)
            {
                Handlers.Add(i, aggregate);
            }

            return this;
        }
Exemplo n.º 17
0
        public MainWindow()
        {
            InitializeComponent();
            // populate Aggregate combobox
            var aggregates = new Aggregate[]
            {
                Aggregate.None,
                Aggregate.Sum,
                Aggregate.Average,
                Aggregate.Maximum,
                Aggregate.Minimum,
                Aggregate.Count
            };

            foreach (var agg in aggregates)
            {
                _cmbAggregates.Items.Add(agg);
            }
            _cmbAggregates.SelectedIndex = 1; // Aggregate.Sum

            // build data source
            var view = Product.GetProducts(200);

            // set up grouping
            var gd = view.GroupDescriptions;
            gd.Add(new PropertyGroupDescription("Total"));  // grand total group
            gd.Add(new PropertyGroupDescription("Line"));   // group by product line
            gd.Add(new PropertyGroupDescription("Color"));  // group by product color
            gd.Add(new PropertyGroupDescription("Price"));  // group by price range
            var pgdPrice = gd[gd.Count - 1] as PropertyGroupDescription;
            pgdPrice.Converter = new PriceRangeConverter();

            // assign data source to grid
            _flex.ItemsSource = view;

            // provide choices in grid editors
            _flex.Columns["Line"].ValueConverter = new ColumnValueConverter(Product.GetLines(), true);
            _flex.Columns["Color"].ValueConverter = new ColumnValueConverter(Product.GetColors(), false);

            // needed to show aggregates
            _flex.AreRowGroupHeadersFrozen = false;
        }
 //calculates the team ball possession data from player ball possession
 private static Aggregate aggregatorFunction(Aggregate seed, PlayerBallPossession curr,
     IList<PlayerBallPossession> expList, long count)
 {
     double pTimeA = seed.pTimeA, pTimeB = seed.pTimeB;
     //remove expired possession time from the aggregate team possession time information
     foreach (var ele in expList)
     {
         if (MetaData.PLAYER_TEAM_MAP[ele.player_id].Equals("A"))
             pTimeA -= ele.time;
         else
             pTimeB -= ele.time;
     }
     string team_name = MetaData.PLAYER_TEAM_MAP[curr.player_id];
     //if the player for which this PlayerBallPossession information(curr) belongs to Team A
     //then add possession time of this player to pTimeA else to pTimeB
     if (team_name.Equals("A"))
         pTimeA = seed.pTimeA + curr.time;
     else
         pTimeB = seed.pTimeB + curr.time;
     //return updated team possession time information
     return new Aggregate { currTeam = team_name, pTimeA = pTimeA, pTimeB = pTimeB, ts = curr.ts };
 }
Exemplo n.º 19
0
 protected override String GetOperatorString(Aggregate operatorType)
 {
     return base.GetOperatorString(operatorType);
 }
 public override void PreSave(Aggregate aggregate, CommandContext context)
 {
     base.PreSave(null, null); PreSaveHandled = true;
 }
Exemplo n.º 21
0
        /// <summary>
        /// Creates Entities from aggregates (collections of components)
        /// </summary>
        /// <param name="aggregate">The specific aggreage to create</param>
        public void CreateFromAggregate(Aggregate aggregate)
        {
            switch (aggregate)
            {
                case Aggregate.FairyPlayer:
                    uint entityID = Entity.NextEntity();
                    Texture2D spriteSheet = game.Content.Load<Texture2D>("Spritesheets/wind_fae");
                    spriteSheet.Name = "Spritesheets/wind_fae";

                    Position position = new Position()
                    {
                        EntityID = entityID,
                        Center = new Vector2(400, 50),
                        Radius = 32f,
                    };
                    game.PositionComponent[entityID] = position;

                    Movement movement = new Movement() {
                        EntityID = entityID,
                        Direction = new Vector2(0, 1),
                        Speed = 200f,
                    };
                    game.MovementComponent[entityID] = movement;

                    MovementSprite movementSprite = new MovementSprite() {
                        EntityID = entityID,
                        Facing = Facing.South,
                        SpriteSheet = spriteSheet,
                        SpriteBounds = new Rectangle(0, 0, 64, 64),
                        Timer = 0f,
                    };
                    game.MovementSpriteComponent[entityID] = movementSprite;

                    Local local = new Local(){
                        EntityID = entityID,
                    };
                    game.LocalComponent[entityID] = local;

                    Player player = new Player()
                    {
                        EntityID = entityID,
                        PlayerIndex = PlayerIndex.One,
                    };
                    game.PlayerComponent[entityID] = player;

                    break;

                case Aggregate.CultistPlayer:
                    break;

                case Aggregate.CyborgPlayer:
                    break;

                case Aggregate.EarthianPlayer:
                    break;

                case Aggregate.GargranianPlayer:
                    break;

                case Aggregate.SpacePiratePlayer:
                    break;

                case Aggregate.ZombiePlayer:
                    break;
            }
        }
Exemplo n.º 22
0
        public bool TryCreateObject(ObjectType objectType, out IPersistable persistObj)
        {
            switch (objectType)
            {
            case ObjectType.Aggregate:
                persistObj = new Aggregate();
                break;

            case ObjectType.AggregateRow:
                persistObj = new AggregateRow();
                break;

            case ObjectType.Avg:
                persistObj = new Avg();
                break;

            case ObjectType.BTree:
                persistObj = new BTree();
                break;

            case ObjectType.BTreeNode:
                persistObj = new BTreeNode();
                break;

            case ObjectType.BTreeNodeTupleList:
                persistObj = new BTreeNodeTupleList();
                break;

            case ObjectType.BTreeNodeTuple:
                persistObj = new BTreeNodeTuple();
                break;

            case ObjectType.BTreeNodeHierarchyObj:
                persistObj = new BTreeNodeHierarchyObj();
                break;

            case ObjectType.CalculatedFieldWrapperImpl:
                persistObj = new CalculatedFieldWrapperImpl();
                break;

            case ObjectType.ChildLeafInfo:
                persistObj = new ChildLeafInfo();
                break;

            case ObjectType.Count:
                persistObj = new Count();
                break;

            case ObjectType.CountDistinct:
                persistObj = new CountDistinct();
                break;

            case ObjectType.CountRows:
                persistObj = new CountRows();
                break;

            case ObjectType.DataAggregateObj:
                persistObj = new DataAggregateObj();
                break;

            case ObjectType.DataAggregateObjResult:
                persistObj = new DataAggregateObjResult();
                break;

            case ObjectType.DataFieldRow:
                persistObj = new DataFieldRow();
                break;

            case ObjectType.DataRegionMemberInstance:
                persistObj = new DataRegionMemberInstance();
                break;

            case ObjectType.FieldImpl:
                persistObj = new FieldImpl();
                break;

            case ObjectType.First:
                persistObj = new First();
                break;

            case ObjectType.Last:
                persistObj = new Last();
                break;

            case ObjectType.Max:
                persistObj = new Max();
                break;

            case ObjectType.Min:
                persistObj = new Min();
                break;

            case ObjectType.Previous:
                persistObj = new Previous();
                break;

            case ObjectType.RuntimeCells:
                persistObj = new RuntimeCells();
                break;

            case ObjectType.RuntimeChartCriCell:
                persistObj = new RuntimeChartCriCell();
                break;

            case ObjectType.RuntimeChartCriGroupLeafObj:
                persistObj = new RuntimeChartCriGroupLeafObj();
                break;

            case ObjectType.RuntimeChartObj:
                persistObj = new RuntimeChartObj();
                break;

            case ObjectType.RuntimeGaugePanelObj:
                persistObj = new RuntimeGaugePanelObj();
                break;

            case ObjectType.RuntimeCriObj:
                persistObj = new RuntimeCriObj();
                break;

            case ObjectType.RuntimeDataTablixGroupRootObj:
                persistObj = new RuntimeDataTablixGroupRootObj();
                break;

            case ObjectType.RuntimeDataTablixMemberObj:
                persistObj = new RuntimeDataTablixMemberObj();
                break;

            case ObjectType.RuntimeExpressionInfo:
                persistObj = new RuntimeExpressionInfo();
                break;

            case ObjectType.RuntimeHierarchyObj:
                persistObj = new RuntimeHierarchyObj();
                break;

            case ObjectType.RuntimeRICollection:
                persistObj = new RuntimeRICollection();
                break;

            case ObjectType.RuntimeSortDataHolder:
                persistObj = new RuntimeSortDataHolder();
                break;

            case ObjectType.RuntimeSortFilterEventInfo:
                persistObj = new RuntimeSortFilterEventInfo();
                break;

            case ObjectType.RuntimeSortHierarchyObj:
                persistObj = new RuntimeSortHierarchyObj();
                break;

            case ObjectType.RuntimeDataRowSortHierarchyObj:
                persistObj = new RuntimeDataRowSortHierarchyObj();
                break;

            case ObjectType.RuntimeTablixCell:
                persistObj = new RuntimeTablixCell();
                break;

            case ObjectType.RuntimeTablixGroupLeafObj:
                persistObj = new RuntimeTablixGroupLeafObj();
                break;

            case ObjectType.RuntimeTablixObj:
                persistObj = new RuntimeTablixObj();
                break;

            case ObjectType.RuntimeUserSortTargetInfo:
                persistObj = new RuntimeUserSortTargetInfo();
                break;

            case ObjectType.ScopeLookupTable:
                persistObj = new ScopeLookupTable();
                break;

            case ObjectType.SortExpressionScopeInstanceHolder:
                persistObj = new RuntimeSortFilterEventInfo.SortExpressionScopeInstanceHolder();
                break;

            case ObjectType.SortFilterExpressionScopeObj:
                persistObj = new RuntimeSortFilterEventInfo.SortFilterExpressionScopeObj();
                break;

            case ObjectType.SortHierarchyStruct:
                persistObj = new RuntimeSortHierarchyObj.SortHierarchyStructure();
                break;

            case ObjectType.SortScopeValuesHolder:
                persistObj = new RuntimeSortFilterEventInfo.SortScopeValuesHolder();
                break;

            case ObjectType.StDev:
                persistObj = new StDev();
                break;

            case ObjectType.StDevP:
                persistObj = new StDevP();
                break;

            case ObjectType.StorageItem:
                persistObj = new StorageItem();
                break;

            case ObjectType.Sum:
                persistObj = new Sum();
                break;

            case ObjectType.Var:
                persistObj = new Var();
                break;

            case ObjectType.VarP:
                persistObj = new VarP();
                break;

            case ObjectType.FilterKey:
                persistObj = new Filters.FilterKey();
                break;

            case ObjectType.LookupMatches:
                persistObj = new LookupMatches();
                break;

            case ObjectType.LookupMatchesWithRows:
                persistObj = new LookupMatchesWithRows();
                break;

            case ObjectType.LookupTable:
                persistObj = new LookupTable();
                break;

            case ObjectType.Union:
                persistObj = new Union();
                break;

            case ObjectType.RuntimeMapDataRegionObj:
                persistObj = new RuntimeMapDataRegionObj();
                break;

            case ObjectType.DataScopeInfo:
                persistObj = new DataScopeInfo();
                break;

            case ObjectType.BucketedDataAggregateObjs:
                persistObj = new BucketedDataAggregateObjs();
                break;

            case ObjectType.DataAggregateObjBucket:
                persistObj = new DataAggregateObjBucket();
                break;

            case ObjectType.RuntimeGroupingObjHash:
                persistObj = new RuntimeGroupingObjHash();
                break;

            case ObjectType.RuntimeGroupingObjTree:
                persistObj = new RuntimeGroupingObjTree();
                break;

            case ObjectType.RuntimeGroupingObjDetail:
                persistObj = new RuntimeGroupingObjDetail();
                break;

            case ObjectType.RuntimeGroupingObjDetailUserSort:
                persistObj = new RuntimeGroupingObjDetailUserSort();
                break;

            case ObjectType.RuntimeGroupingObjLinkedList:
                persistObj = new RuntimeGroupingObjLinkedList();
                break;

            case ObjectType.RuntimeGroupingObjNaturalGroup:
                persistObj = new RuntimeGroupingObjNaturalGroup();
                break;

            default:
                persistObj = null;
                return(false);
            }
            return(true);
        }
Exemplo n.º 23
0
 public long ZsetUnionStore(RedisKey dest, RedisKey first, RedisKey second, Aggregate aggregate)
 {
     return(m_DataBase.SortedSetCombineAndStore(SetOperation.Union, dest, first, second, aggregate));
 }
Exemplo n.º 24
0
 public void should_handle_single_return_value()
 {
     Aggregate.Do(new Hide());
     Assert.False(State.IsVisible);
 }
Exemplo n.º 25
0
 /// <summary>
 /// Returns an object that represents the aggregate of the items in an IEnumerable defined
 /// by the delegate supplied. An optional seed parameter is used as the aggregate collector.
 /// </summary>
 /// <param name="e">The IEnumerable to iterate.</param>
 /// <param name="a">The delegate which is applied to each element.</param>
 /// <returns>An object that is the result of the aggregate being applied to each element.</returns>
 public static object Aggregate(this IEnumerable e, Aggregate a)
 {
     return(Aggregate(e, new object(), a));
 }
Exemplo n.º 26
0
        private IObservable <TdApi.Message> LoadAggregateMessages(
            Aggregate aggregate,
            AggregateLoadingState state)
        {
            var actualLimit = _limit;

            var list = aggregate.Chats.Select(f =>
            {
                var stackedCount = state.CountStackedMessages(f.ChatData.Id);

                return(Enumerable.Range(0, stackedCount)
                       .Select(_ => state.PopMessageFromStack(f.ChatData.Id)) // get stacked messages for this chat
                       .ToObservable()
                       .Concat(stackedCount < _limit
                        ? LoadChannelMessages(f, new ChatLoadingState // load messages from the server
                {
                    LastMessageId = state.GetLastMessageId(f.ChatData.Id)
                }, _limit, 0)
                        : Observable.Empty <TdApi.Message>())
                       .Aggregate(new List <TdApi.Message>(), (l, m) =>
                {
                    l.Add(m);
                    return l;
                })
                       .Do(l =>
                {
                    // api has no guarantees about actual number of messages returned
                    // actual limit would be equal to min number of messages for all feeds
                    // unless it is zero
                    if (l.Count > 0 && l.Count < actualLimit)
                    {
                        actualLimit = l.Count;
                    }
                })
                       .SelectMany(messages => messages));
            });

            return(list.Merge()
                   .Aggregate(new List <TdApi.Message>(), (l, m) =>
            {
                l.Add(m);
                return l;
            })
                   .SelectMany(l =>
            {
                // make sure all messages are unique
                var all = l.GroupBy(m => m.Id)
                          .Select(g => g.First())
                          .OrderByDescending(m => m.Date)
                          .ToArray();

                var toBeReturned = all.Take(actualLimit);
                var toBeStacked = all.Skip(actualLimit);

                // remember last message id
                foreach (var message in all.Reverse())
                {
                    state.SetLastMessageId(message.ChatId, message.Id);
                }

                // put into stack
                foreach (var message in toBeStacked.Reverse())
                {
                    state.PushMessageToStack(message.ChatId, message);
                }

                return toBeReturned;
            }));
        }
        public static ICollection <ServerModeSummaryDescriptor> AddSummaryDesciptor(this ICollection <ServerModeSummaryDescriptor> source, Aggregate summaryType, string propertyName)
        {
            var result = source != null
                             ? new List <ServerModeSummaryDescriptor>(source)
                             : new List <ServerModeSummaryDescriptor>();


            var summaryDescriptor = summaryType.CreateDescriptorFor(propertyName);

            result.Add(summaryDescriptor);


            return(result);
        }
 public static ServerModeSummaryDescriptor CreateDescriptorFor(this string propertyName, Aggregate summaryType)
 {
     return(new ServerModeSummaryDescriptor(new OperandProperty(propertyName), summaryType));
 }
 private static string CalculateKeyPart(Aggregate source)
 {
     return(source.ToString());
 }
Exemplo n.º 30
0
 private Task Save(Aggregate agg, string entityName, Guid userId)
 {
     return(_aggregateStorage.SaveEventsAsync(agg, entityName, userId));
 }
Exemplo n.º 31
0
 public void Save(Aggregate aggregate)
 {
     _store.AddEvents(aggregate.Id, aggregate.GetEvents());
 }
Exemplo n.º 32
0
 public Task <long> SortedSetCombineAndStoreAsync(SetOperation operation, RedisKey destination, RedisKey first, RedisKey second, Aggregate aggregate = Aggregate.Sum, CommandFlags flags = CommandFlags.None)
 {
     return(this.db.SortedSetCombineAndStoreAsync(operation, destination, first, second, aggregate, flags));
 }
 public override void PreSave(Aggregate aggregate, CommandContext context)
 {
 }
Exemplo n.º 34
0
        public void Sum()
        {
            // NOTE: fully qualifying the type name matters.  If this were a real thing, you could put in default namespaces.
            var summer = new Aggregate<Event<long>>("(sum, @event) => new RoslynRx.Tests.Event<long>(0, sum.Data + @event.Data)");
            var testInterval = new TestInterval();
            long sum = long.MinValue;

            testInterval.Interval.Link(summer).Subscribe(i => sum = i.Data);
            testInterval.Start();
            sum.Should().Be(1770);
        }
Exemplo n.º 35
0
 private void _createFromState(TAggregateState state)
 {
     Aggregate.SetState(state);
 }
Exemplo n.º 36
0
        public void SetUp()
        {
            _createSomething          = new CreateSomething();
            _somethingCreated         = new SomethingCreated();
            _somethingCreatedConcrete = new SomethingCreated();
            _events = new List <IEvent> {
                _somethingCreated
            };

            _createAggregate          = new CreateAggregate();
            _aggregateCreatedConcrete = new AggregateCreated();
            _aggregate        = new Aggregate();
            _aggregateCreated = (AggregateCreated)_aggregate.Events[0];

            _sampleCommandSequence = new sampleCommandSequence();

            _commandResponse = new CommandResponse {
                Events = _events, Result = "Result"
            };
            _domainCommandResponse = new CommandResponse {
                Events = _aggregate.Events, Result = "Result"
            };

            _eventPublisher = new Mock <IEventPublisher>();
            _eventPublisher
            .Setup(x => x.Publish(_aggregateCreatedConcrete));

            _storeProvider = new Mock <IStoreProvider>();
            _storeProvider
            .Setup(x => x.Save(It.IsAny <SaveStoreData>()))
            .Callback <SaveStoreData>(x => _storeDataSaved = x);

            _eventFactory = new Mock <IEventFactory>();
            _eventFactory
            .Setup(x => x.CreateConcreteEvent(_somethingCreated))
            .Returns(_somethingCreatedConcrete);
            _eventFactory
            .Setup(x => x.CreateConcreteEvent(_aggregateCreated))
            .Returns(_aggregateCreatedConcrete);

            _validationService = new Mock <IValidationService>();
            _validationService
            .Setup(x => x.Validate(_createAggregate));

            _commandHandler = new Mock <ICommandHandler <CreateSomething> >();
            _commandHandler
            .Setup(x => x.Handle(_createSomething))
            .Returns(_commandResponse);

            _domainCommandHandler = new Mock <ICommandHandler <CreateAggregate> >();
            _domainCommandHandler
            .Setup(x => x.Handle(_createAggregate))
            .Returns(_domainCommandResponse);

            _sequenceCommandHandler = new Mock <ISequenceCommandHandler <ICommand> >();
            _sequenceCommandHandler
            .Setup(x => x.Handle(It.IsAny <ICommand>(), It.IsAny <CommandResponse>()))
            .Returns(It.IsAny <CommandResponse>());

            _handlerResolver = new Mock <IHandlerResolver>();
            _handlerResolver
            .Setup(x => x.ResolveHandler(_createSomething, typeof(ICommandHandler <>)))
            .Returns(_commandHandler.Object);
            _handlerResolver
            .Setup(x => x.ResolveHandler(_createAggregate, typeof(ICommandHandler <>)))
            .Returns(_domainCommandHandler.Object);
            _handlerResolver
            .Setup(x => x.ResolveHandler(It.IsAny <ICommand>(), typeof(ISequenceCommandHandler <>)))
            .Returns(_sequenceCommandHandler.Object);

            _optionsMock = new Mock <IOptions <Options> >();
            _optionsMock
            .Setup(x => x.Value)
            .Returns(new Options());

            _sut = new CommandSender(_handlerResolver.Object,
                                     _eventPublisher.Object,
                                     _eventFactory.Object,
                                     _storeProvider.Object,
                                     _validationService.Object,
                                     _optionsMock.Object);
        }
Exemplo n.º 37
0
Arquivo: Scenes.cs Projeto: akav/pbrt
 public SceneDescription(Aggregate aggr, IEnumerable <Light> lights, Camera camera)
 {
     Scene  = new Scene(aggr, lights);
     Camera = camera;
 }
Exemplo n.º 38
0
 public ExecutionReport VariantAnalysis(char strand, Dictionary <string, Dictionary <char, List <I> > > references, Aggregate aggregate, out FunctionOutput <Output <C, I, M> > result, MaxDegreeOfParallelism maxDegreeOfParallelism, out Dictionary <uint, int> newRes)
 {
     return(genome.VariantAnalysis(references, strand, aggregate, out result, out newRes, maxDegreeOfParallelism));
 }
Exemplo n.º 39
0
 public List <DomainEvent> EventsForAggregate(Aggregate aggregate)
 {
     return(EventsForAggregate(new AggregateKey(aggregate)));
 }
Exemplo n.º 40
0
 private static List <Declaration> BuildDeclarations()
 {
     return(new List <Declaration>(83)
     {
         Aggregate.GetDeclaration(),
         AggregateRow.GetDeclaration(),
         Avg.GetDeclaration(),
         BTree.GetDeclaration(),
         BTreeNode.GetDeclaration(),
         BTreeNodeTuple.GetDeclaration(),
         BTreeNodeTupleList.GetDeclaration(),
         BTreeNodeHierarchyObj.GetDeclaration(),
         CalculatedFieldWrapperImpl.GetDeclaration(),
         ChildLeafInfo.GetDeclaration(),
         Count.GetDeclaration(),
         CountDistinct.GetDeclaration(),
         CountRows.GetDeclaration(),
         DataAggregateObj.GetDeclaration(),
         DataAggregateObjResult.GetDeclaration(),
         DataRegionMemberInstance.GetDeclaration(),
         DataFieldRow.GetDeclaration(),
         FieldImpl.GetDeclaration(),
         First.GetDeclaration(),
         Last.GetDeclaration(),
         Max.GetDeclaration(),
         Min.GetDeclaration(),
         Previous.GetDeclaration(),
         RuntimeCell.GetDeclaration(),
         RuntimeCells.GetDeclaration(),
         RuntimeCellWithContents.GetDeclaration(),
         RuntimeChartCriCell.GetDeclaration(),
         RuntimeChartCriGroupLeafObj.GetDeclaration(),
         RuntimeChartCriObj.GetDeclaration(),
         RuntimeChartObj.GetDeclaration(),
         RuntimeCriObj.GetDeclaration(),
         RuntimeDataRegionObj.GetDeclaration(),
         RuntimeDataTablixObj.GetDeclaration(),
         RuntimeDataTablixGroupLeafObj.GetDeclaration(),
         RuntimeDataTablixGroupRootObj.GetDeclaration(),
         RuntimeDataTablixMemberObj.GetDeclaration(),
         RuntimeDataTablixWithScopedItemsObj.GetDeclaration(),
         RuntimeDataTablixWithScopedItemsGroupLeafObj.GetDeclaration(),
         RuntimeDetailObj.GetDeclaration(),
         RuntimeExpressionInfo.GetDeclaration(),
         RuntimeGroupLeafObj.GetDeclaration(),
         RuntimeGroupObj.GetDeclaration(),
         RuntimeGroupRootObj.GetDeclaration(),
         RuntimeGroupingObj.GetDeclaration(),
         RuntimeHierarchyObj.GetDeclaration(),
         RuntimeMemberObj.GetDeclaration(),
         RuntimeRDLDataRegionObj.GetDeclaration(),
         RuntimeRICollection.GetDeclaration(),
         RuntimeSortDataHolder.GetDeclaration(),
         RuntimeSortFilterEventInfo.GetDeclaration(),
         RuntimeSortFilterEventInfo.SortExpressionScopeInstanceHolder.GetDeclaration(),
         RuntimeSortFilterEventInfo.SortFilterExpressionScopeObj.GetDeclaration(),
         RuntimeSortFilterEventInfo.SortScopeValuesHolder.GetDeclaration(),
         RuntimeSortHierarchyObj.GetDeclaration(),
         RuntimeSortHierarchyObj.SortHierarchyStructure.GetDeclaration(),
         RuntimeDataRowSortHierarchyObj.GetDeclaration(),
         RuntimeTablixCell.GetDeclaration(),
         RuntimeTablixGroupLeafObj.GetDeclaration(),
         RuntimeTablixObj.GetDeclaration(),
         RuntimeUserSortTargetInfo.GetDeclaration(),
         ScopeInstance.GetDeclaration(),
         ScopeLookupTable.GetDeclaration(),
         StDev.GetDeclaration(),
         StDevP.GetDeclaration(),
         Sum.GetDeclaration(),
         Var.GetDeclaration(),
         VarBase.GetDeclaration(),
         VarP.GetDeclaration(),
         Filters.FilterKey.GetDeclaration(),
         RuntimeGaugePanelObj.GetDeclaration(),
         LookupMatches.GetDeclaration(),
         LookupMatchesWithRows.GetDeclaration(),
         LookupTable.GetDeclaration(),
         RuntimeMapDataRegionObj.GetDeclaration(),
         DataScopeInfo.GetDeclaration(),
         BucketedDataAggregateObjs.GetDeclaration(),
         DataAggregateObjBucket.GetDeclaration(),
         RuntimeGroupingObjHash.GetDeclaration(),
         RuntimeGroupingObjTree.GetDeclaration(),
         RuntimeGroupingObjDetail.GetDeclaration(),
         RuntimeGroupingObjDetailUserSort.GetDeclaration(),
         RuntimeGroupingObjLinkedList.GetDeclaration(),
         RuntimeGroupingObjNaturalGroup.GetDeclaration()
     });
 }
Exemplo n.º 41
0
 public long ZsetUnionStore(RedisKey dest, RedisKey[] keys, double[] weights, Aggregate aggregate)
 {
     return(m_DataBase.SortedSetCombineAndStore(SetOperation.Union, dest, keys, weights, aggregate));
 }
Exemplo n.º 42
0
 /// <summary>
 /// Returns an object that represents the aggregate of the items in an IEnumerable defined
 /// by the delegate supplied. An optional seed parameter is used as the aggregate collector.
 /// </summary>
 /// <param name="e">The IEnumerable to iterate.</param>
 /// <param name="seed">Optional. The object to seed the delegate.</param>
 /// <param name="a">The aggregate delegate which is applied to each element.</param>
 /// <param name="s">Optional. A selector delegate used to select the result from the seed.</param>
 /// <returns>An object that is the result of the aggregate being applied to each element.</returns>
 public static object Aggregate(this IEnumerable e, object seed, Aggregate a, Selector s)
 {
     return(s(Aggregate(e, seed, a)));
 }
        public IAttributeDefinition Aggregate(Aggregate aggregate)
        {
            if (IsMultiValue)
            {
                switch (aggregate)
                {
                case APIClient.Aggregate.Min:
                    switch (AttributeType)
                    {
                    case AttributeType.Numeric:
                        return(metaModel.GetAttributeDefinition(Token + ".@Min"));

                    case AttributeType.Date:
                        return(metaModel.GetAttributeDefinition(Token + ".@MinDate"));
                    }

                    throw new MetaException("Must aggregate MIN of numerics and dates");

                case APIClient.Aggregate.Max:
                    switch (AttributeType)
                    {
                    case AttributeType.Numeric:
                        return(metaModel.GetAttributeDefinition(Token + ".@Max"));

                    case AttributeType.Date:
                        return(metaModel.GetAttributeDefinition(Token + ".@MaxDate"));
                    }

                    throw new MetaException("Must aggregate MAX of numerics and dates");

                case APIClient.Aggregate.Count:
                    if (AttributeType == AttributeType.Relation)
                    {
                        return(metaModel.GetAttributeDefinition(Token + ".@Count"));
                    }

                    throw new MetaException("Must aggregate COUNT of relations");

                case APIClient.Aggregate.Sum:
                    if (AttributeType == AttributeType.Numeric)
                    {
                        return(metaModel.GetAttributeDefinition(Token + ".@Sum"));
                    }

                    throw new MetaException("Must aggregate SUM of numerics");

                case APIClient.Aggregate.And:
                    if (AttributeType == AttributeType.Boolean)
                    {
                        return(metaModel.GetAttributeDefinition(Token + ".@And"));
                    }

                    throw new MetaException("Must aggregate AND of booleans");

                case APIClient.Aggregate.Or:
                    if (AttributeType == AttributeType.Boolean)
                    {
                        return(metaModel.GetAttributeDefinition(Token + ".@Or"));
                    }

                    throw new MetaException("Must aggregate OR of booleans");
                }
            }

            throw new MetaException("Must aggregate multi-value attributes");
        }
 public override void PostGet(Aggregate aggregate)
 {
     base.PostGet(null); PostGetHandled = true;
 }
Exemplo n.º 45
0
 public async Task Cleanup()
 {
     await Aggregate.ScheduleDeleteAsync(SutSchedule);
 }
 public override void PostSave(Aggregate aggregate, Commit commit, Exception error)
 {
     base.PostSave(null, null, null); PostSaveHandled = true;
 }
Exemplo n.º 47
0
        private IEnumerable <object> GetClasses(Aggregate aggregate, Entity entity)
        {
            var classContexts = GetClassGenerationContexts(entity);

            foreach (var classContext in classContexts)
            {
                var contextualSuffixes = GetContextualClassAndPropertyNameSuffixes(entity);

                foreach (var contextualSuffix in contextualSuffixes)
                {
                    yield return
                        (new
                    {
                        AggregateName = aggregate.Name, ClassName = entity.Name, TableName = entity.Name, SchemaName = entity.Schema,
                        ClassNameSuffix = QueryModelSuffix, ContextualClassNameSuffix = contextualSuffix.ClassNameSuffix, entity.IsAggregateRoot,
                        entity.IsAbstract, entity.IsDerived, classContext.IsConcreteEntityBaseClass,
                        classContext.IsConcreteEntityChildClassForBase, BaseAggregateRootRelativeNamespace =
                            entity.IsDerived
                                    ? entity.BaseEntity.GetRelativeEntityNamespace(
                                entity.BaseEntity.SchemaProperCaseName(),
                                true,
                                !entity.BaseEntity.IsEdFiStandardEntity)
                            + (!entity.BaseEntity.IsAbstract
                                          ? "Base"
                                          : string.Empty)
                            + QueryModelSuffix
                                    : NotRendered,
                        PrimaryKey = new
                        {
                            ParentReference = entity.ParentAssociation != null
                                                 ? new
                            {
                                ParentClassName = entity.Parent.Name, FullyQualifiedParentClassName =
                                    $"{entity.GetRelativeAggregateNamespace(entity.Parent.IsEdFiStandardEntity ? EdFiConventions.ProperCaseName : TemplateContext.SchemaProperCaseName, isQueryModel: true)}.{entity.Parent.Name}",
                                ContextualSuffix = (classContext.IsConcreteEntityChildClassForBase
                                                                              ? "Base"
                                                                              : string.Empty)
                                                   + QueryModelSuffix
                            }
                                                 : NotRendered,
                            NonParentProperties = entity
                                                  .Identifier
                                                  .Properties
                                                  .Where(p => !p.IsFromParent)
                                                  .Select(
                                p => new
                            {
                                entity.IsAbstract,
                                NeedsOverride = entity.IsDerived && !p.IsInheritedIdentifyingRenamed,
                                CSharpDeclaredType =
                                    p.PropertyType.ToCSharp(includeNullability: true),
                                CSharpSafePropertyName =
                                    p.PropertyName.MakeSafeForCSharpClass(entity.Name)
                            })
                        },
                        Properties = GetMappedProperties(entity, contextualSuffix)
                                     .OrderBy(p => p.PropertyName)
                                     .Select(
                            p => new
                        {
                            CSharpDeclaredType = p.PropertyType.ToCSharp(includeNullability: true), PropertyName = p.PropertyName.ToMixedCase()
                        }),
                        HasOneToOnes = GetMappedNavigableOneToOnes(entity).Any(), OneToOnes = GetMappedNavigableOneToOnes(entity)
                                                                                              .Select(
                            a => new
                        {
                            OtherClassName = a.OtherEntity.Name, ClassNameSuffix = QueryModelSuffix
                        }),
                        NavigableChildren = GetMappedCollectionAssociations(entity)
                                            .Where(a => _shouldRenderEntityForSchema(a.OtherEntity))
                                            .OrderBy(a => a.Name)
                                            .SelectMany(a => GetContextualNavigableChildren(a, classContext)),
                        HasNonNavigableChildren = GetMappedExternalCollectionAssociations(entity)
                                                  .Any(a => _shouldRenderEntityForSchema(a.OtherEntity)),
                        NonNavigableChildren = GetMappedExternalCollectionAssociations(entity)
                                               .Where(a => _shouldRenderEntityForSchema(a.OtherEntity))
                                               .OrderBy(a => a.Name)
                                               .SelectMany(GetContextualNonNavigableChildren),
                        HasNonNavigableParents = GetMappedExternalParentAssociations(entity)
                                                 .Any(a => _shouldRenderEntityForSchema(a.OtherEntity)),
                        NonNavigableParents = GetMappedExternalParentAssociations(entity)
                                              .Where(a => _shouldRenderEntityForSchema(a.OtherEntity))
                                              .OrderBy(a => a.Name)
                                              .Select(
                            a => new
                        {
                            AggregateRelativeNamespace = a.OtherEntity.GetRelativeAggregateNamespace(
                                TemplateContext.SchemaProperCaseName,
                                isQueryModel: true,
                                isExtensionContext: TemplateContext.IsExtension),
                            ClassName = a.OtherEntity.Name, ClassNameSuffix = QueryModelSuffix,
                            AssociationName = a.Name
                        })
                    });
                }
            }
        }
 public override void PostGet(Aggregate aggregate)
 {
 }
Exemplo n.º 49
0
 public long SortedSetCombineAndStore(SetOperation operation, RedisKey destination, RedisKey[] keys, double[] weights = null, Aggregate aggregate = Aggregate.Sum, CommandFlags flags = CommandFlags.None)
 {
     return(Inner.SortedSetCombineAndStore(operation, ToInner(destination), ToInner(keys), weights, aggregate, flags));
 }
 public override void PostSave(Aggregate aggregate, Commit commit, Exception error)
 {
 }
Exemplo n.º 51
0
 public long SortedSetCombineAndStore(SetOperation operation, RedisKey destination, RedisKey first, RedisKey second, Aggregate aggregate = Aggregate.Sum, CommandFlags flags = CommandFlags.None)
 {
     return(Inner.SortedSetCombineAndStore(operation, ToInner(destination), ToInner(first), ToInner(second), aggregate, flags));
 }
Exemplo n.º 52
0
        public void Get_hash_code_should_be_id()
        {
            var aggregate = new Aggregate("id");

            aggregate.GetHashCode().Should().Be("id".GetHashCode());
        }
Exemplo n.º 53
0
 public ExecutionReport Cover(CoverVariation coverVariation, char strand, int minAcc, int maxAcc, Aggregate aggregate, out FunctionOutput <Output <C, I, M> > result, MaxDegreeOfParallelism maxDegreeOfParallelism)
 {
     return(genome.Cover(coverVariation, strand, minAcc, maxAcc, aggregate, out result, maxDegreeOfParallelism));
 }
Exemplo n.º 54
0
 /// <summary>
 /// Convenience extension to wrap Aggregate for numeric operations with an initial seed value of 0.
 /// </summary>
 /// <param name="e">The IEnumerable to iterate. Should be a ValueType array or collection.</param>
 /// <param name="seed">The initial value to start the sum. This must be the same type as used in the aggregate delegate.</param>
 /// <param name="a">The aggregate delegate used to perform the sum operation on the elements.</param>
 /// <param name="s">Optional. A selector delegate used to select the value from an object.</param>
 /// <returns>ValueType with the sum value.</returns>
 public static ValueType Sum(this IEnumerable e, ValueType seed, Aggregate a, Selector s)
 {
     return(Aggregate(e, seed, a, s) as ValueType);
 }
Exemplo n.º 55
0
 public ExecutionReport Map(char strand, Dictionary <string, Dictionary <char, List <I> > > references, Aggregate aggregate, out FunctionOutput <Output <C, I, M> > result, MaxDegreeOfParallelism maxDegreeOfParallelism)
 {
     return(genome.Map(references, strand, aggregate, out result, maxDegreeOfParallelism));
 }
Exemplo n.º 56
0
        // CONSIDER: configure the scanner : local info

        internal ExpressionNode Parse()
        {
            // free all nodes
            _expression = null;

            StartScan();

            int          cParens = 0;
            OperatorInfo opInfo;

            while (_token != Tokens.EOS)
            {
loop:
                Scan();

                switch (_token)
                {
                case Tokens.EOS:
                    // End of string: must be operand; force out expression;
                    // check for bomb; check nothing left on stack.

                    if (_prevOperand == Empty)
                    {
                        if (_topNode == 0)
                        {
                            // we have an empty expression
                            break;
                        }
                        // set error missing operator
                        // read the last operator info
                        opInfo = _ops[_topOperator - 1];

                        throw ExprException.MissingOperand(opInfo);
                    }
                    // collect all nodes
                    BuildExpression(Operators.priLow);
                    if (_topOperator != 1)
                    {
                        throw ExprException.MissingRightParen();
                    }
                    break;

                case Tokens.Name:
                case Tokens.Parent:
                case Tokens.Numeric:
                case Tokens.Decimal:
                case Tokens.Float:
                case Tokens.StringConst:
                case Tokens.Date:
                    ExpressionNode node = null;
                    string         str  = null;

                    /* Constants and identifiers: create leaf node */

                    if (_prevOperand != Empty)
                    {
                        // set error missing operator
                        throw ExprException.MissingOperator(new string(_text, _start, _pos - _start));
                    }

                    if (_topOperator > 0)
                    {
                        // special check for IN without parentheses

                        opInfo = _ops[_topOperator - 1];

                        if (opInfo._type == Nodes.Binop && opInfo._op == Operators.In && _token != Tokens.Parent)
                        {
                            throw ExprException.InWithoutParentheses();
                        }
                    }

                    _prevOperand = Scalar;

                    switch (_token)
                    {
                    case Tokens.Parent:
                        string relname;
                        string colname;

                        // parsing Parent[(relation_name)].column_name)
                        try
                        {
                            // expecting an '(' or '.'
                            Scan();
                            if (_token == Tokens.LeftParen)
                            {
                                //read the relation name
                                ScanToken(Tokens.Name);
                                relname = NameNode.ParseName(_text, _start, _pos);
                                ScanToken(Tokens.RightParen);
                                ScanToken(Tokens.Dot);
                            }
                            else
                            {
                                relname = null;
                                CheckToken(Tokens.Dot);
                            }
                        }
                        catch (Exception e) when(Common.ADP.IsCatchableExceptionType(e))
                        {
                            throw ExprException.LookupArgument();
                        }

                        ScanToken(Tokens.Name);
                        colname = NameNode.ParseName(_text, _start, _pos);

                        opInfo = _ops[_topOperator - 1];
                        node   = new LookupNode(_table, colname, relname);

                        break;

                    case Tokens.Name:
                        /* Qualify name now for nice error checking */

                        opInfo = _ops[_topOperator - 1];

                        /* Create tree element -                */
                        // CONSIDER: Check for reserved proc names here
                        node = new NameNode(_table, _text, _start, _pos);

                        break;

                    case Tokens.Numeric:
                        str  = new string(_text, _start, _pos - _start);
                        node = new ConstNode(_table, ValueType.Numeric, str);
                        break;

                    case Tokens.Decimal:
                        str  = new string(_text, _start, _pos - _start);
                        node = new ConstNode(_table, ValueType.Decimal, str);
                        break;

                    case Tokens.Float:
                        str  = new string(_text, _start, _pos - _start);
                        node = new ConstNode(_table, ValueType.Float, str);
                        break;

                    case Tokens.StringConst:
                        Debug.Assert(_text[_start] == '\'' && _text[_pos - 1] == '\'', "The expression contains an invalid string constant");
                        Debug.Assert(_pos - _start > 1, "The expression contains an invalid string constant");
                        // Store string without quotes..
                        str  = new string(_text, _start + 1, _pos - _start - 2);
                        node = new ConstNode(_table, ValueType.Str, str);
                        break;

                    case Tokens.Date:
                        Debug.Assert(_text[_start] == '#' && _text[_pos - 1] == '#', "The expression contains invalid date constant.");
                        Debug.Assert(_pos - _start > 2, "The expression contains invalid date constant '{0}'.");
                        // Store date without delimiters(#s)..
                        str  = new string(_text, _start + 1, _pos - _start - 2);
                        node = new ConstNode(_table, ValueType.Date, str);
                        break;

                    default:
                        Debug.Assert(false, "unhandled token");
                        break;
                    }

                    NodePush(node);
                    goto loop;

                case Tokens.LeftParen:
                    cParens++;
                    if (_prevOperand == Empty)
                    {
                        // Check for ( following IN/IFF. if not, we have a normal (.
                        // Peek: take a look at the operators stack

                        Debug.Assert(_topOperator > 0, "Empty operator stack!!");
                        opInfo = _ops[_topOperator - 1];

                        if (opInfo._type == Nodes.Binop && opInfo._op == Operators.In)
                        {
                            /* IN - handle as procedure call */

                            node = new FunctionNode(_table, "In");
                            NodePush(node);
                            /* Push operator decriptor */
                            _ops[_topOperator++] = new OperatorInfo(Nodes.Call, Operators.Noop, Operators.priParen);
                        }
                        else
                        {      /* Normal ( */
                            /* Push operator decriptor */
                            _ops[_topOperator++] = new OperatorInfo(Nodes.Paren, Operators.Noop, Operators.priParen);
                        }
                    }
                    else
                    {
                        // This is a procedure call or () qualification
                        // Force out any dot qualifiers; check for bomb

                        BuildExpression(Operators.priProc);
                        _prevOperand = Empty;
                        ExpressionNode nodebefore = NodePeek();

                        if (nodebefore == null || nodebefore.GetType() != typeof(NameNode))
                        {
                            // this is more like an assert, so we not care about "nice" exception text..
                            throw ExprException.SyntaxError();
                        }

                        /* Get the proc name */
                        NameNode name = (NameNode)NodePop();

                        // Make sure that we can bind the name as a Function
                        // then get the argument count and types, and parse arguments..

                        node = new FunctionNode(_table, name._name);

                        // check to see if this is an aggregate function
                        Aggregate agg = (Aggregate)(int)((FunctionNode)node).Aggregate;
                        if (agg != Aggregate.None)
                        {
                            node = ParseAggregateArgument((FunctionId)(int)agg);
                            NodePush(node);
                            _prevOperand = Expr;
                            goto loop;
                        }

                        NodePush(node);
                        _ops[_topOperator++] = new OperatorInfo(Nodes.Call, Operators.Noop, Operators.priParen);
                    }
                    goto loop;

                case Tokens.RightParen:
                {
                    /* Right parentheses: Build expression if we have an operand. */
                    if (_prevOperand != Empty)
                    {
                        BuildExpression(Operators.priLow);
                    }

                    /* We must have Tokens.LeftParen on stack. If no operand, must be procedure call. */
                    if (_topOperator <= 1)
                    {
                        // set error, syntax: too many right parens..
                        throw ExprException.TooManyRightParentheses();
                    }

                    Debug.Assert(_topOperator > 1, "melformed operator stack.");
                    _topOperator--;
                    opInfo = _ops[_topOperator];

                    if (_prevOperand == Empty && opInfo._type != Nodes.Call)
                    {
                        // set error, syntax: missing operand.
                        throw ExprException.MissingOperand(opInfo);
                    }

                    Debug.Assert(opInfo._priority == Operators.priParen, "melformed operator stack.");

                    if (opInfo._type == Nodes.Call)
                    {
                        /* add argument to the function call. */

                        if (_prevOperand != Empty)
                        {
                            // read last function argument
                            ExpressionNode argument = NodePop();

                            /* Get the procedure name and append argument */
                            Debug.Assert(_topNode > 0 && NodePeek().GetType() == typeof(FunctionNode), "The function node should be created on '('");

                            FunctionNode func = (FunctionNode)NodePop();
                            func.AddArgument(argument);
                            func.Check();
                            NodePush(func);
                        }
                    }
                    else
                    {
                        /* Normal parentheses: create tree node */
                        // Construct & Put the Nodes.Paren node on node stack
                        node = NodePop();
                        node = new UnaryNode(_table, Operators.Noop, node);
                        NodePush(node);
                    }

                    _prevOperand = Expr;
                    cParens--;
                    goto loop;
                }

                case Tokens.ListSeparator:
                {
                    /* Comma encountered: Must be operand; force out subexpression */

                    if (_prevOperand == Empty)
                    {
                        throw ExprException.MissingOperandBefore(",");
                    }

                    /* We are be in a procedure call */

                    /* build next argument */
                    BuildExpression(Operators.priLow);

                    opInfo = _ops[_topOperator - 1];

                    if (opInfo._type != Nodes.Call)
                    {
                        throw ExprException.SyntaxError();
                    }

                    ExpressionNode argument2 = NodePop();

                    /* Get the procedure name */

                    FunctionNode func = (FunctionNode)NodePop();

                    func.AddArgument(argument2);

                    NodePush(func);

                    _prevOperand = Empty;

                    goto loop;
                }

                case Tokens.BinaryOp:
                    if (_prevOperand == Empty)
                    {
                        /* Check for unary plus/minus */
                        if (_op == Operators.Plus)
                        {
                            _op = Operators.UnaryPlus;
                            // fall through to UnaryOperator;
                        }
                        else if (_op == Operators.Minus)
                        {
                            /* Unary minus */
                            _op = Operators.Negative;
                            // fall through to UnaryOperator;
                        }
                        else
                        {
                            // Error missing operand:
                            throw ExprException.MissingOperandBefore(Operators.ToString(_op));
                        }
                    }
                    else
                    {
                        _prevOperand = Empty;

                        /* CNSIDER: If we are going to support BETWEEN Translate AND to special BetweenAnd if it is. */

                        /* Force out to appropriate precedence; push operator. */

                        BuildExpression(Operators.Priority(_op));

                        // PushOperator descriptor
                        _ops[_topOperator++] = new OperatorInfo(Nodes.Binop, _op, Operators.Priority(_op));
                        goto loop;
                    }

                    goto
                case Tokens.UnaryOp;     // fall through to UnaryOperator;

                case Tokens.UnaryOp:
                    /* Must be no operand. Push it. */
                    _ops[_topOperator++] = new OperatorInfo(Nodes.Unop, _op, Operators.Priority(_op));
                    goto loop;

                case Tokens.ZeroOp:
                    // check the we have operator on the stack
                    if (_prevOperand != Empty)
                    {
                        // set error missing operator
                        throw ExprException.MissingOperator(new string(_text, _start, _pos - _start));
                    }

                    // PushOperator descriptor
                    _ops[_topOperator++] = new OperatorInfo(Nodes.Zop, _op, Operators.priMax);
                    _prevOperand         = Expr;
                    goto loop;

                case Tokens.Dot:
                    //if there is a name on the stack append it.
                    ExpressionNode before = NodePeek();

                    if (before != null && before.GetType() == typeof(NameNode))
                    {
                        Scan();

                        if (_token == Tokens.Name)
                        {
                            NameNode nameBefore = (NameNode)NodePop();
                            string   newName    = nameBefore._name + "." + NameNode.ParseName(_text, _start, _pos);
                            NodePush(new NameNode(_table, newName));
                            goto loop;
                        }
                    }
                    // fall through to default
                    goto default;

                default:
                    throw ExprException.UnknownToken(new string(_text, _start, _pos - _start), _start + 1);
                }
            }
            goto end_loop;
end_loop:
            Debug.Assert(_topNode == 1 || _topNode == 0, "Invalid Node Stack");
            _expression = _nodeStack[0];

            return(_expression);
        }
Exemplo n.º 57
0
 public Task <long> SortedSetCombineAndStoreAsync(SetOperation operation, RedisKey destination, RedisKey[] keys, double[] weights = null, Aggregate aggregate = Aggregate.Sum, CommandFlags flags = CommandFlags.None)
 {
     return(this.db.SortedSetCombineAndStoreAsync(operation, destination, keys, weights, aggregate, flags));
 }
Exemplo n.º 58
0
        public void LoadWithInclude()
        {
            using(GetNewServer())
            using (var store = new DocumentStore{Url = "http://localhost:8079"}.Initialize())
            {

                var aggregate = new Aggregate
                                    {
                                        Name = "First"
                                    };

                using (var session = store.OpenSession())
                {
                    session.Advanced.UseOptimisticConcurrency = true;
                    session.Store(aggregate); 
                    session.SaveChanges();
                }

                var root = new Root
                            {
                                Bridge = new Bridge
                                            {
                                                Aggregates = new List<string>
                                                                {
                                                                    aggregate.Id
                                                                }
                                            }
                            };

                using (var session = store.OpenSession())
                {
                    session.Advanced.UseOptimisticConcurrency = true;
                    session.Store(root); session.SaveChanges();
                }

                using (var session = store.OpenSession())
                {
                    var item = session.Load<Aggregate>(1);
                    Assert.NotNull(item);
                }

                using (var session = store.OpenSession())
                {
                    session.Advanced.UseOptimisticConcurrency = true;
                    var query = session
                        .Include("Bridge.Aggregates")
                        .Load<Root>(1);

                    Assert.NotNull(query);
                }

                using (var session = store.OpenSession())
                {
                    session.Advanced.UseOptimisticConcurrency = true;
                    var query = session
                        .Include("Bridge.Aggregates")
                        .Load<Root>("roots/1");
                    var loaded = session.Load<Aggregate>("aggregates/1");

                    Assert.NotNull(query);
                    Assert.Equal(1, session.Advanced.NumberOfRequests);
                }

                using (var session = store.OpenSession())
                {
                    session.Advanced.UseOptimisticConcurrency = true;
                    var query = session
                        .Include("Bridge.Aggregates")
                        .Load<Root>(1);
                    var loaded = session.Load<Aggregate>("aggregates/1");

                    Assert.NotNull(query);
                    Assert.Equal(1, session.Advanced.NumberOfRequests);
                }
            }
        }
Exemplo n.º 59
0
 public void SaveChanges(Aggregate aggregate)
 {
     SaveEvents(new AggregateKey(aggregate.GetType(), aggregate.AggregateId), aggregate.Revision, aggregate.UncommittedChanges());
     aggregate.ClearUncommittedEvents();
 }
Exemplo n.º 60
-1
        static void Main()
        {
            string decorationLine = new string('-', Console.WindowWidth);
            Console.Write(decorationLine);
            Console.WriteLine("***Example for the 'Iterator' design pattern***");
            Console.Write(decorationLine);

            IAggregate<int> fibonacciNumbersToFifty = new Aggregate<int>();
            fibonacciNumbersToFifty.AddItem(0);
            fibonacciNumbersToFifty.AddItem(1);
            fibonacciNumbersToFifty.AddItem(1);
            fibonacciNumbersToFifty.AddItem(2);
            fibonacciNumbersToFifty.AddItem(3);
            fibonacciNumbersToFifty.AddItem(5);
            fibonacciNumbersToFifty.AddItem(8);
            fibonacciNumbersToFifty.AddItem(13);
            fibonacciNumbersToFifty.AddItem(21);
            fibonacciNumbersToFifty.AddItem(34);

            Console.WriteLine("Fibonacci numbers to 50:");
            foreach (int number in fibonacciNumbersToFifty.GetAll())
            {
                Console.WriteLine(number);
            }
        }