Exemplo n.º 1
0
        public ContentApp(Window window)

        {
            HOME = new Command(() => {
                page = new welcomme();
                prev = null;
            });
            clients = new Command(() => {
                page = new ViewClient();
                prev = null;
            });
            processes = new Command(() => {
                page = new PCrad();
                prev = null;
            });
            this.btnmenu = new Command(() => {
                this.vismenu = Visibility.Visible;
                contentWidth = window.Width - 250;
                this.visbtn  = Visibility.Hidden;
                MessageBox.Show("" + menuWidth);
            });
            this.btnclose = new Command(() => {
                this.vismenu = Visibility.Hidden;
                contentWidth = window.Width;
                this.visbtn  = Visibility.Visible;
                MessageBox.Show("" + menuWidth);
            });
            this.window         = window;
            contentHeigth       = window.Height;
            contentWidth        = window.Width - 250;
            window.SizeChanged += SizeChanged;
            this.vismenu        = Visibility.Collapsed;
            this.visbtn         = Visibility.Visible;
        }
 public ViewReceivedServiceProduct()
 {
     ForwardToModels      = new List <ForwardToModel>();
     ChargeReportModel    = new ChargeReportModel();
     DischargeReportModel = new DischargeReportModel();
     Client = new ViewClient();
 }
        public async Task ViewClient_Submits_ViewQuery_Using_Post()
        {
            var keys         = Enumerable.Range(1, 10).Select(i => $"key-{i}").ToList();
            var expectedJson = JsonConvert.SerializeObject(new
            {
                keys
            }, Formatting.None);

            var handler = FakeHttpMessageHandler.Create(request =>
            {
                // verify request was a post
                Assert.Equal(HttpMethod.Post, request.Method);

                // get the post body and verify content
                var content = request.Content.ReadAsStringAsync().Result;
                Assert.Equal(expectedJson, content);

                // return empty json response
                return(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent("{ }")
                });
            });

            var httpClient  = new CouchbaseHttpClient(handler);
            var serializer  = new DefaultSerializer();
            var queryClient = new ViewClient(httpClient, serializer, new Mock <ILogger <ViewClient> >().Object, new Mock <IRedactor>().Object);

            var query = new ViewQuery("bucket-name", "http://localhost");

            query.Keys(keys);

            await queryClient.ExecuteAsync <dynamic, dynamic>(query).ConfigureAwait(false);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Sends a request for a View to the server asynchronously.
        /// </summary>
        /// <typeparam name="T">The <see cref="Type" /> T of the body for each row result.</typeparam>
        /// <param name="query">The <see cref="IViewQuery" /> representing the query.</param>
        /// <returns>
        /// An <see cref="Task{IViewResult}" /> object representing the asynchronous operation.
        /// </returns>
        public Task <IViewResult <T> > SendAsync <T>(IViewQueryable query)
        {
            Task <IViewResult <T> > result;

            try
            {
                query.BaseUri(CachedViewBaseUri);
                result = query.IsStreaming
                    ? _streamingViewClient.ExecuteAsync <T>(query)
                    : ViewClient.ExecuteAsync <T>(query);
            }
            catch (Exception e)
            {
                var tcs = new TaskCompletionSource <IViewResult <T> >();
                tcs.SetResult(new ViewResult <T>
                {
                    Exception  = e,
                    Message    = e.Message,
                    Error      = e.Message,
                    Success    = false,
                    StatusCode = HttpStatusCode.BadRequest,
                    Rows       = new List <ViewRow <T> >()
                });
                result = tcs.Task;
            }
            return(result);
        }
        public void Test_ExecuteAsync()
        {
            var query = new ViewQuery().
                        From("docs", "all_docs").
                        Bucket("default").
                        BaseUri(_baseUri);

            var client = new ViewClient(new HttpClient(),
                                        new JsonDataMapper(new ClientConfiguration()),
                                        new BucketConfig {
                Name = "beer-sample"
            },
                                        new ClientConfiguration());

            int n       = 10000;
            var options = new ParallelOptions {
                MaxDegreeOfParallelism = 4
            };

            Parallel.For(0, n, options, async i =>
            {
                var result = await client.ExecuteAsync <dynamic>(query);
                Console.WriteLine("{0} {1} {2}", i, result.Success, result.Message);
            });
        }
Exemplo n.º 6
0
        /// <summary>
        /// Sends a request for a View to the server.
        /// </summary>
        /// <typeparam name="T">The <see cref="Type" /> T of the body for each row result.</typeparam>
        /// <param name="query">The <see cref="IViewQuery" /> representing the query.</param>
        /// <returns>
        /// An <see cref="IViewResult{T}" /> representing the result of the query.
        /// </returns>
        public IViewResult <T> Send <T>(IViewQueryable query)
        {
            IViewResult <T> result;

            try
            {
                query.BaseUri(CachedViewBaseUri);
                result = query.IsStreaming
                    ? _streamingViewClient.Execute <T>(query)
                    : ViewClient.Execute <T>(query);
            }
            catch (Exception e)
            {
                result = new ViewResult <T>
                {
                    Exception  = e,
                    Message    = e.Message,
                    Error      = e.Message,
                    Success    = false,
                    StatusCode = HttpStatusCode.BadRequest,
                    Rows       = new List <ViewRow <T> >()
                };
            }
            return(result);
        }
