Esempio n. 1
0
        static void Main(string[] args)
        {
            Console.WriteLine("Delegate Example 4:");
            Console.WriteLine("Using the FCL-defined Comparison<T> delegate as");
            Console.WriteLine(
                "an argument to the List<T>.Sort(Comparison<T> comp) method");

            DomainObjectStore store = new DomainObjectStore();

            // Use override of Sort method that takes a Comparison<T> delegate.
            // The point here is that the .Net Framework has a pre-defined delegate
            // Comparison<T> so we don't define a new delegate type, but use
            // an existing one. Then the List<T> class has a
            // Sort(Comparison<T> comp) method overload that can use the
            // delegate to sort. Compare this to the Sort(IComparer c)
            // and you can see that this is a bit simpler than creating a whole
            // new class that just implements the IComparer.Compare() method.
            store.People.Sort(FirstNameComparison);

            foreach (var item in store.People)
            {
                Console.WriteLine("\t" + item);
            }

            Console.WriteLine("Press <Enter> to quit the program:");
            Console.ReadLine();
        }
Esempio n. 2
0
        public async Task CatchSnapshotStoreError()
        {
            var provider = new ServiceCollection()
                           .AddLogging()
                           .AddMemoryCache()
                           .BuildServiceProvider();

            var config = new ConfigurationBuilder()
                         .AddInMemoryCollection(new[] { new KeyValuePair <string, string>("MemoryCache:Local:Duration", "00:00:05") })
                         .Build();

            var logger   = provider.GetRequiredService <ILogger <DomainObjectStore> >();
            var memCache = provider.GetRequiredService <IMemoryCache>();

            var eventStore = new Mock <IEventStore>(MockBehavior.Strict);

            var snapshotStore = new Mock <ISnapshotStore>(MockBehavior.Strict);

            snapshotStore.Setup(s => s.GetSnapshot <ConfigEnvironmentList>(It.IsAny <string>(), It.IsAny <long>()))
            .Throws <Exception>()
            .Verifiable();

            var store = new DomainObjectStore(eventStore.Object,
                                              snapshotStore.Object,
                                              memCache,
                                              config,
                                              logger);

            var result = await store.ReplayObject <ConfigEnvironmentList>();

            Assert.True(result.IsError);

            snapshotStore.Verify();
        }
Esempio n. 3
0
        public async Task CachedItemBeyondMaxVersionReplayed()
        {
            var provider = new ServiceCollection()
                           .AddLogging()
                           .AddMemoryCache()
                           .BuildServiceProvider();

            var config = new ConfigurationBuilder()
                         .AddInMemoryCollection(new[] { new KeyValuePair <string, string>("MemoryCache:Local:Duration", "00:00:10") })
                         .Build();

            var logger   = provider.GetRequiredService <ILogger <DomainObjectStore> >();
            var memCache = provider.GetRequiredService <IMemoryCache>();

            var eventStore = new Mock <IEventStore>(MockBehavior.Strict);

            eventStore.Setup(es => es.ReplayEventsAsStream(
                                 It.IsAny <Func <(StoredEvent, DomainEvent), bool> >(),
                                 It.IsAny <int>(),
                                 It.IsAny <StreamDirection>(),
                                 It.IsAny <long>()))
            .Returns(Task.CompletedTask)
            .Verifiable();

            var snapshotStore = new Mock <ISnapshotStore>(MockBehavior.Strict);

            snapshotStore.Setup(s => s.GetSnapshot <ConfigEnvironmentList>(It.IsAny <string>(), It.IsAny <long>()))
            .ReturnsAsync(() => Result.Error <DomainObjectSnapshot>("no snapshot found", ErrorCode.DbQueryError))
            .Verifiable("snapshot not retrieved");

            var item = new ConfigEnvironmentList();

            item.ApplyEvent(new ReplayedEvent
            {
                DomainEvent = new EnvironmentCreated(new EnvironmentIdentifier("Foo", "Bar")),
                UtcTime     = DateTime.UtcNow,
                Version     = 4711
            });

            memCache.Set(nameof(ConfigEnvironmentList), item);

            var store = new DomainObjectStore(eventStore.Object,
                                              snapshotStore.Object,
                                              memCache,
                                              config,
                                              logger);

            var result = await store.ReplayObject <ConfigEnvironmentList>(42);

            Assert.False(result.IsError, "result.IsError");
            Assert.NotNull(result.Data);

            eventStore.Verify();
            snapshotStore.Verify();
        }
