public void ConvertingEvents()
 {
     string received = "";
                 var names = new[] { "wE", "hOpE", "yOU", "aRe", "eNJoyIng", "tHiS" };
                 names.ToObservable().Select(x => x.ToLower()).Subscribe(x => received += x + " ");
                 Assert.AreEqual("we hope you are enjoying this ", received);
 }
 public void CheckingEverything()
 {
     bool? received = null;
                 var names = new[] { 2, 4, 6, 8 };
                 names.ToObservable().All(x => x.IsEven()).Subscribe(x => received = x);
                 Assert.AreEqual(true, received);
 }
 public void ComposableAddition()
 {
     int received = 0;
                 var numbers = new[] { 10, 100, 1000 };
                 numbers.ToObservable().Sum().Subscribe(x => received = x);
                 Assert.AreEqual(1110, received);
 }
        public void InvalidInputData()
        {
            var input = new[]
            {
                new Envelope(DateTimeOffset.MinValue, DateTimeOffset.MinValue, null, null, null, null, null),
                new Envelope(DateTimeOffset.MinValue, DateTimeOffset.MinValue, null, null, typeof(string).GetTypeIdentifier(), null, null),
                new Envelope(DateTimeOffset.MinValue, DateTimeOffset.MinValue, null, null, null, null, "A"),
                new Envelope(DateTimeOffset.MinValue, DateTimeOffset.MinValue, null, null, typeof(int).GetTypeIdentifier(), null, null),
            };

            IEnumerable<string> stringCollection;

            using (var playback = new Playback())
            {
                ((IPlaybackConfiguration)playback).AddInput(() => input.ToObservable(), typeof(EnvelopeTypeMap));

                var stringStream = playback.GetObservable<string>();

                stringCollection = playback.BufferOutput(stringStream);

                playback.Run();
            }

            var strings = stringCollection.ToArray();
            Assert.IsNotNull(strings);
            Assert.AreEqual(0, strings.Length);
        }
        public void DeserializeMixedStream()
        {
            var input = new[]
            {
                new SimpleEnvelope("JSON", Guid.Parse("daf0be6e-da1e-5a6a-0d49-69782745c885"), Encoding.UTF8.GetBytes(@"""A""")),
                new SimpleEnvelope("JSON", Guid.Parse("daf0be6e-da1e-5a6a-0d49-69782745c885"), new byte[0]),
                new SimpleEnvelope("BOND_V1", new Guid("daf0be6e-da1e-5a6a-0d49-69782745c886"), new byte[] { 41, 1, 65, 0 }),
            };

            IEnumerable<TestBondClass> testBondClassCollection;
            IEnumerable<string> stringCollection;

            using (var playback = new Playback())
            {
                ((IPlaybackConfiguration)playback).AddInput(
                    () => input.ToObservable(),
                    typeof(GeneralPartitionableTypeMap));

                var testBondClassStream = playback.GetObservable<TestBondClass>();
                var stringStream = playback.GetObservable<string>();

                testBondClassCollection = playback.BufferOutput(testBondClassStream);
                stringCollection = playback.BufferOutput(stringStream);

                playback.Run();
            }

            var bondObjects = testBondClassCollection.ToArray();
            Assert.IsNotNull(bondObjects);
            Assert.AreEqual(1, bondObjects.Length);

            var strings = stringCollection.ToArray();
            Assert.IsNotNull(strings);
            Assert.AreEqual(1, strings.Length);
        }