Exemplo n.º 7
0
        public void ViewClient_Submits_ViewQuery_Using_Post()
        {
            var keys         = Enumerable.Range(1, 10).Select(i => $"key-{i}").ToList();
            var expectedJson = JsonConvert.SerializeObject(new
            {
                keys
            }, Formatting.None);

            var handler = FakeHttpMessageHandler.Create(request =>
            {
                // verify request was a post
                Assert.AreEqual(HttpMethod.Post, request.Method);

                // get the post body and verify content
                var content = request.Content.ReadAsStringAsync().Result;
                Assert.AreEqual(expectedJson, content);

                // return empty json response
                return(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent("{ }")
                });
            });

            var httpClient  = new HttpClient(handler);
            var queryClient = new ViewClient(httpClient, new JsonDataMapper(new DefaultSerializer()));

            var query = new ViewQuery("bucket-name", "http://localhost");

            query.Keys(keys);

            var result = queryClient.Execute <dynamic>(query);

            Assert.IsTrue(result.Success);
        }
Exemplo n.º 8
0
        public void When_Row_Is_Dynamic_Query_By_Key_Succeeds()
        {
            var query = new ViewQuery().
                        From("beer_ext", "all_beers").
                        Bucket("beer-sample").
                        Limit(1).
                        Development(false);;

            var client = new ViewClient(new HttpClient(),
                                        new JsonDataMapper(new ClientConfiguration()),
                                        new BucketConfig {
                Name = "beer-sample"
            },
                                        new ClientConfiguration());

            var result = client.Execute <Beer>(query);

            var query2 = new ViewQuery().
                         From("beer_ext", "all_beers").
                         Bucket("beer-sample").Key(result.Rows.First().Id);

            var result2 = client.Execute <Beer>(query2);

            Assert.AreEqual(result.Rows.First().Id, result2.Rows.First().Id);
        }
        public void When_Row_Is_Dynamic_Query_By_Key_Succeeds()
        {
            var query = new ViewQuery().
                From("beer_ext", "all_beers").
                Bucket("beer-sample").
                Limit(1).
                Development(false).
                BaseUri(_baseUri);

            var client = new ViewClient(new HttpClient(),
                new JsonDataMapper(new ClientConfiguration()),
                new BucketConfig { Name = "beer-sample" },
                new ClientConfiguration());

            var result = client.Execute<Beer>(query);

            var query2 = new ViewQuery().
                From("beer_ext", "all_beers").
                Bucket("beer-sample").
                Key(result.Rows.First().Id).
                BaseUri(_baseUri);

            var result2 = client.Execute<Beer>(query2);
            Assert.AreEqual(result.Rows.First().Id, result2.Rows.First().Id);
        }
Exemplo n.º 10
0
        public void When_Poco_Is_Supplied_Map_Results_To_It()
        {
            var query = new ViewQuery().
                        From("beer_ext", "all_beers").
                        Bucket("beer-sample").
                        Limit(10).
                        Development(false);

            var client = new ViewClient(new HttpClient(),
                                        new JsonDataMapper(new ClientConfiguration()),
                                        new BucketConfig {
                Name = "beer-sample"
            },
                                        new ClientConfiguration());

            var result = client.Execute <Beer>(query);

            foreach (var viewRow in result.Rows)
            {
                Assert.IsNotNull(viewRow.Id);
            }
            Console.WriteLine(result.Error);
            Assert.IsNotNull(result.Rows);
            Assert.IsTrue(result.Success);
            Assert.AreEqual(result.Rows.Count(), result.Values.Count());
        }