Esempio n. 4
0
        static void Main(string[] args)
        {
            Console.WriteLine("LINQ Lab:");
            DomainObjectStore store = new DomainObjectStore();

            store.People.PrintToConsole();



            Console.WriteLine("Press <Enter> to quit the application");
            Console.ReadLine();
        }
Esempio n. 5
0
        static void Main(string[] args)
        {
            Console.WriteLine("Lambda Expression Sorting:");
            Console.WriteLine("Using the FCL-defined Comparison<T> delegate as");
            Console.WriteLine(
                "an argument to the List<T>.Sort(Comparison<T> comp) method");

            DomainObjectStore store = new DomainObjectStore();

            // Use override of Sort method that takes a Comparison<T> delegate.
            // The point here is that the .Net Framework has a pre-defined delegate
            // Comparison<T> so we don't define a new delegate type, but use
            // an existing one. Then the List<T> class has a
            // Sort(Comparison<T> comp) method overload that can use the
            // delegate to sort. Compare this to the Sort(IComparer c)
            // and you can see that this is a bit simpler than creating a whole
            // new class that just implements the IComparer.Compare() method.
            store.People.Sort((p1, p2) =>
                              String.Compare(p1.FirstLastName, p2.FirstLastName));

            foreach (var item in store.People)
            {
                Console.WriteLine("\t" + item);
            }

            Console.WriteLine("Example of Variable Capture with Lambdas");
            while (true)
            {
                Console.WriteLine("Enter a partial name and <Enter> to search, or just <Enter> to quit:");
                string criterion = Console.ReadLine();
                if (String.IsNullOrWhiteSpace(criterion))
                {
                    break;
                }

                Person person = store.People
                                .Find(p => p.FirstLastName.ToUpper().Contains(criterion.ToUpper()));
                if (person == null)
                {
                    Console.WriteLine("(No matches)");
                }
                else
                {
                    Console.WriteLine(person.FirstLastName);
                }
            }


            //Console.WriteLine("Press <Enter> to quit the program:");
            //Console.ReadLine();
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Extension Method Lab:");
            Console.WriteLine("\r\nPrint using foreach loop:");

            DomainObjectStore store = new DomainObjectStore();

            foreach (Show s in store.Shows)
            {
                Console.WriteLine(s.Display());
            }

            Console.WriteLine("Press <Enter> to quit the application");
            Console.ReadLine();
        }
Esempio n. 7
0
        public async Task CachedItemExpires()
        {
            var provider = new ServiceCollection()
                           .AddLogging()
                           .AddMemoryCache()
                           .BuildServiceProvider();

            var config = new ConfigurationBuilder()
                         .AddInMemoryCollection(new[] { new KeyValuePair <string, string>("MemoryCache:Local:Duration", "00:00:03") })
                         .Build();

            var logger   = provider.GetRequiredService <ILogger <DomainObjectStore> >();
            var memCache = provider.GetRequiredService <IMemoryCache>();

            var eventStore = new Mock <IEventStore>(MockBehavior.Strict);

            eventStore.Setup(es => es.ReplayEventsAsStream(
                                 It.IsAny <Func <(StoredEvent, DomainEvent), bool> >(),
                                 It.IsAny <int>(),
                                 It.IsAny <StreamDirection>(),
                                 It.IsAny <long>()))
            .Returns(Task.CompletedTask)
            .Verifiable();

            var snapshotStore = new Mock <ISnapshotStore>(MockBehavior.Strict);

            snapshotStore.Setup(s => s.GetSnapshot <ConfigEnvironmentList>(It.IsAny <string>(), It.IsAny <long>()))
            .ReturnsAsync(() => Result.Error <DomainObjectSnapshot>(string.Empty, ErrorCode.DbQueryError))
            .Verifiable();

            var store = new DomainObjectStore(eventStore.Object,
                                              snapshotStore.Object,
                                              memCache,
                                              config,
                                              logger);

            await store.ReplayObject <ConfigEnvironmentList>();

            Assert.True(memCache.TryGetValue(nameof(ConfigEnvironmentList), out _), "item not cached after replay");

            await Task.Delay(TimeSpan.FromSeconds(5));

            Assert.False(memCache.TryGetValue(nameof(ConfigEnvironmentList), out _), "item still in cache after duration");

            eventStore.Verify();
            snapshotStore.Verify();
        }