Example #6
0
        public void Works()
        {
            var values = new[]
                {
                    new Tuple<string, string>("faces", "[]"),
                    new Tuple<string, string>("faces", "[{ \"foo\": \"fools\", \"confidence\": -1.503985\"}]"),
                    new Tuple<string, string>("navdata", "[{ \"foo\": \"fools\", \"altitudeMeters\": 0.0\"}]"),
                    new Tuple<string, string>("faces", "[{ \"foo\": \"fools\", \"confidence\": 0.937\"}]"),
                    new Tuple<string, string>("navdata", "[{ \"foo\": \"fools\", \"altitudeMeters\": 0.2\"}]"),
                    new Tuple<string, string>("navdata", "[{ \"foo\": \"fools\", \"altitudeMeters\": 0.4\"}]"),
                    new Tuple<string, string>("faces", "[{ \"foo\": \"fools\", \"confidence\": 1.01\"}]"),
                    new Tuple<string, string>("navdata", "[{ \"foo\": \"fools\", \"altitudeMeters\": 0.6\"}]"),
                    new Tuple<string, string>("faces", "[{ \"foo\": \"fools\", \"confidence\": 1.20\"}]"),
                    new Tuple<string, string>("navdata", "[{ \"foo\": \"fools\", \"altitudeMeters\": 0.8\"}]"),
                    new Tuple<string, string>("navdata", "[{ \"foo\": \"fools\", \"altitudeMeters\": 1.0\"}]"),
                    new Tuple<string, string>("faces", "[{ \"foo\": \"fools\", \"confidence\": 1.25\"}]"),
                    new Tuple<string, string>("navdata", "[{ \"foo\": \"fools\", \"altitudeMeters\": 1.2\"}]"),
                    new Tuple<string, string>("navdata", "[{ \"foo\": \"fools\", \"altitudeMeters\": 1.4\"}]"),
                    new Tuple<string, string>("faces", "[{ \"foo\": \"fools\", \"confidence\": 1.30\"}]"),
                    new Tuple<string, string>("navdata", "[{ \"foo\": \"fools\", \"altitudeMeters\": 1.6\"}]"),
                };

            var drone = new DroneSample();
            var results = drone.Execute(values.ToObservable()).ToEnumerable();
            var list = results.ToList();
            Assert.IsTrue(list.Any());
        }
 public void CreatingAMoreRelevantEventStream()
 {
     string received = "";
             var mouseXMovements = new[] { 100, 200, 150 };
             IObservable<int> relativemouse = mouseXMovements.ToObservable().Select((int x) => x - ___);
             relativemouse.Subscribe(x => received += x + ", ");
             Assert.AreEqual("50, 150, 100, ", received);
 }
Example #8
0
        private static void EnumerableToObservable()
        {
            Console.WriteLine("----- Enumerable to Observable ----");

            IEnumerable<string> names = new[] { "Shira", "Yonatan", "Gabi", "Tamir" };
            IObservable<string> observable = names.ToObservable();

            observable.SubscribeConsole("names");
        }
Example #9
0
        private static void EnumerableToObservable()
        {
            Demo.DisplayHeader("Enumerable to Observable");

            IEnumerable<string> names = new[] { "Shira", "Yonatan", "Gabi", "Tamir" };
            IObservable<string> observable = names.ToObservable();

            observable.SubscribeConsole("names");
        }
        public void FilterBursts_SeuquenceOf10AndBurstSize5_TwoEmissions()
        {
            var seqeucneSize = 10;
            var burstSize = 5;
            var expected = new[] { 0, 5 };
            var xs = Observable.Range(0, seqeucneSize);

            xs.FilterBursts(burstSize)
                .AssertEqual(expected.ToObservable());
        }
        public void CacheShouldEatExceptionsAndMarshalThemToObservable()
        {
            /* This is a bit tricky:
             *
             * 5,2 complete at t=1000 simultaneously
             * 10,0 get queued up, 0 fails immediately (delay() doesn't delay the OnError),
             *    so 10 completes at t=2000
             * The 7 completes at t=3000
             */
            var input = new[] { 5, 2, 10, 0/*boom!*/, 7 };
            var sched = new TestScheduler();

            Observable.Throw<int>(new Exception("Foo")).Subscribe(x => {
                Console.WriteLine(x);
            }, ex => {
                Console.WriteLine(ex);
            }, () => {
                Console.WriteLine("Completed");
            });

            var delay = TimeSpan.FromSeconds(1.0);
            var fixture = new ObservableAsyncMRUCache<int, int>(x =>
                (x == 0 ? Observable.Throw<int>(new Exception("Boom!")) : Observable.Return(10 * x)).Delay(delay, sched), 5, 2, sched);

            Exception exception = null;
            int completed = 0;
            input.ToObservable()
                .SelectMany(x => (IObservable<int>)fixture.AsyncGet(x))
                .Subscribe(x => {
                    this.Log().InfoFormat("Result = {0}", x);
                    completed++;
                }, ex => exception = exception ?? ex);

            sched.RunTo(sched.FromTimeSpan(TimeSpan.FromMilliseconds(500)));
            Assert.IsNull(exception);
            Assert.AreEqual(0, completed);

            sched.RunTo(sched.FromTimeSpan(TimeSpan.FromMilliseconds(1500)));
            Assert.IsNotNull(exception);
            Assert.AreEqual(2, completed);

            sched.RunTo(sched.FromTimeSpan(TimeSpan.FromMilliseconds(7500)));
            Assert.IsNotNull(exception);
            Assert.AreEqual(4, completed);
            this.Log().Info(exception);
        }