Exemplo n.º 11
0
        //----------------------Get Client By Id----------
        public JsonResult GetClientById(int clientId)
        {
            Session["Orders"]      = null;
            Session["ProductList"] = null;
            ViewClient client = _iClientManager.GetClientDeailsById(clientId);

            return(Json(client, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 12
0
        public JsonResult GetClientById(int clientId)
        {
            //------------Remove all product added before on client select----
            RemoveAll();
            ViewClient client = _iClientManager.GetClientDeailsById(clientId);

            return(Json(client, JsonRequestBehavior.AllowGet));
        }
        public void When_Query_Is_Succesful_Rows_Are_Returned()
        {
            var query = new ViewQuery(false).
                From("beer-sample", "beer").
                View("brewery_beers");

            var client = new ViewClient(new HttpClient(), new JsonDataMapper());
            var result = client.Execute<dynamic>(query);
            Assert.IsNotNull(result.Rows);
            Assert.AreEqual(result.StatusCode, HttpStatusCode.OK);
        }
Exemplo n.º 14
0
        public Client(ClientOptions options)
        {
            Options = options;
            // TODO : pass server options
            ClientHttpBase = string.Format("http://{0}:{1}", options.Ip, options.HttpPort);
            Views          = PlatformClient.ConnectToViewStorage(options.StoreLocation, options.ViewsFolder);

            UseEventStore("default");

            RegisterCommands();
        }
Exemplo n.º 15
0
Arquivo: Client.cs Projeto: AigizK/Seo
        public Client(ClientOptions options)
        {
            Options = options;
            // TODO : pass server options
            ClientHttpBase = string.Format("http://{0}:{1}", options.Ip, options.HttpPort);
            Views = PlatformClient.ConnectToViewStorage(options.StoreLocation, options.ViewsFolder);

            UseEventStore("seo");

            RegisterCommands();
        }
Exemplo n.º 16
0
        public void When_Query_Is_Succesful_Rows_Are_Returned()
        {
            var query = new ViewQuery(false).
                        From("beer-sample", "beer").
                        View("brewery_beers");

            var client = new ViewClient(new HttpClient(), new JsonDataMapper());
            var result = client.Execute <dynamic>(query);

            Assert.IsNotNull(result.Rows);
            Assert.AreEqual(result.StatusCode, HttpStatusCode.OK);
        }
        public static async Task <string> GetStaticFileAsync(string path)
        {
            try
            {
                var request  = GrpcGetStaticFileRequestFactory.Make(path);
                var response = await ViewClient.GetStaticFileAsync(request);

                return(response.Data);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        public void When_Url_Is_Invalid_WebException_Is_Returned()
        {
            var query = new ViewQuery(false).
                From("beer-sample", "beer").
                View("brewery_beers").
                BaseUri("http://192.168.56.105:8092/");

            var client = new ViewClient(new HttpClient(), new JsonDataMapper());
            var result = client.Execute<dynamic>(query);
            Assert.IsNotNull(result.Rows);
            Assert.IsFalse(result.Success);
            Assert.AreEqual(HttpStatusCode.ServiceUnavailable, result.StatusCode);
            Assert.AreEqual(typeof(HttpRequestException), result.Exception.GetType());
        }
Exemplo n.º 19
0
        public ContentApp(Window window)

        {
            HOME = new Command(() => {
                page = new welcomme();
                prev = null;
            });
            account = new Command(() => {
                page = new ViewAcount();
                prev = null;
            });
            settings = new Command(() => {
                page = new Settings();
                prev = null;
            });
            logout = new Command(() => {
                login login = new login();
                login.Show();
                App.Current.MainWindow.Close();
                App.Current.MainWindow = login;
                Ico.getValue <db>().GetUnivdb().users.ToList().Where(c => c.id == Ico.getValue <user>().id).ToList().FirstOrDefault().date_gust = DateTime.Now;
                Ico.getValue <db>().savedb();
                ;
            });
            clients = new Command(() => {
                page = new ViewClient();
                prev = null;
            });
            processes = new Command(() => {
                page = new PCrad();
                prev = null;
            });
            this.btnmenu = new Command(() => {
                this.vismenu = Visibility.Visible;
                contentWidth = window.Width - 250;
                this.visbtn  = Visibility.Hidden;
            });
            this.btnclose = new Command(() => {
                this.vismenu = Visibility.Hidden;
                contentWidth = window.Width;
                this.visbtn  = Visibility.Visible;
            });
            this.window         = window;
            contentHeigth       = window.Height;
            contentWidth        = window.Width - 250;
            window.SizeChanged += SizeChanged;
            this.vismenu        = Visibility.Collapsed;
            this.visbtn         = Visibility.Visible;
        }
Exemplo n.º 20
0
        static void Main()
        {
            StorePath = ConfigurationManager.AppSettings["StorePath"];

            if (string.IsNullOrWhiteSpace(StorePath))
            {
                StorePath = @"C:\LokadData\dp-store";
            }

            StoreConnection = ConfigurationManager.AppSettings["StoreConnection"];
            if (string.IsNullOrWhiteSpace(StoreConnection))
            {
                StoreConnection = "http://localhost:8080";
            }

            // Use "default" container for reading/writing events
            _client = PlatformClient.ConnectToEventStore(StorePath, storeId: "default", platformServerEndpoint: StoreConnection);
            _view   = PlatformClient.ConnectToViewStorage(StorePath, "sample1-views");


            Console.WriteLine("You name:");
            _userName = Console.ReadLine();
            Console.WriteLine("Chat starting...");

            _client.WriteEvent("", Encoding.UTF8.GetBytes("|join a new user " + _userName));
            Task.Factory.StartNew(ScanChat,
                                  TaskCreationOptions.LongRunning | TaskCreationOptions.PreferFairness);

            WriteColorText(_userName + ">", ConsoleColor.Green);

            _userMessage = "";

            while (true)
            {
                ConsoleKeyInfo keyInfo = Console.ReadKey();

                if (keyInfo.KeyChar != '\r')
                {
                    _userMessage += keyInfo.KeyChar;
                }
                else
                {
                    _client.WriteEvent("", Encoding.UTF8.GetBytes(string.Format("{0}|{1}", _userName, _userMessage)));
                    Console.WriteLine();
                    WriteColorText(_userName + ">", ConsoleColor.Green);
                    _userMessage = "";
                }
            }
        }
Exemplo n.º 21
0
 private static async Task RunInitializationRoutine()
 {
     try
     {
         InitializeDatabase();
         ViewClient.Initialize();
         ShippingClient.Initialize();
         MercadoLivreClient.Initialize();
         SaleClient.Initialize();
     }
     catch (Exception e)
     {
         HandleInitializationFailure(e);
     }
 }
Exemplo n.º 22
0
        public void When_Url_Is_Invalid_WebException_Is_Returned()
        {
            var query = new ViewQuery(false).
                        From("beer-sample", "beer").
                        View("brewery_beers").
                        BaseUri("http://192.168.56.105:8092/");

            var client = new ViewClient(new HttpClient(), new JsonDataMapper());
            var result = client.Execute <dynamic>(query);

            Assert.IsNotNull(result.Rows);
            Assert.IsFalse(result.Success);
            Assert.AreEqual(HttpStatusCode.ServiceUnavailable, result.StatusCode);
            Assert.AreEqual(typeof(HttpRequestException), result.Exception.GetType());
        }
        public void When_View_Is_Not_Found_404_Is_Returned()
        {
            var query = new ViewQuery(false).
                From("beer-sample", "beer").
                View("view_that_does_not_exist");

            var client = new ViewClient(new HttpClient(), new JsonDataMapper());
            var result = client.Execute<dynamic>(query);
            
            Assert.IsNotNull(result.Message);
            Assert.AreEqual(HttpStatusCode.NotFound, result.StatusCode);
            Assert.IsFalse(result.Success);

            Console.WriteLine(result.Message);
        }
Exemplo n.º 24
0
        public void When_View_Is_Not_Found_404_Is_Returned()
        {
            var query = new ViewQuery(false).
                        From("beer-sample", "beer").
                        View("view_that_does_not_exist");

            var client = new ViewClient(new HttpClient(), new JsonDataMapper());
            var result = client.Execute <dynamic>(query);

            Assert.IsNotNull(result.Message);
            Assert.AreEqual(HttpStatusCode.NotFound, result.StatusCode);
            Assert.IsFalse(result.Success);

            Console.WriteLine(result.Message);
        }
Exemplo n.º 25
0
        public async Task ExecuteAsync_SerializerOverride_UsesOverride()
        {
            var handlerMock = new Mock <HttpMessageHandler>();

            handlerMock.Protected().Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>()).ReturnsAsync(new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new ByteArrayContent(Array.Empty <byte>())
            });

            var httpClient = new HttpClient(handlerMock.Object)
            {
                BaseAddress = new Uri("http://localhost:8091")
            };
            var httpClientFactory = new MockHttpClientFactory(httpClient);

            var mockServiceUriProvider = new Mock <IServiceUriProvider>();

            mockServiceUriProvider
            .Setup(m => m.GetRandomViewsUri(It.IsAny <string>()))
            .Returns(new Uri("http://localhost:8092"));

            var primarySerializer = new Mock <ITypeSerializer> {
                DefaultValue = DefaultValue.Mock
            };
            var overrideSerializer = new Mock <ITypeSerializer> {
                DefaultValue = DefaultValue.Mock
            };
            var client = new ViewClient(httpClientFactory, primarySerializer.Object, new Mock <ILogger <ViewClient> >().Object,
                                        new Mock <IRedactor>().Object, NoopRequestTracer.Instance);

            await client.ExecuteAsync <object, object>(new ViewQuery("default", "doc", "view")
            {
                Serializer = overrideSerializer.Object
            }).ConfigureAwait(false);

            primarySerializer.Verify(
                m => m.DeserializeAsync <BlockViewResult <object, object> .ViewResultData>(It.IsAny <Stream>(),
                                                                                           It.IsAny <CancellationToken>()),
                Times.Never);
            overrideSerializer.Verify(
                m => m.DeserializeAsync <BlockViewResult <object, object> .ViewResultData>(It.IsAny <Stream>(),
                                                                                           It.IsAny <CancellationToken>()),
                Times.AtLeastOnce);
        }
Exemplo n.º 26
0
        public void When_View_Is_Called_With_Invalid_Parameters_Error_Is_Returned()
        {
            var query = new ViewQuery(false).
                        From("beer-sample", "beer").
                        View("brewery_beers").
                        Group(true);

            var client = new ViewClient(new HttpClient(), new JsonDataMapper());
            var result = client.Execute <dynamic>(query);

            Assert.AreEqual("query_parse_error", result.Error);
            Assert.AreEqual("Invalid URL parameter 'group' or  'group_level' for non-reduce view.", result.Message);
            Assert.AreEqual(HttpStatusCode.BadRequest, result.StatusCode);
            Assert.IsFalse(result.Success);

            Console.WriteLine(result.Message);
        }
        public void When_View_Is_Called_With_Invalid_Parameters_Error_Is_Returned()
        {
            var query = new ViewQuery(false).
                From("beer-sample", "beer").
                View("brewery_beers").
                Group(true);

            var client = new ViewClient(new HttpClient(), new JsonDataMapper());
            var result = client.Execute<dynamic>(query);
            
            Assert.AreEqual("query_parse_error", result.Error);
            Assert.AreEqual("Invalid URL parameter 'group' or  'group_level' for non-reduce view.", result.Message);
            Assert.AreEqual(HttpStatusCode.BadRequest, result.StatusCode);
            Assert.IsFalse(result.Success);

            Console.WriteLine(result.Message);
        }
Exemplo n.º 28
0
        public void When_Query_Is_Succesful_Rows_Are_Returned()
        {
            var query = new ViewQuery().
                        From("beer", "brewery_beers").
                        Bucket("beer-sample");

            var client = new ViewClient(new HttpClient(),
                                        new JsonDataMapper(new ClientConfiguration()),
                                        new BucketConfig {
                Name = "beer-sample"
            },
                                        new ClientConfiguration());

            var result = client.Execute <dynamic>(query);

            Assert.IsNotNull(result.Rows);
            Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
        }
Exemplo n.º 29
0
        public ContentApp(Window window)

        {
            HOME = new Command(() => {
                page = new welcomme();
                prev = null;
            });
            account = new Command(() => {
                page = new ViewAcount();
                prev = null;
            });
            logout = new Command(() => {
                login login = new login();
                login.Show();
                App.Current.MainWindow.Close();
                App.Current.MainWindow = login;
                Ico.Delete <user>();
                ;
            });
            clients = new Command(() => {
                page = new ViewClient();
                prev = null;
            });
            processes = new Command(() => {
                page = new PCrad();
                prev = null;
            });
            this.btnmenu = new Command(() => {
                this.vismenu = Visibility.Visible;
                contentWidth = window.Width - 250;
                this.visbtn  = Visibility.Hidden;
            });
            this.btnclose = new Command(() => {
                this.vismenu = Visibility.Hidden;
                contentWidth = window.Width;
                this.visbtn  = Visibility.Visible;
            });
            this.window         = window;
            contentHeigth       = window.Height;
            contentWidth        = window.Width - 250;
            window.SizeChanged += SizeChanged;
            this.vismenu        = Visibility.Collapsed;
            this.visbtn         = Visibility.Visible;
        }
Exemplo n.º 30
0
        static void Main()
        {
            StorePath = ConfigurationManager.AppSettings["StorePath"];

            if (string.IsNullOrWhiteSpace(StorePath))
                StorePath = @"C:\LokadData\dp-store";

            StoreConnection = ConfigurationManager.AppSettings["StoreConnection"];
            if (string.IsNullOrWhiteSpace(StoreConnection))
                StoreConnection = "http://localhost:8080";

            // Use "default" container for reading/writing events
            _client = PlatformClient.ConnectToEventStore(StorePath, storeId : "default", platformServerEndpoint : StoreConnection);
            _view = PlatformClient.ConnectToViewStorage(StorePath, "sample1-views");

            Console.WriteLine("You name:");
            _userName = Console.ReadLine();
            Console.WriteLine("Chat starting...");

            _client.WriteEvent("", Encoding.UTF8.GetBytes("|join a new user " + _userName));
            Task.Factory.StartNew(ScanChat,
                TaskCreationOptions.LongRunning | TaskCreationOptions.PreferFairness);

            WriteColorText(_userName + ">", ConsoleColor.Green);

            _userMessage = "";

            while (true)
            {
                ConsoleKeyInfo keyInfo = Console.ReadKey();

                if (keyInfo.KeyChar != '\r')
                    _userMessage += keyInfo.KeyChar;
                else
                {
                    _client.WriteEvent("", Encoding.UTF8.GetBytes(string.Format("{0}|{1}", _userName, _userMessage)));
                    Console.WriteLine();
                    WriteColorText(_userName + ">", ConsoleColor.Green);
                    _userMessage = "";
                }
            }
        }
Exemplo n.º 31
0
        public void When_Query_Is_Succesful_Rows_Are_Returned()
        {
            var query = new ViewQuery().
                From("beer", "brewery_beers").
                Bucket("beer-sample").
                Limit(10);

            var client = new ViewClient(new HttpClient(),
                new JsonDataMapper(new ClientConfiguration()),
                new BucketConfig { Name = "beer-sample" },
                new ClientConfiguration());

            var result = client.Execute<dynamic>(query);
            Assert.IsNotNull(result.Rows);
            foreach (var viewRow in result.Rows)
            {
                Assert.IsNotNull(viewRow.Id);
            }
            Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
        }
Exemplo n.º 32
0
        public void When_Poco_Is_Supplied_Map_Results_To_It()
        {
            var query = new ViewQuery().
              From("beer", "all_beers").
              Bucket("beer-sample").Limit(10);

            var client = new ViewClient(new HttpClient(),
                new JsonDataMapper(new ClientConfiguration()),
                new BucketConfig { Name = "beer-sample" },
                new ClientConfiguration());

            var result = client.Execute<Beer>(query);
            foreach (var viewRow in result.Rows)
            {
                Assert.IsNotNull(viewRow.Id);
            }
            Console.WriteLine(result.Error);
            Assert.IsNotNull(result.Rows);
            Assert.IsTrue(result.Success);
            Assert.AreEqual(result.Rows.Count(), result.Values.Count());
        }
        public async Task ExecuteAsync_Sets_LastActivity()
        {
            var handler = FakeHttpMessageHandler.Create(request => new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("{ }")
            });

            var httpClient  = new CouchbaseHttpClient(handler);
            var serializer  = new DefaultSerializer();
            var queryClient = new ViewClient(httpClient, serializer, new Mock <ILogger <ViewClient> >().Object, new Mock <IRedactor>().Object);

            Assert.Null(queryClient.LastActivity);

            var query = new ViewQuery("bucket-name", "http://localhost");

            query.Keys("test-key");

            await queryClient.ExecuteAsync <dynamic, dynamic>(query);

            Assert.NotNull(queryClient.LastActivity);
        }
Exemplo n.º 34
0
        /// <summary>
        /// Creates a connection to view storage
        /// </summary>
        /// <param name="storageConfiguration">Storage configuration (either local file path
        /// or <see cref="AzureStoreConfiguration"/>)</param>
        /// <param name="containerName">container name (directory) where to put views</param>
        /// <returns>new instance of the client that can read and write events</returns>
        public static ViewClient ConnectToViewStorage(string storageConfiguration, string containerName)
        {
            AzureStoreConfiguration configuration;
            if (!AzureStoreConfiguration.TryParse(storageConfiguration, out configuration))
            {
                var root = new FileViewRoot(new DirectoryInfo(storageConfiguration));

                var viewClient = new ViewClient(root.GetContainer(containerName), FileActionPolicy);
                viewClient.CreateContainerIfNeeded();
                return viewClient;
            }
            else
            {
                var account = CloudStorageAccount.Parse(configuration.ConnectionString);
                var client = account.CreateCloudBlobClient();
                var viewContainer = new AzureViewRoot(client).GetContainer(configuration.RootBlobContainerName);

                var viewClient = new ViewClient(viewContainer.GetContainer(containerName), AzureActionPolicy);
                viewClient.CreateContainerIfNeeded();
                return viewClient;
            }
        }
        public void When_View_Is_Not_Found_404_Is_Returned()
        {
            var query = new ViewQuery().
                        From("beer", "view_that_does_not_exist").
                        Bucket("beer-sample").
                        BaseUri(_baseUri);

            var client = new ViewClient(new HttpClient(),
                                        new JsonDataMapper(new ClientConfiguration()),
                                        new BucketConfig {
                Name = "beer-sample"
            },
                                        new ClientConfiguration());

            var result = client.Execute <dynamic>(query);

            Assert.IsNotNull(result.Message);
            Assert.AreEqual(HttpStatusCode.NotFound, result.StatusCode);
            Assert.IsFalse(result.Success);

            Console.WriteLine(result.Message);
        }
Exemplo n.º 36
0
        public void Execute_Sets_LastActivity()
        {
            var handler = FakeHttpMessageHandler.Create(request => new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("{ }")
            });

            var httpClient  = new HttpClient(handler);
            var queryClient = new ViewClient(httpClient,
                                             new JsonDataMapper(new DefaultSerializer()),
                                             new ClusterOptions());

            Assert.Null(queryClient.LastActivity);

            var query = new ViewQuery("bucket-name", "http://localhost");

            query.Keys("test-key");
            query.UseStreaming(true);

            queryClient.Execute <dynamic>(query);
            Assert.NotNull(queryClient.LastActivity);
        }
Exemplo n.º 37
0
        public void When_View_Is_Called_With_Invalid_Parameters_Error_Is_Returned()
        {
            var query = new ViewQuery().
                        From("beer", "brewery_beers").
                        Bucket("beer-sample").
                        Group(true);

            var client = new ViewClient(new HttpClient(),
                                        new JsonDataMapper(new ClientConfiguration()),
                                        new BucketConfig {
                Name = "beer-sample"
            },
                                        new ClientConfiguration());

            var result = client.Execute <dynamic>(query);

            Assert.AreEqual("query_parse_error", result.Error);
            Assert.AreEqual(HttpStatusCode.BadRequest, result.StatusCode);
            Assert.IsFalse(result.Success);

            Console.WriteLine(result.Message);
        }
Exemplo n.º 38
0
        public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            // Initialize the content controller.
            var bounds                = UIScreen.MainScreen.Bounds;
            var contentController     = new WKUserContentController();
            var contentMessageHandler = new WebClient();

            contentController.AddScriptMessageHandler(contentMessageHandler, "native");

            // Initialize the content.
            var webView = new WKWebView(bounds, new WKWebViewConfiguration {
                UserContentController = contentController
            });
            var view = new ViewClient(webView);

            _bridge = new Bridge(new BridgeClient(webView), new CorePlugin(view));

            // Initialize the content configuration.
            contentMessageHandler.UseBridge(_bridge);
            webView.ScrollView.ContentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentBehavior.Never;
            webView.ScrollView.ShowsHorizontalScrollIndicator = false;
            webView.ScrollView.ShowsVerticalScrollIndicator   = false;

            // Initialize the view splash screen.
            var launchScreen = NSBundle.MainBundle.LoadNib("LaunchScreen", null, null);
            var launchView   = launchScreen.GetItem <UIView>(0);

            launchView.Frame = bounds;

            // Initialize the window.
            Window = new UIWindow(bounds)
            {
                RootViewController = view
            };
            Window.RootViewController.View = launchView;
            Window.MakeKeyAndVisible();
            return(true);
        }