Esempio n. 8
0
        public async Task ItemRetrievedFromEventStore()
        {
            var provider = new ServiceCollection()
                           .AddLogging()
                           .AddMemoryCache()
                           .BuildServiceProvider();

            var config = new ConfigurationBuilder()
                         .AddInMemoryCollection(new[] { new KeyValuePair <string, string>("MemoryCache:Local:Duration", "00:00:10") })
                         .Build();

            var logger   = provider.GetRequiredService <ILogger <DomainObjectStore> >();
            var memCache = provider.GetRequiredService <IMemoryCache>();

            var eventStore = new Mock <IEventStore>(MockBehavior.Strict);

            eventStore.Setup(es => es.ReplayEventsAsStream(
                                 It.IsAny <Func <(StoredEvent, DomainEvent), bool> >(),
                                 It.IsAny <int>(),
                                 It.IsAny <StreamDirection>(),
                                 It.IsAny <long>()))
            .Returns(Task.CompletedTask)
            .Verifiable();

            var snapshotStore = new Mock <ISnapshotStore>(MockBehavior.Strict);

            snapshotStore.Setup(s => s.GetSnapshot <ConfigEnvironmentList>(It.IsAny <string>(), It.IsAny <long>()))
            .ReturnsAsync(() => Result.Error <DomainObjectSnapshot>(string.Empty, ErrorCode.DbQueryError))
            .Verifiable();

            var store = new DomainObjectStore(eventStore.Object,
                                              snapshotStore.Object,
                                              memCache,
                                              config,
                                              logger);

            var result = await store.ReplayObject <ConfigEnvironmentList>();

            Assert.False(result.IsError, "result.IsError");
            Assert.NotNull(result.Data);

            eventStore.Verify();
            snapshotStore.Verify();
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            Console.WriteLine("Delegate Example 5:");
            Console.WriteLine("Multicast Delegates");

            DomainObjectStore store = new DomainObjectStore();

            var people = store.People;

            Action <Person> act1 = null;

            act1 += PrintName;
            act1 += PrintAge;

            Console.WriteLine("\r\nPrintName and Age:");
            act1(people[0]);

            Console.WriteLine("\r\nSame method can be invoked multiple times:");
            act1 += PrintName;
            act1 += PrintAge;
            act1(people[1]);

            Console.WriteLine("\r\nCan remove method from invocation list:");
            act1 -= PrintName;
            act1(people[0]);

            Console.WriteLine("\r\nWhen a method in the invocation list fails:");
            Action <Person> act2 = null;

            act2 += PrintName;
            act2 += BadMethod;
            act2 += PrintAge;
            try
            {
                act2(people[1]);
            }
            catch (ApplicationException)
            {
                Console.WriteLine("When exception is thrown, "
                                  + "delegate stops processing methods on the invocation list!");
            }

            Console.WriteLine("\r\nManually iterating through invocation list:");
            Console.WriteLine("Allows handling exceptions or retrieving return values");
            foreach (Action <Person> m in act2.GetInvocationList())
            {
                try
                {
                    m(people[1]);
                }
                catch (ApplicationException ae)
                {
                    Console.WriteLine(ae.Message);
                }
            }

            Console.WriteLine("\r\nA Delegate with an empty invocation list");
            Console.WriteLine("throws an exception if invoked.");
            act2 -= PrintName;
            act2 -= BadMethod;
            act2 -= PrintAge;
            // act2(people[0]);  // this would throw an exception, since we
            // need to check for empty invocation list
            // if it might be empty.
            if (act2 != null)
            {
                act2(people[0]);
            }

            Console.WriteLine("\r\nPress <Enter> to quit the program:");
            Console.ReadLine();
        }