Example #12
0
        public void ObservableCanExecuteShouldShowUpInCommand()
        {
            (new TestScheduler()).With(sched => {
                var input = new[] { true, true, false, true, false, false };
                var expected = new[] { true, false, true, false };

                var inputObs = input.ToObservable().Multicast(new Subject<bool>());
                var fixture = new ReactiveCommand(inputObs);

                var results = new List<bool>();
                fixture.CanExecuteObservable.Subscribe(x => results.Add(x));
                inputObs.Connect();
                sched.Start();

                expected.AssertSequenceAreEqual(results);
            });
        }
        public void AsyncGetTest()
        {
            var input = new[] { 1, 1, 1, 1, 1 };
            var sched = new TestScheduler();

            var delay = TimeSpan.FromSeconds(1.0);
            var fixture = new ObservableAsyncMRUCache<int, int>(x => Observable.Return(x*5).Delay(delay, sched), 5, 2, null, sched);

            int result = 0;
            input.ToObservable(sched).SelectMany<int, int>(x => (IObservable<int>)fixture.AsyncGet(x)).Subscribe(x => result += x);

            sched.AdvanceTo(sched.FromTimeSpan(TimeSpan.FromMilliseconds(500)));
            Assert.Equal(0, result);

            sched.AdvanceTo(sched.FromTimeSpan(TimeSpan.FromMilliseconds(1200)));
            Assert.Equal(25, result);

            sched.Start();
            Assert.Equal(25, result);
        }
        public void EnsureCacheDoesNotBlockOnRelease()
        {
            var input = new[] { 1, 2 };
            var sched = new TestScheduler();
            var releaseCount = 0;

            var delay = TimeSpan.FromSeconds(1.0);
            //set the cache to only hold one value, which forces an eviction of an inflight request from the inner cache
            var fixture = new ObservableAsyncMRUCache<int, int>(x => Observable.Return(x * 5).Delay(delay, sched), 1, 2, x=>releaseCount+=1, sched);


            int result = 0;
            input.ToObservable(sched).SelectMany<int, int>(x => (IObservable<int>)fixture.AsyncGet(x)).Subscribe(x => result += x);

            sched.AdvanceTo(sched.FromTimeSpan(TimeSpan.FromMilliseconds(1000)));
            Assert.Equal(0,releaseCount);
            sched.AdvanceTo(sched.FromTimeSpan(TimeSpan.FromMilliseconds(1001)));
            Assert.Equal(1, releaseCount);
           

        }
        public async Task CanRetrieveAndCacheGitIgnores()
        {
            var templates = new[] { "dotnet", "peanuts", "bloomcounty" };
            var apiClient = Substitute.For<IApiClient>();
            apiClient.GetGitIgnoreTemplates().Returns(templates.ToObservable());
            var cache = new InMemoryBlobCache();
            var modelService = new ModelService(apiClient, cache, Substitute.For<IAvatarProvider>());

            var fetched = await modelService.GetGitIgnoreTemplates();

            Assert.Equal(4, fetched.Count);
            Assert.Equal("None", fetched[0].Name);
            Assert.Equal("dotnet", fetched[1].Name);
            Assert.Equal("peanuts", fetched[2].Name);
            Assert.Equal("bloomcounty", fetched[3].Name);
            var cached = await cache.GetObject<IReadOnlyList<string>>("gitignores");
            Assert.Equal(3, cached.Count);
            Assert.Equal("dotnet", cached[0]);
            Assert.Equal("peanuts", cached[1]);
            Assert.Equal("bloomcounty", cached[2]);
        }
        public void DeserializeMixedStream()
        {
            var integerIdentifier = typeof(int).GetTypeIdentifier();
            var stringIdentifier = typeof(string).GetTypeIdentifier();

            var input = new[]
            {
                new Envelope(DateTimeOffset.MinValue, DateTimeOffset.MinValue, "A", "1", stringIdentifier, null, "Hello"),
                new Envelope(DateTimeOffset.MinValue, DateTimeOffset.MinValue, "B", "2", "", null, "Hello"),
                new Envelope(DateTimeOffset.MinValue, DateTimeOffset.MinValue, "B", "2", integerIdentifier, null, 10),
            };

            IEnumerable<int> intCollection;
            IEnumerable<string> stringCollection;

            using (var playback = new Playback())
            {
                ((IPlaybackConfiguration)playback).AddInput(
                    () => input.ToObservable(),
                    typeof(EnvelopeTypeMap));

                var intStream = playback.GetObservable<int>();
                var stringStream = playback.GetObservable<string>();

                intCollection = playback.BufferOutput(intStream);
                stringCollection = playback.BufferOutput(stringStream);

                playback.Run();
            }

            var bondObjects = intCollection.ToArray();
            Assert.IsNotNull(bondObjects);
            Assert.AreEqual(1, bondObjects.Length);
            Assert.AreEqual(10, bondObjects[0]);

            var strings = stringCollection.ToArray();
            Assert.IsNotNull(strings);
            Assert.AreEqual(1, strings.Length);
            Assert.AreEqual("Hello", strings[0]);
        }