Exemplo n.º 39
0
        public void When_Url_Is_Invalid_WebException_Is_Returned_2()
        {
            var query = new ViewQuery().
                        From("beer", "brewery_beers").
                        Bucket("beer-sample").
                        BaseUri("http://192.168.62.200:8092/");

            var client = new ViewClient(new HttpClient(),
                                        new JsonDataMapper(new ClientConfiguration()),
                                        new BucketConfig {
                Name = "beer-sample"
            },
                                        new ClientConfiguration {
                ViewRequestTimeout = 5000
            });

            var result = client.Execute <dynamic>(query);

            Assert.IsNotNull(result.Rows);
            Assert.IsFalse(result.Success);
            Assert.AreEqual(HttpStatusCode.ServiceUnavailable, result.StatusCode);
            Assert.AreEqual(typeof(WebException), result.Exception.GetType());
        }
        public void Test_Geo_Spatial_View()
        {
            var uriString = ClientConfigUtil.GetConfiguration().Servers.First().ToString();

            uriString = uriString.Replace("8091", "8092").Replace("pools", "travel-sample/");

            var query = new SpatialViewQuery().From("spatial", "routes")
                        .Stale(StaleState.False)
                        .Limit(10)
                        .Skip(0)
                        .BaseUri(new Uri(uriString));

            var client = new ViewClient(new HttpClient(),
                                        new JsonDataMapper(ClientConfigUtil.GetConfiguration()),
                                        new BucketConfig {
                Name = "travel-sample"
            },
                                        new ClientConfiguration());

            var results = client.Execute <dynamic>(query);

            Assert.IsTrue(results.Success, results.Error);
        }
