/// <summary> /// Sends a request for a N1QL query to the server. /// </summary> /// <typeparam name="T">The <see cref="Type" /> T of the body for each row (or document) result.</typeparam> /// <param name="queryRequest">A <see cref="IQueryRequest" /> object.</param> /// <returns></returns> async Task <IQueryResult <T> > IServer.SendAsync <T>(IQueryRequest queryRequest) { IQueryResult <T> result; if (_isDown) { result = HandleNodeUnavailable <T>(queryRequest); } else { try { queryRequest.BaseUri(CachedQueryBaseUri); result = await QueryClient.QueryAsync <T>(queryRequest).ContinueOnAnyContext(); } catch (Exception e) { MarkDead(); result = new QueryResult <T> { Exception = e, Message = e.Message, Success = false }; } } return(result); }
public void EnhancedPreparedStatements_defaults_to_false() { var context = new ClusterContext(new CancellationTokenSource(), new ClusterOptions()); var client = new QueryClient(context); Assert.False(client.EnhancedPreparedStatementsEnabled); }
public async Task Test_PrepareQueryAsync_CanCancel() { ConfigContextBase.QueryUris.Add(new FailureCountingUri("http://localhost")); // create hander that takes some time to return var httpClient = new HttpClient( FakeHttpMessageHandler.Create(request => { Thread.Sleep(TimeSpan.FromMilliseconds(200)); return(new HttpResponseMessage(HttpStatusCode.OK)); } )); var config = new ClientConfiguration(); var queryClient = new QueryClient( httpClient, new JsonDataMapper(config), config, new ConcurrentDictionary <string, QueryPlan>() ); var queryRequest = new QueryRequest("SELECT * FROM `default`;"); var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(100)); var result = await queryClient.PrepareAsync(queryRequest, cancellationTokenSource.Token); Assert.False(result.Success); Assert.NotNull(result.Exception); Assert.IsInstanceOf <OperationCanceledException>(result.Exception); }
private static void DrillThroughThreadSafe(QueryClient queryClient) { Excel.Range rngCell = queryClient.RangeCell; // create sheet Excel.Sheets sheets = xlApp.Sheets; Excel.Worksheet sheet = (Excel.Worksheet)sheets.Add(); // show message to user we are retrieving records Excel.Range rngHead = sheet.Range["A1"]; int maxDrillThroughRecords = ExcelHelper.GetMaxDrillthroughRecords(rngCell); rngHead.Value2 = string.Format("Retrieving TOP {0} records", maxDrillThroughRecords); // set up connection var connString = ExcelHelper.GetConnectionString(rngCell); var commandText = queryClient.GetDAXQuery(connString); var daxClient = new DaxClient(); var cnnStringBuilder = new TabularConnectionStringBuilder(connString); var cnn = new ADOMD.AdomdConnection(cnnStringBuilder.StrippedConnectionString); // retrieve result var dtResult = daxClient.ExecuteTable(commandText, cnn); // output result to sheet Excel.Range rngOut = sheet.Range["A3"]; ExcelHelper.FillRange(dtResult, rngOut); ExcelHelper.FormatRange(dtResult, rngOut); rngHead.Value2 = string.Format("Retrieved TOP {0} records", maxDrillThroughRecords); }
private static void OnUserQueryChanged(DependencyObject s, UserQueryEntity uc) { UserQueryPermission.ViewUserQuery.Authorize(); var currentEntity = UserAssetsClient.GetCurrentEntity(s); if (s is CountSearchControl csc) { csc.QueryName = QueryClient.GetQueryName(uc.Query.Key); using (currentEntity == null ? null : CurrentEntityConverter.SetCurrentEntity(currentEntity)) UserQueryClient.ToCountSearchControl(uc, csc); csc.Search(); return; } if (s is SearchControl sc && sc.ShowHeader == false) { sc.QueryName = QueryClient.GetQueryName(uc.Query.Key); using (currentEntity == null ? null : CurrentEntityConverter.SetCurrentEntity(currentEntity)) UserQueryClient.ToSearchControl(uc, sc); sc.Search(); return; } return; }
public IQueryResult <IQueryPlan> Prepare(IQueryRequest toPrepare) { var uri = new Uri(GetBaseQueryUri()); toPrepare.BaseUri(uri); return(QueryClient.Prepare(toPrepare)); }
public async Task <IActionResult> Registration([Bind("Login, Password")] User user) { var values = new JObject(); values.Add("Login", user.Login); values.Add("Password", user.Password); values.Add("Role", "User"); string usr = HttpContext.Session.GetString("Login"); usr = usr != null ? usr : ""; try { var result = await QueryClient.SendQueryToService(HttpMethod.Post, "http://localhost:54196", "/api/Users", null, values); User resultUser = JsonConvert.DeserializeObject <User>(result); StatisticSender.SendStatistic("Home", DateTime.Now, "Registration", Request.HttpContext.Connection.RemoteIpAddress.ToString(), true, usr); return(RedirectToAction("Authorisation")); } catch { StatisticSender.SendStatistic("Home", DateTime.Now, "Registration", Request.HttpContext.Connection.RemoteIpAddress.ToString(), false, usr); return(View("Error", "Cannot create this User. Try again later or input another Data")); } }
public static void Start() { if (Navigator.Manager.NotDefined(MethodInfo.GetCurrentMethod())) { TypeClient.Start(); QueryClient.Start(); Navigator.AddSetting(new EntitySettings <UserQueryEntity> { View = _ => new UserQuery(), Icon = ExtensionsImageLoader.GetImageSortName("userQuery.png") }); SearchControl.GetMenuItems += SearchControl_GetCustomMenuItems; UserAssetsClient.Start(); UserAssetsClient.RegisterExportAssertLink <UserQueryEntity>(); Constructor.Register <UserQueryEntity>(ctx => { MessageBox.Show(Window.GetWindow(ctx.Element), ChartMessage._0CanOnlyBeCreatedFromTheSearchWindow.NiceToString().FormatWith(typeof(UserQueryEntity).NicePluralName()), ChartMessage.CreateNew.NiceToString(), MessageBoxButton.OK, MessageBoxImage.Information); return(null); }); LinksClient.RegisterEntityLinks <Entity>((entity, ctrl) => { if (!UserQueryPermission.ViewUserQuery.IsAuthorized()) { return(null); } return(Server.Return((IUserQueryServer us) => us.GetUserQueriesEntity(entity.EntityType)) .Select(cp => new UserQueryQuickLink(cp, entity)).ToArray()); }); } }
public void When_AdHoc_Is_True_Client_Doesnt_Cache() { var config = new ClientConfiguration(); var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); var request = QueryRequest.Create("SELECT * from `beer-sample` LIMIT 100"). BaseUri(new Uri(string.Format("http://{0}:8093/query", _server))). Pretty(false); var stopWatch = new Stopwatch(); stopWatch.Start(); var result = client.Query <dynamic>(request); stopWatch.Stop(); Console.WriteLine("Elasped time 1:{0}", stopWatch.ElapsedMilliseconds); stopWatch = new Stopwatch(); stopWatch.Restart(); result = client.Query <dynamic>(request); stopWatch.Stop(); Console.WriteLine("Elasped time 2:{0}", stopWatch.ElapsedMilliseconds); stopWatch = new Stopwatch(); stopWatch.Restart(); result = client.Query <dynamic>(request); stopWatch.Stop(); Console.WriteLine("Elasped time 3:{0}", stopWatch.ElapsedMilliseconds); Assert.AreEqual(QueryStatus.Success, result.Status); }
public static void Start(bool toExcel, bool excelReport) { if (Navigator.Manager.NotDefined(MethodInfo.GetCurrentMethod())) { if (excelReport) { if (toExcel) { SearchControl.GetMenuItems += sc => (sc.QueryName as Type) == typeof(ExcelReportEntity) ? null : ExcelMenuItemConstructor.Construct(sc, PlainExcelMenuItemConstructor.Construct(sc)); } else { SearchControl.GetMenuItems += sc => (sc.QueryName as Type) == typeof(ExcelReportEntity) ? null : ExcelMenuItemConstructor.Construct(sc, null); } QueryClient.Start(); Navigator.AddSetting(new EntitySettings <ExcelReportEntity> { View = e => new ExcelReport() }); } else { if (toExcel) { SearchControl.GetMenuItems += sc => PlainExcelMenuItemConstructor.Construct(sc); } } } }
public async Task <IEnumerable <SearchResultItem> > SearchAsync(string searchText, int projectId) { var query = new SearchQuery(searchText) { SearchFields = "id,title,details,tags,events", Select = "id", }; if (projectId != default(int)) { query.Filter = string.Format("projectid eq '{0}'", projectId); } var result = await QueryClient.SearchAsync(IndexName, query); if (result.IsSuccess) { return (result.Body.Records.Select( r => new SearchResultItem { Id = int.Parse((string)r.Properties["id"]), SearchScore = (float)r.Score })); } return(new SearchResultItem[0]); }
/// <summary> /// If the node is strictly a query node, this method will send a simple statement to /// be executed. If it returns successfully, then the node will be marked as not /// <see cref="_isDown">down</see> and put back into rotation. /// </summary> void CheckQueryNode() { try { var query = new QueryRequest("SELECT 'PING!'").BaseUri(CachedQueryBaseUri); var result = QueryClient.Query <dynamic>(query); if (result.Success) { Log.InfoFormat("Successfully connected and marking query node {0} as up.", EndPoint); _isDown = false; } else { Log.InfoFormat("The query node {0} is still down: {1}", EndPoint, result.Status); } } catch (Exception e) { Log.InfoFormat("The query node {0} is still down: {1}", EndPoint, e.Message); //the node is down or unreachable _isDown = true; Log.Debug(e); } finally { StartHeartbeatTimer(); } }
public override void Render(float dt) { if (game.reconnect) { game.Dispose(); menu.StartGame(singleplayer, singleplayerSavePath, connectData); return; } if (game.exitToMainMenu) { game.Dispose(); if (game.GetRedirect() != null) { //Query new server for public key QueryClient qclient = new QueryClient(); qclient.SetPlatform(platform); qclient.PerformQuery(game.GetRedirect().GetIP(), game.GetRedirect().GetPort()); if (qclient.queryPerformed && !qclient.querySuccess) { //Query did not succeed. Back to main menu platform.MessageBoxShowError(qclient.GetServerMessage(), "Redirection error"); menu.StartMainMenu(); return; } QueryResult qresult = qclient.GetResult(); //Get auth hash for new server LoginClientCi lic = new LoginClientCi(); LoginData lidata = new LoginData(); string token = platform.StringSplit(qresult.PublicHash, "=", new IntRef())[1]; lic.Login(platform, connectData.Username, "", token, platform.GetPreferences().GetString("Password", ""), new LoginResultRef(), lidata); while (lic.loginResult.value == LoginResult.Connecting) { lic.Update(platform); } //Check if login was successful if (!lidata.ServerCorrect) { //Invalid server adress platform.MessageBoxShowError("Invalid server address!", "Redirection error!"); menu.StartMainMenu(); } else if (!lidata.PasswordCorrect) { //Authentication failed menu.StartLogin(token, null, 0); } else if (lidata.ServerAddress != null && lidata.ServerAddress != "") { //Finally switch to the new server menu.ConnectToGame(lidata, connectData.Username); } } else { menu.StartMainMenu(); } return; } game.OnRenderFrame(dt); }
protected override void ProcessRecord() { base.ProcessRecord(); try { client?.Dispose(); int timeout = GetPreferredTimeout(); WriteDebug($"Cmdlet Timeout : {timeout} milliseconds."); client = new QueryClient(AuthProvider, new Oci.Common.ClientConfiguration { RetryConfiguration = retryConfig, TimeoutMillis = timeout, ClientUserAgent = PSUserAgent }); string region = GetPreferredRegion(); if (region != null) { WriteDebug("Choosing Region:" + region); client.SetRegion(region); } if (Endpoint != null) { WriteDebug("Choosing Endpoint:" + Endpoint); client.SetEndpoint(Endpoint); } } catch (Exception ex) { TerminatingErrorDuringExecution(ex); } }
public async Task Test_QueryAsync_CanCancel() { var cancellationTokenSource = new CancellationTokenSource(); var context = ContextFactory.GetCouchbaseContext(); context.QueryUris.Add(new FailureCountingUri("http://localhost")); // create hander that takes some time to return var httpClient = new HttpClient( FakeHttpMessageHandler.Create(request => { cancellationTokenSource.Cancel(true); return(new HttpResponseMessage(HttpStatusCode.OK)); } )); var config = new ClientConfiguration(); var queryClient = new QueryClient( httpClient, new JsonDataMapper(config), new ConcurrentDictionary <string, QueryPlan>(), context ); var queryRequest = new QueryRequest("SELECT * FROM `default`;"); var result = await queryClient.QueryAsync <dynamic>(queryRequest, cancellationTokenSource.Token); Assert.False(result.Success); Assert.NotNull(result.Exception); Assert.IsInstanceOf <OperationCanceledException>(result.Exception); }
public async Task PrepareAsync_Sets_LastActivity() { var context = ContextFactory.GetCouchbaseContext(); context.QueryUris.Add(new FailureCountingUri("http://localhost")); var httpClient = new HttpClient( FakeHttpMessageHandler.Create(request => new HttpResponseMessage(HttpStatusCode.OK)) ); var config = new ClientConfiguration(); var client = new QueryClient( httpClient, new JsonDataMapper(config), new ConcurrentDictionary <string, QueryPlan>(), context ); Assert.IsNull(client.LastActivity); var queryRequest = new QueryRequest("SELECT * FROM `default`;"); await client.PrepareAsync(queryRequest, CancellationToken.None); Assert.IsNotNull(client.LastActivity); }
/// <summary> /// Sends a request for a N1QL query to the server. /// </summary> /// <typeparam name="T">The <see cref="Type" /> T of the body for each row (or document) result.</typeparam> /// <param name="queryRequest">A <see cref="IQueryRequest" /> object.</param> /// <param name="cancellationToken">Token which can cancel the query.</param> /// <returns></returns> async Task <IQueryResult <T> > IServer.SendAsync <T>(IQueryRequest queryRequest, CancellationToken cancellationToken) { IQueryResult <T> result; if (_isDown) { result = HandleNodeUnavailable <T>(queryRequest); } else { try { queryRequest.BaseUri(CachedQueryBaseUri); if (queryRequest.IsStreaming) { result = await _streamingQueryClient.QueryAsync <T>(queryRequest, cancellationToken).ContinueOnAnyContext(); } else { result = await QueryClient.QueryAsync <T>(queryRequest, cancellationToken).ContinueOnAnyContext(); } } catch (Exception e) { result = new QueryResult <T> { Exception = e, Message = e.Message, Success = false }; } } return(result); }
public IActionResult EditeProduct(int?id) { string result = QueryClient.SendQueryToService(HttpMethod.Get, RabbitDLL.Linker.Products, "/api/Products/" + id, null, null).Result; Product objectToView = JsonConvert.DeserializeObject <Product>(result); return(View(objectToView)); }
public QueryResponce <T> DoQuery() { var urlGenerator = new UrlGenerator() { Options = Options, StructureType = typeof(T) }; var url = urlGenerator.GetUrl(); var client = new QueryClient() { Url = url }; var textResult = ""; textResult = client.DoQuery(); if (string.IsNullOrEmpty(textResult)) { var nullResult = new QueryResponce <T>() { Data = new List <T>(), Length = 0, Pagination = null, Url = url }; return(nullResult); } var json = JsonConvert.DeserializeObject <QueryResponce <T> >(textResult); json.Url = url; return(json); }
private void UpdateKnownNodes() { var nodes2Add = new List <ServerAddress>(); foreach (var n in node.knownNodes) { try { var nodeList = new QueryClient(n).RequestNodes(); foreach (var newN in nodeList) { if (!node.knownNodes.Contains(newN) && !nodes2Add.Contains(newN)) { nodes2Add.Add(newN); } } } catch (RpcException) { } } foreach (var n in nodes2Add) { node.AddServerAddress(n); } }
/// <summary> /// Sends a request for a N1QL query to the server asynchronously. /// </summary> /// <typeparam name="T">The <see cref="Type" /> T of the body for each row (or document) result.</typeparam> /// <param name="queryRequest">A <see cref="IQueryRequest" /> object.</param> /// <returns> /// An <see cref="Task{IQueryResult}" /> object representing the asynchronous operation. /// </returns> IQueryResult <T> IServer.Send <T>(IQueryRequest queryRequest) { IQueryResult <T> result; if (_isDown) { result = HandleNodeUnavailable <T>(queryRequest); } else { try { queryRequest.BaseUri(CachedQueryBaseUri); // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression if (queryRequest.IsStreaming) { result = _streamingQueryClient.Query <T>(queryRequest); } else { result = QueryClient.Query <T>(queryRequest); } } catch (Exception e) { result = new QueryResult <T> { Exception = e, Message = e.Message, Success = false, }; } } return(result); }
public static async Task Main(string[] args) { Console.WriteLine("Hello, press [Enter] to proceed..."); Console.ReadLine(); var commandClient = new CommandClient("https://commandquery-sample-azurefunctions-vs2.azurewebsites.net/api/command/", x => { x.MaxResponseContentBufferSize = 1000000; }); var queryClient = new QueryClient("https://commandquery-sample-azurefunctions-vs2.azurewebsites.net/api/query/"); commandClient.Post(new FooCommand { Value = "sv-SE" }); queryClient.Post(new BarQuery { Id = 1 }).Log(); queryClient.Get(new BarQuery { Id = 1 }).Log(); await commandClient.PostAsync(new FooCommand { Value = "en-GB" }); (await queryClient.PostAsync(new BarQuery { Id = 1 })).Log(); (await queryClient.GetAsync(new BarQuery { Id = 1 })).Log(); Console.WriteLine("Press [Enter] to exit"); Console.ReadLine(); }
public async Task <BatchRequest> AddToCurrentBatchAsync(ODataQuery <TModel> query) { // We always refresh the EntityInfo object accordingly to the current query EntityInfo = EntityManager.GetClassInfo <TModel>(typeof(TModel), null, this.Parent, query.Fields.ToArray()); var batchParent = Parent; // In case a model can be used from different contexts (e.g. ContentType can be used from Web, but also from List) // it's required to let the entity know this context so that it can provide the correct information when requested if (batchParent != null) { // Replicate the parent object in order to keep original collection as is batchParent = EntityManager.ReplicateParentHierarchy(batchParent, PnPContext); EntityInfo.Target = batchParent.GetType(); } // and its concrete instance var concreteEntity = EntityManager.GetEntityConcreteInstance(typeof(TModel), batchParent); // Ensure the passed model has a PnPContext set if (concreteEntity is IDataModelWithContext d && d.PnPContext == null) { d.PnPContext = PnPContext; } // Get the parent (container) entity info var parentEntityInfo = EntityManager.Instance.GetStaticClassInfo(batchParent.GetType()); // and cast it to the IDataModelMappingHandler interface var parentEntityWithMappingHandlers = (IDataModelMappingHandler)batchParent; // Build the needed API call ApiCallRequest apiCallRequest = await QueryClient.BuildGetAPICallAsync <TModel>(concreteEntity as BaseDataModel <TModel>, EntityInfo, query, default, false, true).ConfigureAwait(false);
/// <summary> /// Sends a request for a N1QL query to the server asynchronously. /// </summary> /// <typeparam name="T">The <see cref="Type" /> T of the body for each row (or document) result.</typeparam> /// <param name="queryRequest">A <see cref="IQueryRequest" /> object.</param> /// <returns> /// An <see cref="Task{IQueryResult}" /> object representing the asynchronous operation. /// </returns> IQueryResult <T> IServer.Send <T>(IQueryRequest queryRequest) { IQueryResult <T> result; if (_isDown) { result = HandleNodeUnavailable <T>(queryRequest); } else { try { queryRequest.BaseUri(CachedQueryBaseUri); result = QueryClient.Query <T>(queryRequest); } catch (Exception e) { MarkDead(); result = new QueryResult <T> { Exception = e, Message = e.Message, Success = false, }; } } return(result); }
public void EnhancedPreparedStatements_is_set_to_true_if_enabled_in_cluster_caps() { var httpClient = new CouchbaseHttpClient(new HttpClientHandler()) { BaseAddress = new Uri("http://localhost:8091") }; var mockServiceUriProvider = new Mock <IServiceUriProvider>(); mockServiceUriProvider .Setup(m => m.GetRandomQueryUri()) .Returns(new Uri("http://localhost:8093")); var client = new QueryClient(httpClient, mockServiceUriProvider.Object, new DefaultSerializer(), new Mock <ILogger <QueryClient> >().Object, NoopRequestTracer.Instance); Assert.False(client.EnhancedPreparedStatementsEnabled); var clusterCapabilities = new ClusterCapabilities { Capabilities = new Dictionary <string, IEnumerable <string> > { { ServiceType.Query.GetDescription(), new List <string> { ClusterCapabilityFeatures.EnhancedPreparedStatements.GetDescription() } } } }; client.UpdateClusterCapabilities(clusterCapabilities); Assert.True(client.EnhancedPreparedStatementsEnabled); }
public void Test_Create_Index() { var config = new ClientConfiguration(); var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); var uri = new Uri(string.Format("http://{0}:8093/query", _server)); var indexes = client.Query <dynamic>(new QueryRequest("SELECT name FROM system:keyspaces").BaseUri(uri)); foreach (var row in indexes.Rows) { if (row.GetValue("name").Value == "beer-sample") { client.Query <dynamic>(new QueryRequest("DROP PRIMARY INDEX ON `beer-sample`").BaseUri(uri)); } } var query = new QueryRequest("CREATE PRIMARY INDEX ON `beer-sample`") .BaseUri(uri) .Timeout(new TimeSpan(0, 0, 0, 60)); var result = client.Query <dynamic>(query); Assert.IsNotNull(result); Assert.IsTrue(result.Success, result.GetErrorsAsString()); Assert.IsNotNull(result.Rows); }
public Task <IQueryResult <T> > SendAsync <T>(string query) { var uri = new Uri(GetBaseQueryUri()); var task = QueryClient.QueryAsync <T>(uri, query); return(task); }
public void when_configuring_the_client() { var client = new QueryClient("http://example.com", x => x.BaseAddress = new Uri("https://commandquery-sample-azurefunctions-vs2.azurewebsites.net/api/query/")); client.Post(new BarQuery { Id = 1 }); }
internal static UserQueryEntity FromSearchControl(SearchControl searchControl) { QueryDescription description = DynamicQueryServer.GetQueryDescription(searchControl.QueryName); return(searchControl.GetQueryRequest(true).ToUserQuery(description, QueryClient.GetQuery(searchControl.QueryName), FindOptions.DefaultPagination, searchControl.SimpleFilterBuilder != null)); }
/// <summary> /// Sends a request for a N1QL query to the server. /// </summary> /// <typeparam name="T">The <see cref="Type" /> T of the body for each row (or document) result.</typeparam> /// <param name="queryRequest">A <see cref="IQueryRequest" /> object.</param> /// <returns></returns> Task <IQueryResult <T> > IServer.SendAsync <T>(IQueryRequest queryRequest) { if (queryRequest.GetBaseUri() == null) { var uri = new Uri(GetBaseQueryUri()); queryRequest.BaseUri(uri); } return(QueryClient.QueryAsync <T>(queryRequest)); }
public void TestQuery_HelloWorld() { var client = new QueryClient(new HttpClient(), new JsonDataMapper()); var uri = new Uri("http://localhost:8093/query"); const string query = "SELECT 'Hello World' AS Greeting"; var result = client.Query<dynamic>(uri, query); Assert.IsNotNull(result); Assert.AreEqual("Hello World", result.Rows.First().Greeting.ToString()); }
public void TestQuery_Select_Children_Poco() { var client = new QueryClient(new HttpClient(), new JsonDataMapper()); var uri = new Uri("http://localhost:8093/query"); const string query = "SELECT c.children FROM tutorial as c"; var result = client.Query<Contact>(uri, query); Assert.IsNotNull(result); Assert.IsTrue(result.Success); Assert.IsNotNull(result.Rows); }
public void Test_Query_HelloWorld_BareStringRequet() { var config = new ClientConfiguration(); var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); var uri = new Uri(string.Format("http://{0}:8093/query", _server)); var query = "SELECT 'Hello World' AS Greeting"; var result = client.Query<dynamic>(uri, query); Assert.IsNotNull(result); Assert.AreEqual("Hello World", result.Rows.First().Greeting.ToString()); }
public void TestQuery_Incorrect_Syntax() { var client = new QueryClient(new HttpClient(), new JsonDataMapper()); var uri = new Uri("http://localhost:8093/query"); const string query = "SELECT 'Hello World' ASB Greeting"; var result = client.Query<dynamic>(uri, query); Assert.IsNotNull(result); Assert.IsFalse(result.Success); Assert.IsEmpty(result.Rows); }
public void Test_Query_Incorrect_Syntax() { var config = new ClientConfiguration(); var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); var uri = new Uri(string.Format("http://{0}:8093/query", _server)); var query = new QueryRequest("SELECT 'Hello World' ASB Greeting").BaseUri(uri); var result = client.Query<dynamic>(query); Assert.IsNotNull(result); Assert.IsFalse(result.Success); Assert.IsEmpty(result.Rows); }
public void Test_Query_HelloWorld_Async() { var config = new ClientConfiguration(); var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); var uri = new Uri(string.Format("http://{0}:8093/query", _server)); var query = new QueryRequest("SELECT 'Hello World' AS Greeting").BaseUri(uri); var task = client.QueryAsync<dynamic>(query); task.Wait(); var result = task.Result; Assert.IsNotNull(result); Assert.AreEqual("Hello World", result.Rows.First().Greeting.ToString()); }
public void Test_Select_Children() { var config = new ClientConfiguration(); var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); var uri = new Uri("http://localhost:8093/query"); const string bucket = "tutorial"; var query = from c in client.Queryable<Contact>(bucket, uri) select c.Children; foreach (var child in query) { Console.WriteLine("{0}, {1}", child, child); } }
public void Test_POCO_Projection() { var config = new ClientConfiguration(); var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); var uri = new Uri("http://localhost:8093/query"); const string bucket = "tutorial"; var query = from c in client.Queryable<Contact>(bucket, uri) select c; foreach (var contact in query) { Console.WriteLine(contact.FirstName); } }
public void Test_Query_Select_Where_Type_Is_Beer_As_Poco() { var config = new ClientConfiguration(); var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); var uri = new Uri(string.Format("http://{0}:8093/query", _server)); var query = new QueryRequest( "SELECT abv, brewery_id, category, description, ibu, name, srm, style, type, upc, updated " + "FROM `beer-sample` as beer " + "WHERE beer.type='beer' LIMIT 10").BaseUri(uri); var result = client.Query<Beer>(query); Assert.IsNotNull(result); Assert.IsTrue(result.Success); Assert.IsNotNull(result.Rows); var beer = result.Rows.First(); Assert.IsNotNullOrEmpty(beer.Name); }
public void GetDataMapper_IQueryRequest_ReturnsClientDataMapper() { // Arrange var dataMapper = new Mock<IDataMapper>(); var queryRequest = new Mock<IQueryRequest>(); var queryClient = new QueryClient(new HttpClient(), dataMapper.Object, new ClientConfiguration(), new ConcurrentDictionary<string, QueryPlan>()); // Act var result = queryClient.GetDataMapper(queryRequest.Object); // Assert Assert.AreEqual(dataMapper.Object, result); }
public void Test_AnonymousType_Projection() { var config = new ClientConfiguration(); var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); var uri = new Uri("http://localhost:8093/query"); const string bucket = "tutorial"; var query = from c in client.Queryable<Contact>(bucket, uri) select new { age = c.Age, fname = c.FirstName }; foreach (var contact in query) { Console.WriteLine("{0}, {1}", contact.fname, contact.age); } }
public void GetDataMapper_IQueryRequestWithDataMapper_NoDataMapper_ReturnsClientDataMapper() { // Arrange var clientDataMapper = new Mock<IDataMapper>(); var queryRequest = new Mock<IQueryRequestWithDataMapper>(); queryRequest.SetupProperty(p => p.DataMapper, null); var queryClient = new QueryClient(new HttpClient(), clientDataMapper.Object, new ClientConfiguration(), new ConcurrentDictionary<string, QueryPlan>()); // Act var result = queryClient.GetDataMapper(queryRequest.Object); // Assert Assert.AreEqual(clientDataMapper.Object, result); }
public void Test_Create_Index() { var config = new ClientConfiguration(); var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); var uri = new Uri(string.Format("http://{0}:8093/query", _server)); var indexes = client.Query<dynamic>(new QueryRequest("SELECT name FROM system:keyspaces").BaseUri(uri)); foreach (var row in indexes.Rows) { if (row.GetValue("name").Value == "beer-sample") { client.Query<dynamic>(new QueryRequest("DROP PRIMARY INDEX ON `beer-sample`").BaseUri(uri)); } } var query = new QueryRequest("CREATE PRIMARY INDEX ON `beer-sample`") .BaseUri(uri) .Timeout(new TimeSpan(0, 0, 0, 60)); var result = client.Query<dynamic>(query); Assert.IsNotNull(result); Assert.IsTrue(result.Success, result.GetErrorsAsString()); Assert.IsNotNull(result.Rows); }
public void Test_Query_Select_All_Where_Type_Is_Beer() { var config = new ClientConfiguration(); var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); var uri = new Uri(string.Format("http://{0}:8093/query", _server)); var query = new QueryRequest("SELECT type, meta FROM `beer-sample` as d WHERE d.type='beer' LIMIT 10") .BaseUri(uri); var result = client.Query<dynamic>(query); Assert.IsNotNull(result); Assert.IsTrue(result.Success); Assert.IsNotNull(result.Rows); }
public override void Render(float dt) { if (game.reconnect) { game.Dispose(); menu.StartGame(singleplayer, singleplayerSavePath, connectData); return; } if (game.exitToMainMenu) { game.Dispose(); if (game.GetRedirect() != null) { //Query new server for public key QueryClient qclient = new QueryClient(); qclient.SetPlatform(platform); qclient.PerformQuery(game.GetRedirect().GetIP(), game.GetRedirect().GetPort()); QueryResult qresult = qclient.GetResult(); if (qresult == null) { //If query fails show error message and go back to main menu platform.MessageBoxShowError(qclient.GetServerMessage(), "Redirection error"); menu.StartMainMenu(); return; } //Get auth hash for new server LoginClientCi lic = new LoginClientCi(); LoginData lidata = new LoginData(); string token = platform.StringSplit(qresult.PublicHash, "=", new IntRef())[1]; lic.Login(platform, connectData.Username, "", token, platform.GetPreferences().GetString("Password", ""), new LoginResultRef(), lidata); while (lic.loginResult.value == LoginResult.Connecting) { lic.Update(platform); } //Check if login was successful if (!lidata.ServerCorrect) { //Invalid server adress platform.MessageBoxShowError("Invalid server address!", "Redirection error!"); menu.StartMainMenu(); } else if (!lidata.PasswordCorrect) { //Authentication failed menu.StartLogin(token, null, 0); } else if (lidata.ServerAddress != null && lidata.ServerAddress != "") { //Finally switch to the new server menu.ConnectToGame(lidata, connectData.Username); } } else { menu.StartMainMenu(); } return; } game.OnRenderFrame(dt); }
void DownloadServerThumbnail(object o) { ThumbnailDownloadArgs args = (ThumbnailDownloadArgs)o; //Fetch server info from given adress QueryClient qClient = new QueryClient(); qClient.SetPlatform(this); qClient.PerformQuery(args.ip, args.port); if (qClient.querySuccess) { //Received a result QueryResult r = qClient.GetResult(); args.response.data = r.ServerThumbnail; args.response.dataLength = r.ServerThumbnail.Length; args.response.serverMessage = qClient.GetServerMessage(); args.response.done = true; } else { //Did not receive a response args.response.error = true; } }
public void When_Prepared_Is_True_Client_Uses_Prepared_Statement() { var config = new ClientConfiguration(); var serverUri = new Uri(string.Format("http://{0}:8093/query", _server)); const string statement = "SELECT * from `beer-sample` LIMIT 100"; var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); var normalRequest = QueryRequest.Create(statement). BaseUri(serverUri). Pretty(false); var preparedRequest = QueryRequest.Create(). //will set the plan later BaseUri(serverUri). Pretty(false); var stopWatch = new Stopwatch(); stopWatch.Start(); var resultNormal = client.Query<dynamic>(normalRequest); stopWatch.Stop(); Console.WriteLine("Elasped time normal request:{0}", stopWatch.ElapsedMilliseconds); stopWatch = new Stopwatch(); stopWatch.Restart(); var plan = client.Prepare(normalRequest).Rows.First(); preparedRequest.Prepared(plan). BaseUri(serverUri). Pretty(false); var resultPrepareExecute = client.Query<dynamic>(preparedRequest); stopWatch.Stop(); Console.WriteLine("Elasped time prepare statement + execute 1:{0}", stopWatch.ElapsedMilliseconds); stopWatch = new Stopwatch(); stopWatch.Restart(); var resultExecute = client.Query<dynamic>(preparedRequest); stopWatch.Stop(); Console.WriteLine("Elasped time execute 2:{0}", stopWatch.ElapsedMilliseconds); Assert.IsTrue(preparedRequest.IsPrepared); Assert.IsFalse(normalRequest.IsPrepared); Assert.AreEqual(QueryStatus.Success, resultNormal.Status); Assert.AreEqual(QueryStatus.Success, resultPrepareExecute.Status); Assert.AreEqual(QueryStatus.Success, resultExecute.Status); }
internal void ClientCommand(string s_) { if (s_ == "") { return; } IntRef ssCount = new IntRef(); string[] ss = platform.StringSplit(s_, " ", ssCount); if (StringTools.StringStartsWith(platform, s_, ".")) { string strFreemoveNotAllowed = language.FreemoveNotAllowed(); //try { string cmd = StringTools.StringSubstringToEnd(platform, ss[0], 1); string arguments; if (platform.StringIndexOf(s_, " ") == -1) { arguments = ""; } else { arguments = StringTools.StringSubstringToEnd(platform, s_, platform.StringIndexOf(s_, " ")); } arguments = platform.StringTrim(arguments); if (cmd == "pos") { ENABLE_DRAWPOSITION = BoolCommandArgument(arguments); } else if (cmd == "fog") { int foglevel; foglevel = platform.IntParse(arguments); //if (foglevel <= 16) //{ // terrain.DrawDistance = (int)Math.Pow(2, foglevel); //} //else { int foglevel2 = foglevel; if (foglevel2 > 1024) { foglevel2 = 1024; } if (foglevel2 % 2 == 0) { foglevel2--; } d_Config3d.viewdistance = foglevel2; //terrain.UpdateAllTiles(); } OnResize(); } else if (cmd == "noclip") { controls.noclip = BoolCommandArgument(arguments); } else if (cmd == "freemove") { if (this.AllowFreemove) { controls.freemove = BoolCommandArgument(arguments); } else { Log(strFreemoveNotAllowed); return; } } else if (cmd == "fov") { int arg = platform.IntParse(arguments); int minfov = 1; int maxfov = 179; if (!issingleplayer) { minfov = 60; } if (arg < minfov || arg > maxfov) { platform.ThrowException(platform.StringFormat2("Valid field of view: {0}-{1}", platform.IntToString(minfov), platform.IntToString(maxfov))); } float fov_ = (2 * Game.GetPi() * (one * arg / 360)); this.fov = fov_; OnResize(); } else if (cmd == "clients") { Log("Clients:"); for (int i = 0; i < entitiesCount; i++) { Entity entity = entities[i]; if (entity == null) { continue; } if (entity.drawName == null) { continue; } if (!entity.drawName.ClientAutoComplete) { continue; } Log(platform.StringFormat2("{0} {1}", platform.IntToString(i), entities[i].drawName.Name)); } } else if (cmd == "movespeed") { //try //{ if (this.AllowFreemove) { if (platform.FloatParse(arguments) <= 500) { movespeed = basemovespeed * platform.FloatParse(arguments); AddChatline(platform.StringFormat("Movespeed: {0}x", arguments)); } else { AddChatline("Entered movespeed to high! max. 500x"); } } else { Log(strFreemoveNotAllowed); return; } //} //catch //{ // AddChatline("Invalid value!"); // AddChatline("USE: .movespeed [movespeed]"); //} } else if (cmd == "gui") { ENABLE_DRAW2D = BoolCommandArgument(arguments); } else if (cmd == "reconnect") { Reconnect(); } else if (cmd == "m") { mouseSmoothing = !mouseSmoothing; if (mouseSmoothing) { Log("Mouse smoothing enabled."); } else { Log("Mouse smoothing disabled."); } } else if (cmd == "serverinfo") { //Fetches server info from given adress IntRef splitCount = new IntRef(); string[] split = platform.StringSplit(arguments, ":", splitCount); if (splitCount.value == 2) { QueryClient qClient = new QueryClient(); qClient.SetPlatform(platform); qClient.PerformQuery(split[0], platform.IntParse(split[1])); if (qClient.querySuccess) { //Received result QueryResult r = qClient.GetResult(); AddChatline(r.GameMode); AddChatline(platform.IntToString(r.MapSizeX)); AddChatline(platform.IntToString(r.MapSizeY)); AddChatline(platform.IntToString(r.MapSizeZ)); AddChatline(platform.IntToString(r.MaxPlayers)); AddChatline(r.MOTD); AddChatline(r.Name); AddChatline(platform.IntToString(r.PlayerCount)); AddChatline(r.PlayerList); AddChatline(platform.IntToString(r.Port)); AddChatline(r.PublicHash); AddChatline(r.ServerVersion); } AddChatline(qClient.GetServerMessage()); } } else { for (int i = 0; i < clientmodsCount; i++) { ClientCommandArgs args = new ClientCommandArgs(); args.arguments = arguments; args.command = cmd; clientmods[i].OnClientCommand(this, args); } string chatline = StringTools.StringSubstring(platform, GuiTypingBuffer, 0, MathCi.MinInt(GuiTypingBuffer.Length, 256)); SendChat(chatline); } } //catch (Exception e) { AddChatline(new StringReader(e.Message).ReadLine()); } } else { string chatline = StringTools.StringSubstring(platform, GuiTypingBuffer, 0, MathCi.MinInt(StringTools.StringLength(platform, GuiTypingBuffer), 4096)); SendChat(chatline); } }
public async void Test_QueryAsync_POST_Positional_Parameters() { var config = new ClientConfiguration(); var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); var request = QueryRequest.Create("SELECT * from `beer-sample` WHERE type=$1 LIMIT 10"). BaseUri(new Uri(string.Format("http://{0}:8093/query", _server))). Pretty(false). AddPositionalParameter("beer"); var result = await client.QueryAsync<dynamic>(request); Assert.AreEqual(QueryStatus.Success, result.Status); Assert.AreEqual(10, result.Rows.Count); foreach (var row in result.Rows) { Console.WriteLine(row); } }
public void When_AdHoc_Is_False_Client_Uses_Prepared_Statement() { var config = new ClientConfiguration(); var serverUri = new Uri(string.Format("http://{0}:8093/query", _server)); const string statement = "SELECT * from `beer-sample` LIMIT 100"; var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); var normalRequest = QueryRequest.Create(statement). BaseUri(serverUri). Pretty(false); var preparedRequest = QueryRequest.Create(statement). AdHoc(false). BaseUri(serverUri). Pretty(false); var stopWatch = new Stopwatch(); stopWatch.Start(); var resultNormal = client.Query<dynamic>(normalRequest); stopWatch.Stop(); Console.WriteLine("Elasped time normal request:{0}", stopWatch.ElapsedMilliseconds); stopWatch = new Stopwatch(); stopWatch.Restart(); var resultPrepareExecute = client.Query<dynamic>(preparedRequest); stopWatch.Stop(); Console.WriteLine("Elasped time prepare statement + execute 1:{0}", stopWatch.ElapsedMilliseconds); stopWatch = new Stopwatch(); stopWatch.Restart(); var resultExecute = client.Query<dynamic>(preparedRequest); stopWatch.Stop(); Console.WriteLine("Elasped time execute 2:{0}", stopWatch.ElapsedMilliseconds); Assert.IsTrue(preparedRequest.IsPrepared); Assert.IsNull(preparedRequest.GetStatement()); Assert.IsNotNull(preparedRequest.GetPreparedPayload()); Assert.IsFalse(normalRequest.IsPrepared); Assert.AreEqual(QueryStatus.Success, resultNormal.Status, resultNormal.GetErrorsAsString()); Assert.AreEqual(QueryStatus.Success, resultPrepareExecute.Status, resultPrepareExecute.GetErrorsAsString()); Assert.AreEqual(QueryStatus.Success, resultExecute.Status, resultExecute.GetErrorsAsString()); //additionally test the plan that was executed and the plan for normalRequest are the same var plan = client.Prepare(normalRequest).Rows.First(); Assert.IsNotNull(preparedRequest.GetPreparedPayload()); Assert.AreEqual(plan.Operator, preparedRequest.GetPreparedPayload().Operator); }
public void When_AdHoc_Is_True_Client_Doesnt_Cache() { var config = new ClientConfiguration(); var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); var request = QueryRequest.Create("SELECT * from `beer-sample` LIMIT 100"). BaseUri(new Uri(string.Format("http://{0}:8093/query", _server))). Pretty(false); var stopWatch = new Stopwatch(); stopWatch.Start(); var result = client.Query<dynamic>(request); stopWatch.Stop(); Console.WriteLine("Elasped time 1:{0}", stopWatch.ElapsedMilliseconds); stopWatch = new Stopwatch(); stopWatch.Restart(); result = client.Query<dynamic>(request); stopWatch.Stop(); Console.WriteLine("Elasped time 2:{0}", stopWatch.ElapsedMilliseconds); stopWatch = new Stopwatch(); stopWatch.Restart(); result = client.Query<dynamic>(request); stopWatch.Stop(); Console.WriteLine("Elasped time 3:{0}", stopWatch.ElapsedMilliseconds); Assert.AreEqual(QueryStatus.Success, result.Status); }