Example #17
0
        public async Task CanRetrieveAndCacheGitIgnores()
        {
            var data = new[] { "dotnet", "peanuts", "bloomcounty" };
            var apiClient = Substitute.For<IApiClient>();
            apiClient.GetGitIgnoreTemplates().Returns(data.ToObservable());
            var cache = new InMemoryBlobCache();
            var modelService = new ModelService(apiClient, cache, Substitute.For<IAvatarProvider>());

            var fetched = await modelService.GetGitIgnoreTemplates().ToList();

            Assert.Equal(3, fetched.Count);
            for (int i = 0; i < data.Length; i++)
                Assert.Equal(data[i], fetched[i].Name);

            var indexKey = CacheIndex.GitIgnoresPrefix;
            var cached = await cache.GetObject<CacheIndex>(indexKey);
            Assert.Equal(3, cached.Keys.Count);

            var items = await cache.GetObjects<GitIgnoreCacheItem>(cached.Keys).Take(1);
            for (int i = 0; i < data.Length; i++)
                Assert.Equal(data[i], items[indexKey + "|" + data[i]].Name);
        }
        public void CacheShouldQueueOnceWeHitOurConcurrentLimit()
        {
            var input = new[] { 1, 2, 3, 4, 1 };
            var sched = new TestScheduler();

            var delay = TimeSpan.FromSeconds(1.0);
            var fixture = new ObservableAsyncMRUCache<int, int>(x => Observable.Return(x*5).Delay(delay, sched), 5, 2, null, sched);

            int result = 0;
            input.ToObservable(sched).SelectMany<int, int>(x => (IObservable<int>)fixture.AsyncGet(x)).Subscribe(x => result += x);

            sched.AdvanceTo(sched.FromTimeSpan(TimeSpan.FromMilliseconds(500)));
            Assert.Equal(0, result);

            sched.AdvanceTo(sched.FromTimeSpan(TimeSpan.FromMilliseconds(1500)));
            Assert.Equal(1*5 + 2*5 + 1*5, result);

            sched.AdvanceTo(sched.FromTimeSpan(TimeSpan.FromMilliseconds(2500)));
            Assert.Equal(1*5 + 2*5 + 3*5 + 4*5 + 1*5, result);

            sched.AdvanceTo(sched.FromTimeSpan(TimeSpan.FromMilliseconds(5000)));
            Assert.Equal(1*5 + 2*5 + 3*5 + 4*5 + 1*5, result);
        }