Exemplo n.º 41
0
        public void When_View_Is_Called_With_Invalid_Parameters_Error_Is_Returned()
        {
            var query = new ViewQuery().
                From("beer", "brewery_beers").
                Bucket("beer-sample").
                Group(true);

            var client = new ViewClient(new HttpClient(),
                new JsonDataMapper(new ClientConfiguration()),
                new BucketConfig { Name = "beer-sample" },
                new ClientConfiguration());

            var result = client.Execute<dynamic>(query);

            Assert.AreEqual("query_parse_error", result.Error);
            Assert.AreEqual(HttpStatusCode.BadRequest, result.StatusCode);
            Assert.IsFalse(result.Success);

            Console.WriteLine(result.Message);
        }
Exemplo n.º 42
0
        private static void CommentProjection(IRawEventStoreClient store, ViewClient views)
        {
            var data = views.ReadAsJsonOrGetNew<CommentDistributionView>(CommentDistributionView.FileName);
            var processingInfo = views.ReadAsJsonOrGetNew<ProcessingInfoView>(CommentDistributionView.FileName + ".info");
            Console.WriteLine("Next comment offset: {0}", processingInfo.NextOffsetInBytes);
            while (true)
            {
                var nextOffset = processingInfo.NextOffsetInBytes;
                processingInfo.LastOffsetInBytes = processingInfo.NextOffsetInBytes;
                processingInfo.DateProcessingUtc = DateTime.UtcNow;

                var records = store.ReadAllEvents(new EventStoreOffset(nextOffset), 10000);
                var emptyData = true;
                foreach (var dataRecord in records)
                {
                    processingInfo.NextOffsetInBytes = dataRecord.Next.OffsetInBytes;
                    processingInfo.EventsProcessed += 1;

                    var user = User.TryGetFromBinary(dataRecord.EventData);
                    if (user != null)
                    {
                        data.Users[user.Id] = user;
                        emptyData = false;
                        continue;
                    }
                    var comment = Comment.TryGetFromBinary(dataRecord.EventData);

                    if (comment != null)
                    {

                        if (data.Distribution.ContainsKey(comment.UserId))
                            data.Distribution[comment.UserId] += 1;
                        else
                            data.Distribution[comment.UserId] = 1;
                        emptyData = false;
                    }

                }

                if (emptyData)
                {
                    views.WriteAsJson(processingInfo, CommentDistributionView.FileName + ".info");

                    Thread.Sleep(1000);
                }
                else
                {
                    try
                    {
                        views.WriteAsJson(data, CommentDistributionView.FileName);

                        views.WriteAsJson(processingInfo, CommentDistributionView.FileName + ".info");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception on writing view - {0}\r\n{1}", CommentDistributionView.FileName, ex.Message);
                    }

                    Console.WriteLine("Next comment offset: {0}", processingInfo.NextOffsetInBytes);
                }
            }
        }
Exemplo n.º 43
0
        private static void UserCommentsPerDayDistributionProjection(IRawEventStoreClient store, ViewClient views)
        {
            var data = views.ReadAsJsonOrGetNew<UserCommentsDistributionView>(UserCommentsDistributionView.FileName);
            var processingInfo =
                views.ReadAsJsonOrGetNew<ProcessingInfoView>(UserCommentsDistributionView.FileName + ".info");
            Console.WriteLine("Next user offset: {0}", processingInfo.NextOffsetInBytes);
            while (true)
            {
                var nextOffcet = processingInfo.NextOffsetInBytes;

                var records = store.ReadAllEvents(new EventStoreOffset(nextOffcet), 10000);
                var emptyData = true;
                foreach (var dataRecord in records)
                {
                    processingInfo.NextOffsetInBytes = dataRecord.Next.OffsetInBytes;

                    var user = User.TryGetFromBinary(dataRecord.EventData);
                    if (user != null)
                    {
                        data.Users[user.Id] = user;
                        emptyData = false;
                        continue;
                    }

                    var comment = Comment.TryGetFromBinary(dataRecord.EventData);
                    if (comment != null)
                    {

                        if (!data.Distribution.ContainsKey(comment.UserId))
                        {
                            data.Distribution.Add(comment.UserId, new long[7]);
                        }

                        var dayOfWeek = (int) comment.CreationDate.Date.DayOfWeek;
                        data.Distribution[comment.UserId][dayOfWeek]++;

                        processingInfo.EventsProcessed += 1;

                        emptyData = false;
                    }
                }

                if (emptyData)
                {
                    views.WriteAsJson(processingInfo, UserCommentsDistributionView.FileName + ".info");

                    Thread.Sleep(1000);
                }
                else
                {
                    try
                    {
                        views.WriteAsJson(data, UserCommentsDistributionView.FileName);

                        views.WriteAsJson(processingInfo, UserCommentsDistributionView.FileName + ".info");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception on writing view - {0}\r\n{1}", UserCommentsDistributionView.FileName, ex.Message);
                    }

                    Console.WriteLine("Next user offset: {0}", processingInfo.NextOffsetInBytes);
                }
            }
        }