Example #19
0
        static void Main(string[] args)
        {
            var users = new[] {
                new Attempt { UserName = "Dru", IP = "1" },
                new Attempt { UserName = "Keith", IP = "1" },
                new Attempt { UserName = "Keith", IP = "2" },
                new Attempt { UserName = "Keith", IP = "3" },
                new Attempt { UserName = "Dru", IP = "3" },
                new Attempt { UserName = "Tim", IP = "4" },
                new Attempt { UserName = "Dru", IP = "3" }
            }.Do(a => Thread.Sleep(300));

            var obs = users.ToObservable(Scheduler.ThreadPool);
                //.Do(n => Thread.Sleep(n * 1));

            var h4x0rz =
                from n in obs
                group n by n.UserName into g
                from b in g.BufferWithTime(TimeSpan.FromSeconds(1))
                where b.Count > 2
                select new
                {
                    UserName = g.Key,
                    IPs = string.Join(" ", b.Select(a => a.IP).ToArray())
                };

            h4x0rz.Subscribe(Console.WriteLine);

            //while (true)
            //{
            //    Console.Write(".");
            //    Thread.Sleep(500);
            //}

            Console.ReadKey();
        }
Example #20
0
        public void Go()
        {
            if (Flying) return;
            lock (Locker)
            {
                if (Flying) return;
                Flying = true;
            }

            var towns = new Dictionary<string, PointF>
            {
                {"Turin", new PointF(45.2008018F, 7.6496301F)},
                {"Berlin", new PointF(52.3800011F, 13.5225F)},
                {"Madrid", new PointF(40.4936F, -3.56676F)},
                {"New York", new PointF(40.639801F, -73.7789002F)},
                {"Istanbul", new PointF(40.9768982F, 28.8146F)},
                {"Paris", new PointF(49.0127983F, 2.55F)},
                {"Cape Town", new PointF(-33.9648018F, 18.6016998F)},
            };

            var flights = new[]
            {
                new
                {
                    Code = "LH100",
                    Color = "red",
                    From = "Turin",
                    To = "Berlin",
                    Speed = 10,
                    Period = 500,
                },
                new
                {
                    Code = "AZ150",
                    Color = "blue",
                    From = "Turin",
                    To = "Madrid",
                    Speed = 8,
                    Period = 1500,
                },
                new
                {
                    Code = "XX150",
                    Color = "green",
                    From = "New York",
                    To = "Istanbul",
                    Speed = 30,
                    Period = 400,
                },
                new
                {
                    Code = "AA777",
                    Color = "orange",
                    From = "Paris",
                    To = "Cape Town",
                    Speed = 35,
                    Period = 2000,
                }
            };

            const int simulationFactor = 20; //1 hours = X seconds

            var signals = from flight in flights.ToObservable()
                let f = towns[flight.From]
                let t = towns[flight.To]
                let dx = t.X - f.X
                let dy = t.Y - f.Y
                let d = Math.Sqrt(
                    Math.Pow(dx, 2) + Math.Pow(dy, 2))
                let time = d/flight.Speed
                let sampling = (double) 1000/flight.Period
                let steps = (int) (sampling*simulationFactor*time)
                            + 1
                let sx = dx/steps
                let sy = dy/steps
                let paused = (int) (0.5*simulationFactor*sampling)
                let outbound = from i in Enumerable.Range(0, steps)
                    select new
                    {
                        Index = i,
                        Landed = false,
                        Touched = i == steps - 1,
                        Town = flight.To
                    }
                let delay1 = from i in Enumerable.Repeat(steps, paused)
                    select new
                    {
                        Index = i,
                        Landed = true,
                        Touched = false,
                        Town = flight.To
                    }
                let inbound = from i in Enumerable.Range(0, steps)
                    select new
                    {
                        Index = steps - i,
                        Landed = false,
                        Touched = i == steps - 1,
                        Town = flight.From
                    }
                let delay2 = from i in Enumerable.Repeat(0, paused)
                    select new
                    {
                        Index = i,
                        Landed = true,
                        Touched = false,
                        Town = flight.From
                    }
                let route = outbound.Concat(delay1)
                    .Concat(inbound)
                    .Concat(delay2).ToArray()
                from st in Observable.Interval(
                    TimeSpan.FromMilliseconds(flight.Period))
                let w = route[st%route.Length]
                let s = w.Index
                let x = f.X + sx*s
                let y = f.Y + sy*s
                let landed = w.Landed
                select new
                {
                    flight.Code,
                    w.Touched,
                    w.Town,
                    Landed = landed,
                    X = x,
                    Y = y,
                    Color = landed
                        ? "black"
                        : flight.Color,
                };

            signals.Subscribe(
                flight =>
                {
                    Clients.All.sample(flight.Code,
                        flight.X, flight.Y,
                        flight.Color, flight.Landed);
                    if (!flight.Touched) return;
                    Trace.WriteLine(
                        string.Format("Notifying {0}...",
                            flight.Code));
                    Clients.Group(flight.Code).touched(flight.Code,
                        flight.Town,
                        DateTime.Now.ToLongTimeString());
                });
        }
        public async Task CanRetrieveAndCacheRepositoriesForUserAndOrganizations()
        {
            var orgs = new[]
            {
                CreateOctokitOrganization("github"),
                CreateOctokitOrganization("octokit")
            };
            var ownedRepos = new[]
            {
                CreateRepository("haacked", "seegit"),
                CreateRepository("haacked", "codehaacks")
            };
            var memberRepos = new[]
            {
                CreateRepository("mojombo", "semver"),
                CreateRepository("ninject", "ninject"),
                CreateRepository("jabbr", "jabbr"),
                CreateRepository("fody", "nullguard")
            };
            var githubRepos = new[]
            {
                CreateRepository("github", "visualstudio")
            };
            var octokitRepos = new[]
            {
                CreateRepository("octokit", "octokit.net"),
                CreateRepository("octokit", "octokit.rb"),
                CreateRepository("octokit", "octokit.objc")
            };
            var apiClient = Substitute.For<IApiClient>();
            apiClient.GetOrganizations().Returns(orgs.ToObservable());
            apiClient.GetUserRepositories(RepositoryType.Owner).Returns(ownedRepos.ToObservable());
            apiClient.GetUserRepositories(RepositoryType.Member).Returns(memberRepos.ToObservable());
            apiClient.GetRepositoriesForOrganization("github").Returns(githubRepos.ToObservable());
            apiClient.GetRepositoriesForOrganization("octokit").Returns(octokitRepos.ToObservable());
            var cache = new InMemoryBlobCache();
            var modelService = new ModelService(apiClient, cache, Substitute.For<IAvatarProvider>());
            await modelService.InsertUser(new AccountCacheItem { Login = "opus" });

            var fetched = await modelService.GetRepositories().ToList();

            Assert.Equal(4, fetched.Count);
            Assert.Equal(2, fetched[0].Count);
            Assert.Equal(4, fetched[1].Count);
            Assert.Equal(1, fetched[2].Count);
            Assert.Equal(3, fetched[3].Count);
            Assert.Equal("seegit", fetched[0][0].Name);
            Assert.Equal("codehaacks", fetched[0][1].Name);
            Assert.Equal("semver", fetched[1][0].Name);
            Assert.Equal("ninject", fetched[1][1].Name);
            Assert.Equal("jabbr", fetched[1][2].Name);
            Assert.Equal("nullguard", fetched[1][3].Name);
            Assert.Equal("visualstudio", fetched[2][0].Name);
            Assert.Equal("octokit.net", fetched[3][0].Name);
            Assert.Equal("octokit.rb", fetched[3][1].Name);
            Assert.Equal("octokit.objc", fetched[3][2].Name);
            var cachedOwnerRepositories = await cache.GetObject<IReadOnlyList<ModelService.RepositoryCacheItem>>("opus|Owner:repos");
            Assert.Equal(2, cachedOwnerRepositories.Count);
            Assert.Equal("seegit", cachedOwnerRepositories[0].Name);
            Assert.Equal("haacked", cachedOwnerRepositories[0].Owner.Login);
            Assert.Equal("codehaacks", cachedOwnerRepositories[1].Name);
            Assert.Equal("haacked", cachedOwnerRepositories[1].Owner.Login);
            var cachedMemberRepositories = await cache.GetObject<IReadOnlyList<ModelService.RepositoryCacheItem>>("opus|Member:repos");
            Assert.Equal(4, cachedMemberRepositories.Count);
            Assert.Equal("semver", cachedMemberRepositories[0].Name);
            Assert.Equal("mojombo", cachedMemberRepositories[0].Owner.Login);
            Assert.Equal("ninject", cachedMemberRepositories[1].Name);
            Assert.Equal("ninject", cachedMemberRepositories[1].Owner.Login);
            Assert.Equal("jabbr", cachedMemberRepositories[2].Name);
            Assert.Equal("jabbr", cachedMemberRepositories[2].Owner.Login);
            Assert.Equal("nullguard", cachedMemberRepositories[3].Name);
            Assert.Equal("fody", cachedMemberRepositories[3].Owner.Login);
            var cachedGitHubRepositories = await cache.GetObject<IReadOnlyList<ModelService.RepositoryCacheItem>>("opus|github|repos");
            Assert.Equal(1, cachedGitHubRepositories.Count);
            Assert.Equal("seegit", cachedOwnerRepositories[0].Name);
            Assert.Equal("haacked", cachedOwnerRepositories[0].Owner.Login);
            Assert.Equal("codehaacks", cachedOwnerRepositories[1].Name);
            Assert.Equal("haacked", cachedOwnerRepositories[1].Owner.Login);
            var cachedOctokitRepositories = await cache.GetObject<IReadOnlyList<ModelService.RepositoryCacheItem>>("opus|octokit|repos");
            Assert.Equal("octokit.net", cachedOctokitRepositories[0].Name);
            Assert.Equal("octokit", cachedOctokitRepositories[0].Owner.Login);
            Assert.Equal("octokit.rb", cachedOctokitRepositories[1].Name);
            Assert.Equal("octokit", cachedOctokitRepositories[1].Owner.Login);
            Assert.Equal("octokit.objc", cachedOctokitRepositories[2].Name);
            Assert.Equal("octokit", cachedOctokitRepositories[2].Owner.Login);
        }
        public async Task OnlyRetrievesOneUserEvenIfCacheOrApiReturnsMoreThanOne()
        {
            // This should be impossible, but let's pretend it does happen.
            var users = new[]
            {
                CreateOctokitUser("peppermintpatty"),
                CreateOctokitUser("peppermintpatty")
            };
            var apiClient = Substitute.For<IApiClient>();
            apiClient.GetUser().Returns(users.ToObservable());
            apiClient.GetOrganizations().Returns(Observable.Empty<Organization>());
            var cache = new InMemoryBlobCache();
            var modelService = new ModelService(apiClient, cache, Substitute.For<IAvatarProvider>());

            var fetched = await modelService.GetAccounts();

            Assert.Equal(1, fetched.Count);
            Assert.Equal("peppermintpatty", fetched[0].Login);
        }
        public async Task CanRetrieveUserFromCacheAndAccountsFromApi()
        {
            var orgs = new[]
            {
                CreateOctokitOrganization("github"),
                CreateOctokitOrganization("fake")
            };
            var apiClient = Substitute.For<IApiClient>();
            apiClient.GetOrganizations().Returns(orgs.ToObservable());
            var cache = new InMemoryBlobCache();
            var modelService = new ModelService(apiClient, cache, Substitute.For<IAvatarProvider>());
            await modelService.InsertUser(new AccountCacheItem(CreateOctokitUser("octocat")));

            var fetched = await modelService.GetAccounts();

            Assert.Equal(3, fetched.Count);
            Assert.Equal("octocat", fetched[0].Login);
            Assert.Equal("github", fetched[1].Login);
            Assert.Equal("fake", fetched[2].Login);
            var cachedOrgs = await cache.GetObject<IReadOnlyList<AccountCacheItem>>("octocat|orgs");
            Assert.Equal(2, cachedOrgs.Count);
            Assert.Equal("github", cachedOrgs[0].Login);
            Assert.Equal("fake", cachedOrgs[1].Login);
            var cachedUser = await cache.GetObject<AccountCacheItem>("user");
            Assert.Equal("octocat", cachedUser.Login);
        }
        public async Task CanRetrieveAndCacheLicenses()
        {
            var licenses = new[]
            {
                new LicenseMetadata("mit", "MIT", new Uri("https://github.com/")),
                new LicenseMetadata("apache", "Apache", new Uri("https://github.com/"))
            };
            var apiClient = Substitute.For<IApiClient>();
            apiClient.GetLicenses().Returns(licenses.ToObservable());
            var cache = new InMemoryBlobCache();
            var modelService = new ModelService(apiClient, cache, Substitute.For<IAvatarProvider>());

            var fetched = await modelService.GetLicenses();

            Assert.Equal(3, fetched.Count);
            Assert.Equal("None", fetched[0].Name);
            Assert.Equal("MIT", fetched[1].Name);
            Assert.Equal("Apache", fetched[2].Name);
            var cached = await cache.GetObject<IReadOnlyList<ModelService.LicenseCacheItem>>("licenses");
            Assert.Equal(2, cached.Count);
            Assert.Equal("mit", cached[0].Key);
            Assert.Equal("apache", cached[1].Key);
        }
        public void CachedValuesTest()
        {
            var input = new[] { 1, 2, 1, 3, 1 };
            var sched = new TestScheduler();

            var delay = TimeSpan.FromSeconds(1.0);
            var fixture = new ObservableAsyncMRUCache<int, int>(x => Observable.Return(x*5).Delay(delay, sched), 2, 2);

            var results = input.ToObservable().SelectMany(fixture.AsyncGet).CreateCollection();
            sched.AdvanceTo(sched.FromTimeSpan(TimeSpan.FromMilliseconds(500)));

            Assert.Equal(0, fixture.CachedValues().Count());

            sched.AdvanceTo(sched.FromTimeSpan(TimeSpan.FromMilliseconds(1500)));

            var output = fixture.CachedValues().ToArray();
            Assert.IsTrue(output.Length == 2);
            Assert.Equal(input.Length, results.Count);
        }