Exemplo n.º 44
0
        private static void TagProjection(IRawEventStoreClient store, ViewClient views)
        {
            var data = views.ReadAsJsonOrGetNew<TagsDistributionView>(TagsDistributionView.FileName);
            var processingInfo = views.ReadAsJsonOrGetNew<ProcessingInfoView>(TagsDistributionView.FileName + ".info");
            Console.WriteLine("Next post offset: {0}", processingInfo.NextOffsetInBytes);
            while (true)
            {
                var nextOffcet = processingInfo.NextOffsetInBytes;
                processingInfo.LastOffsetInBytes = processingInfo.NextOffsetInBytes;
                processingInfo.DateProcessingUtc = DateTime.UtcNow;

                var records = store.ReadAllEvents(new EventStoreOffset(nextOffcet), 10000);
                var emptyData = true;
                foreach (var dataRecord in records)
                {
                    processingInfo.NextOffsetInBytes = dataRecord.Next.OffsetInBytes;

                    var post = Post.TryGetFromBinary(dataRecord.EventData);
                    if (post == null)
                        continue;

                    foreach (var tag in post.Tags)
                    {
                        if (data.Distribution.ContainsKey(tag))
                            data.Distribution[tag]++;
                        else
                            data.Distribution[tag] = 1;
                    }
                    processingInfo.EventsProcessed += 1;

                    emptyData = false;
                }

                if (emptyData)
                {
                    views.WriteAsJson(processingInfo, TagsDistributionView.FileName + ".info");

                    Thread.Sleep(1000);
                }
                else
                {
                    try
                    {
                        views.WriteAsJson(data, TagsDistributionView.FileName);

                        views.WriteAsJson(processingInfo, TagsDistributionView.FileName + ".info");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception on writing view - {0}\r\n{1}", TagsDistributionView.FileName, ex.Message);
                    }
                    Console.WriteLine("Next post offset: {0}", processingInfo.NextOffsetInBytes);
                }
            }
        }
        public void When_View_Is_Not_Found_404_Is_Returned()
        {
            var query = new ViewQuery().
                From("beer", "view_that_does_not_exist").
                Bucket("beer-sample").
                BaseUri(_baseUri);

            var client = new ViewClient(new HttpClient(),
                new JsonDataMapper(new ClientConfiguration()),
                new BucketConfig { Name = "beer-sample" },
                new ClientConfiguration());

            var result = client.Execute<dynamic>(query);

            Assert.IsNotNull(result.Message);
            Assert.AreEqual(HttpStatusCode.NotFound, result.StatusCode);
            Assert.IsFalse(result.Success);

            Console.WriteLine(result.Message);
        }
        public void Test_Geo_Spatial_View()
        {
            var query = new SpatialViewQuery().From("spatial", "routes")
                .BaseUri(ClientConfigUtil.GetConfiguration().Servers.First().ToString())
                .Bucket("travel-sample")
                .Stale(StaleState.False)
                .Limit(10)
                .Skip(0);

             var client = new ViewClient(new HttpClient(),
                new JsonDataMapper(ClientConfigUtil.GetConfiguration()),
                new BucketConfig { Name = "travel-sample" },
                new ClientConfiguration());

            var results = client.Execute<dynamic>(query);
            Assert.IsTrue(results.Success, results.Error);

        }
Exemplo n.º 47
0
        public void Test_ExecuteAsync()
        {
            var query = new ViewQuery().
                From("docs", "all_docs").
                Bucket("default");

            var client = new ViewClient(new HttpClient(),
                new JsonDataMapper(new ClientConfiguration()),
                new BucketConfig { Name = "beer-sample" },
                new ClientConfiguration());

            int n = 10000;
            var options = new ParallelOptions { MaxDegreeOfParallelism = 4};

            Parallel.For(0, n, options, async i =>
            {
                var result = await client.ExecuteAsync<dynamic>(query);
                Console.WriteLine("{0} {1} {2}", i, result.Success, result.Message);
            });
        }
Exemplo n.º 48
0
        public void When_Url_Is_Invalid_WebException_Is_Returned_2()
        {
            var query = new ViewQuery().
                From("beer", "brewery_beers").
                Bucket("beer-sample").
                BaseUri("http://192.168.62.200:8092/");

            var client = new ViewClient(new HttpClient(),
                new JsonDataMapper(new ClientConfiguration()),
                new BucketConfig { Name = "beer-sample" },
                new ClientConfiguration{ViewRequestTimeout = 5000});

            var result = client.Execute<dynamic>(query);
            Assert.IsNotNull(result.Rows);
            Assert.IsFalse(result.Success);
            Assert.AreEqual(HttpStatusCode.ServiceUnavailable, result.StatusCode);
            Assert.AreEqual(typeof(WebException), result.Exception.GetType());
        }