Example #26
0
 public void TheLastEvent()
 {
     var received = "";
     var names = new[] { "Foo", "Bar" };
     names.ToObservable().Subscribe((s) => received = s);
     Assert.AreEqual(___, received);
 }
Example #27
0
 public void EveryThingCounts()
 {
     var received = 0;
     var numbers = new[] { 3, 4 };
     numbers.ToObservable().Subscribe((int x) => received += x);
     Assert.AreEqual(___, received);
 }
Example #28
0
        private static void ObservableToDictionary()
        {
            Console.WriteLine();
            Console.WriteLine("----- Observable To Dictionary ----");
            IEnumerable<string> cities = new[] { "London", "Tel-Aviv", "Tokyo", "Rome" };

            var dictionaryObservable =
                cities
                .ToObservable()
                .ToDictionary(c => c.Length);//change the value to some const to see and error

            dictionaryObservable
                .Select(d => string.Join(",", d))
                .SubscribeConsole("dictionary");
        }
        private static void ProcessingTheSourceAndTheResult()
        {
            Demo.DisplayHeader("The SelectMany operator - processing the source item and the result item");
            #region creating collection of news items
            var theNews = new[]
            {
                new NewsItem
                {
                    Title = "NewsItem1",
                    Url = new Url("https://news.com/NewsItem1"),
                    Images =
                        new[]
                        {
                            new NewsImage {ImageName = "Item1Image1"},
                            new NewsImage {ImageName = "Item1Image2", IsChildFriendly = false}
                        },
                },
                new NewsItem
                {
                    Title = "NewsItem2",
                    Url = new Url("https://news.com/NewsItem2"),
                    Images =
                        new[] {new NewsImage {ImageName = "Item2Image1"}},
                }
            };
            #endregion

            IObservable<NewsItem> news = theNews.ToObservable();

            news.SelectMany(n => n.Images,
            (newsItem, img) => new NewImageViewModel
            {
            ItemUrl = newsItem.Url,
            NewsImage = img
            })
            .Where(vm => vm.NewsImage.IsChildFriendly)
            .Subscribe(img => AddToHeadlines(img));
        }
Example #30
0
        private static void ObservableToLookup()
        {
            Console.WriteLine();
            Console.WriteLine("----- Observable To Lookup ----");
            // Madrid and London has the same length
            IEnumerable<string> cities = new[] { "London", "Tel-Aviv", "Tokyo", "Rome", "Madrid" };

            var lookupObservable =
                cities
                .ToObservable()
                .ToLookup(c => c.Length);

            lookupObservable
                .Select(lookup =>
                {
                    var groups = new StringBuilder();
                    foreach (var grp in lookup)
                        groups.AppendFormat("[Key:{0} => {1}]", grp.Key, grp.Count());
                    return groups.ToString();
                })
                .SubscribeConsole("lookup");
        }