public QueryDefinition Replace(QueryDefinition definition) { string queryText = definition.QueryText; foreach (var macro in Macros) { queryText = queryText.Replace("@" + macro.Name, macro.GetValue(definition)); queryText = Regex.Replace(queryText, "@" + macro.Name, macro.GetValue(definition),RegexOptions.IgnoreCase); } return new QueryDefinition(definition.Name, queryText); }
private void ShowQueryResults(QueryDefinition queryDefinition) { object lockToken = new object(); IQueryDocument queryDocument = documentService.GetQuery(visualStudioAdapter.GetCurrent(), queryDefinition.Id.ToString(), lockToken); queryDocument.Load(); IResultsDocument results = documentService.GetLinkResults(queryDocument, lockToken); documentService.ShowResults(results); results.Release(lockToken); queryDocument.Release(lockToken); }
public IEnumerable<WorkItem> RunQuery(QueryDefinition queryDefinition) { QueryDefinition parsedQueryDefinition = macroParser.Replace(queryDefinition); var query = new Query(currentContext.CurrentWorkItemStore, parsedQueryDefinition.QueryText); if (query.IsLinkQuery) { var queryResults = query.RunLinkQuery(); return from l in queryResults.OfType<WorkItemLinkInfo>() select currentContext.CurrentWorkItemStore.GetWorkItem(l.TargetId); } else { var queryResults = query.RunQuery(); return queryResults.OfType<WorkItem>(); } }
/// <summary> /// Initialize all of the internal objects inside of the query definition /// </summary> /// <returns>A new instance of type QueryDefinition</returns> public static Profiles GetNewProfilesDefinition() { QueryDefinition qd = new QueryDefinition(); Profiles profiles = new Profiles(); Name name = new Name(); name.FirstName = new FirstName(); name.LastName = new LastName(); qd.Name = name; OutputOptions oo = new OutputOptions(); oo.SortType = OutputOptionsSortType.QueryRelevance; oo.StartRecord = "0"; Affiliation affiliation = new Affiliation(); AffiliationList affList = new AffiliationList(); //affiliations.AffiliationList = affList; affList.Affiliation = new List<Affiliation>(); affList.Affiliation.Add(affiliation); FacultyRankList ftList = new FacultyRankList(); ftList.FacultyRank = new List<string>(); KeywordString kws = new KeywordString(); Keywords kw = new Keywords(); kw.KeywordString = new KeywordString(); kw.KeywordString = kws; profiles.QueryDefinition = qd; profiles.QueryDefinition.AffiliationList = affList; profiles.QueryDefinition.Keywords = kw; profiles.QueryDefinition.Name = name; profiles.OutputOptions = oo; //its hard wired for 2 in this version. profiles.Version = 2; return profiles; }
public async Task <IEnumerable <YSetting> > GetSettingsAsync() { using CosmosClient client = new CosmosClient(accountEndpoint, accountKey, clientOptions); var container = client.GetContainer(databaseName, containerName); var results = new List <YSetting>(); var query = new QueryDefinition("SELECT VALUE c FROM c ORDER BY c.Name"); var resultSetIterator = container.GetItemQueryIterator <YSetting>( query, null, new QueryRequestOptions { PartitionKey = partitionKey }); while (resultSetIterator.HasMoreResults) { FeedResponse <YSetting> response = await resultSetIterator.ReadNextAsync().ConfigureAwait(false); results.AddRange(response); } return(results); }
public virtual async IAsyncEnumerable <T> GetAll([EnumeratorCancellation] CancellationToken cancellationToken) { var container = await GetContainer(cancellationToken); var sqlQuery = new QueryDefinition($"select * from {container.Id} c"); var iterator = container.GetItemQueryIterator <T>(sqlQuery); var ru = 0.0; while (iterator.HasMoreResults) { var results = await iterator.ReadNextAsync(cancellationToken); ru += results.RequestCharge; foreach (var result in results) { yield return(result); } } Activity.Current?.AddTag("RU", ru.ToString(CultureInfo.InvariantCulture)); }
private static GitHubQuery GenerateAreaQuery(QueryDefinition queryDefinition, QueryArea area) { string baseUrl; string areaFilter; if (area.Repositories.Count > 1) { baseUrl = "https://github.com/search?q="; areaFilter = string.Join(" ", area.Repositories.Select(r => $"repo:{r}")) + " "; } else { baseUrl = $"https://github.com/{area.Repositories[0]}/issues?q="; areaFilter = ""; } if (!string.IsNullOrEmpty(area.Label)) { areaFilter += $"label:{area.Label}"; } return(GitHubQuery.Create(queryDefinition.Name, baseUrl, $"{queryDefinition.QueryText} {areaFilter}")); }
public async Task <dynamic> GetById(string id) { await ConfigureDbAndContainerAsync(); var sqlQueryText = "SELECT * FROM c WHERE c.id = '" + id + "'"; QueryDefinition queryDefinition = new QueryDefinition(sqlQueryText); FeedIterator <Store> queryResultSetIterator = _container.GetItemQueryIterator <Store>(queryDefinition); List <Store> stores = new List <Store>(); while (queryResultSetIterator.HasMoreResults) { FeedResponse <Store> currentResultSet = await queryResultSetIterator.ReadNextAsync(); foreach (Store store in currentResultSet) { stores.Add(store); } } return(stores.FirstOrDefault()); }
/// <inheritdoc/> public async Task <List <ContentSummary> > GetContentSummariesForStatesAsync(IList <ContentState> states) { // All of the states should have the same slug. if (states.Distinct(x => x.Slug).Count() != 1) { throw new ArgumentException("All of the supplied states should be for the same content slug.", nameof(states)); } var queryBuilder = new StringBuilder("SELECT "); queryBuilder.Append(ContentSummaryProperties); queryBuilder.Append(" FROM c WHERE c.slug = @slug AND c.contentType = '"); queryBuilder.Append(Content.RegisteredContentType); queryBuilder.Append("' AND ARRAY_CONTAINS(["); IList <string> contentIds = states.Select(s => s.ContentId).Distinct().ToList(); Enumerable.Range(0, contentIds.Count).ForEach(i => { queryBuilder.Append("@id"); queryBuilder.Append(i); if (i < contentIds.Count - 1) { queryBuilder.Append(", "); } }); queryBuilder.Append("], c.id)"); QueryDefinition queryDefinition = new QueryDefinition(queryBuilder.ToString()) .WithParameter("@slug", states[0].Slug); contentIds.ForEachAtIndex((s, i) => queryDefinition = queryDefinition.WithParameter($"@id{i}", s)); ContentSummaries summaries = await this.GetContentSummariesAsync(states.Count, null, queryDefinition).ConfigureAwait(false); return(summaries.Summaries); }
///<summary> /// Recursively find the QueryDefinition based on the requested queryName. ///<para>Note that if multiple queries match the requested queryName /// only the first will be used</para> ///</summary> ///<param name=”queryName”>Name of Stored Query. Note if multiple exist /// the first found will be used</param> ///<param name=”currentNode”>Pointer to the current node in the recursive search</param> ///<returns>QueryDefinition</returns> private static QueryDefinition FindQueryItem(string queryName, QueryItem currentNode) { // Attempt to cast to a QueryDefinition QueryDefinition queryDefinition = currentNode as QueryDefinition; // Check if we’ve found a match if (queryDefinition != null && queryDefinition.Name == queryName) { return(queryDefinition); } // Attempt to cast the current node to a QueryFolder QueryFolder queryFolder = currentNode as QueryFolder; // All further checks are for child nodes so if this is not an // instance of QueryFolder then no further processing is required. if (queryFolder == null) { return(null); } // Loop through all the child query item foreach (QueryItem qi in queryFolder) { // Recursively call FindQueryItem QueryDefinition ret = FindQueryItem(queryName, qi); // If a match is found no further checks are required if (ret != null) { return(ret); } } return(null); }
public async Task <List <ScooterDocument> > FindScootersInRange(double longitude, double latitude, int radius) { var scooterContainer = _cosmosClient.GetContainer(Constants.ScootersDataBaseId, Constants.ScooterCollection); var query = new QueryDefinition("SELECT c as scooterDocument,ST_DISTANCE(c.location, {'type': 'Point', 'coordinates':[@longitude, @latitude]}) as distance " + "FROM c where c.documentType = @documentType and " + "ST_DISTANCE(c.location, {'type': 'Point', 'coordinates':[@longitude, @latitude]}) < @radius") .WithParameter("@documentType", Constants.ScooterDocumentType) .WithParameter("@longitude", longitude) .WithParameter("@latitude", latitude) .WithParameter("@radius", radius); var foundedScooters = new List <ScooterDocument>(); var queryRequestOptions = new QueryRequestOptions() { MaxItemCount = 50 }; FeedIterator <JObject> scooterResultSetIterator = scooterContainer. GetItemQueryIterator <JObject>(query, null, queryRequestOptions); while (scooterResultSetIterator.HasMoreResults) { var results = await scooterResultSetIterator.ReadNextAsync(); foreach (JObject result in results) { var scooter = result["store"].ToObject <ScooterDocument>(); //scooterDocument.Distance = result["distance"].ToObject<double>(); foundedScooters.Add(scooter); } } return(foundedScooters.ToList()); }
public async Task <List <GameRegistry> > GetGameRegistries() { var registries = new List <GameRegistry>(); try { using (var client = new CosmosClient(_cosmosSettings.EndpointUrl, _cosmosSettings.Key)) { var database = await client.CreateDatabaseIfNotExistsAsync(_cosmosSettings.DatabaseName); var container = database.Database.GetContainer(_cosmosSettings.GamesRegistryContainer); QueryDefinition queryDefinition = new QueryDefinition("select * from c"); using (FeedIterator <GameRegistry> feedIterator = container.GetItemQueryIterator <GameRegistry>( queryDefinition, null, new QueryRequestOptions())) { while (feedIterator.HasMoreResults) { foreach (var item in await feedIterator.ReadNextAsync()) { if ((item.Players.Where(p => p.Email == GetUser()).Count() > 0) || IsUserSystemAdmin()) { registries.Add(item); } } } } } } catch (Exception ex) { var msg = ex.Message; } return(registries); }
/// <summary> /// Add Query Definition under a specific Query Folder. /// </summary> /// <param name="targetHierarchy">The object that represents the whole of the target query tree</param> /// <param name="query">Query Definition - Contains the Query Details</param> /// <param name="QueryFolder">Parent Folder</param> void MigrateQuery(QueryHierarchy targetHierarchy, QueryDefinition query, QueryFolder parentFolder) { if (parentFolder.FirstOrDefault(q => q.Name == query.Name) != null) { this.totalQueriesSkipped++; Trace.WriteLine($"Skipping query '{query.Name}' as already exists"); } else { // Sort out any path issues in the quertText var fixedQueryText = query.QueryText.Replace($"'{me.Source.Name}", $"'{me.Target.Name}"); // the ' should only items at the start of areapath etc. if (config.PrefixProjectToNodes) { // we need to inject the team name as a folder in the structure too fixedQueryText = fixedQueryText.Replace($"{me.Target.Name}\\", $"{me.Target.Name}\\{me.Source.Name}\\"); } // you cannot just add an item from one store to another, we need to create a new object var queryCopy = new QueryDefinition(query.Name, fixedQueryText); this.totalQueriesAttempted++; Trace.WriteLine($"Migrating query '{query.Name}'"); parentFolder.Add(queryCopy); try { targetHierarchy.Save(); // moved the save here for better error message this.totalQueriesMigrated++; } catch (Exception ex) { this.totalQueryFailed++; Trace.WriteLine($"Error saving query '{query.Name}', probably due to invalid area or iteration paths"); Trace.WriteLine(ex.Message); targetHierarchy.Refresh(); // get the tree without the last edit } } }
public async Task <ProjectDocument> GetAsync(string nameOrId) { var container = await GetContainerAsync() .ConfigureAwait(false); ProjectDocument project = null; try { var response = await container .ReadItemAsync <ProjectDocument>(nameOrId, new PartitionKey(Options.TenantName)) .ConfigureAwait(false); project = response.Resource; } catch (CosmosException cosmosEx) when(cosmosEx.StatusCode == HttpStatusCode.NotFound) { var query = new QueryDefinition($"SELECT * FROM c WHERE c.name = '{nameOrId}'"); var queryIterator = container .GetItemQueryIterator <ProjectDocument>(query, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey(Options.TenantName) }); if (queryIterator.HasMoreResults) { var queryResults = await queryIterator .ReadNextAsync() .ConfigureAwait(false); project = queryResults.FirstOrDefault(); } } return(await PopulateUsersAsync(project) .ConfigureAwait(false)); }
public async Task <GetOrderByIdResponseModel> GetItemAsync(int orderId) { try { var container = _dbClient.GetContainer(_databaseName, _readContainerName); QueryDefinition query = new QueryDefinition( "select * from orders where orders.orderId = @orderId") .WithParameter("@orderId", orderId); using (FeedIterator <GetOrderByIdResponseModel> resultSet = container.GetItemQueryIterator <GetOrderByIdResponseModel>( query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(orderId), MaxItemCount = 1 })) { GetOrderByIdResponseModel order = null; while (resultSet.HasMoreResults) { FeedResponse <GetOrderByIdResponseModel> response = await resultSet.ReadNextAsync(); order = response.FirstOrDefault(); break; } return(order); } } catch (CosmosException ex) when(ex.StatusCode == System.Net.HttpStatusCode.NotFound) { return(null); } }
/// <summary> /// Get a list of Actors by search string /// /// The search is a "contains" search on actor name /// If q is empty, all actors are returned /// </summary> /// <param name="actorQueryParameters">search parameters</param> /// <returns>List of Actors or an empty list</returns> public async Task <IEnumerable <Actor> > GetActorsAsync(ActorQueryParameters actorQueryParameters) { if (actorQueryParameters == null) { throw new ArgumentNullException(nameof(actorQueryParameters)); } string sql = ActorSelect; int offset = actorQueryParameters.GetOffset(); int limit = actorQueryParameters.PageSize; string offsetLimit = string.Format(CultureInfo.InvariantCulture, ActorOffset, offset, limit); if (!string.IsNullOrEmpty(actorQueryParameters.Q)) { // convert to lower and escape embedded ' actorQueryParameters.Q = actorQueryParameters.Q.Trim().ToLowerInvariant().Replace("'", "''", System.StringComparison.OrdinalIgnoreCase); if (!string.IsNullOrEmpty(actorQueryParameters.Q)) { // get actors by a "like" search on name sql += string.Format(CultureInfo.InvariantCulture, $" and contains(m.textSearch, @q) "); } } sql += ActorOrderBy + offsetLimit; QueryDefinition queryDefinition = new QueryDefinition(sql); if (!string.IsNullOrEmpty(actorQueryParameters.Q)) { queryDefinition.WithParameter("@q", actorQueryParameters.Q); } return(await InternalCosmosDBSqlQuery <Actor>(queryDefinition).ConfigureAwait(false)); }
public async IAsyncEnumerable <ProviderDataDocument> GetByNameAsync(string providerId, string projectId, string name) { var container = await GetContainerAsync() .ConfigureAwait(false); var query = new QueryDefinition($"SELECT * FROM d WHERE p.providerId = '{providerId}' and p.scope = 'Project' and p.projectId = '{projectId}' and p.name = '{name}'"); var queryIterator = container .GetItemQueryIterator <ProviderDataDocument>(query, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey(Options.TenantName) }); while (queryIterator.HasMoreResults) { var queryResponse = await queryIterator .ReadNextAsync() .ConfigureAwait(false); foreach (var queryResult in queryResponse) { yield return(queryResult); } } }
private static void DefineQuery(QueryDefinition query, TfsQueryTreeItemViewModel parent, ICommand command) { TfsQueryTreeItemViewModel queryTreeItem = null; switch (query.QueryType) { case QueryType.List: queryTreeItem = new TfsFlatQueryItem(parent, query.Name, command, query.Id); break; case QueryType.OneHop: queryTreeItem = new TfsLinkedListQueryItem(parent, query.Name, command, query.Id); break; case QueryType.Tree: queryTreeItem = new TfsTreeQueryItem(parent, query.Name); break; default: return; } parent.Children.Add(queryTreeItem); }
public void Open(uint shortcutNr) { shortcutNr = shortcutNr & 0x0f; var queryPath = store.GetShortcut(shortcutNr); if (queryPath != null) { try { var workItemStore = visualStudioAdapter.GetCurrent().GetService <WorkItemStore>(); QueryDefinition queryDefinition = workItemStore.GetQueryDefinition(queryPath); if (queryDefinition != null) { ShowQueryResults(queryDefinition); } } catch (Exception) { } } }
public async Task <IReadOnlyList <T> > GetAllAsync() { try { var container = GetContainer(); var sqlQueryText = "SELECT * FROM c"; QueryDefinition queryDefinition = new QueryDefinition(sqlQueryText); AsyncPageable <T> queryResultSetIterator = container.GetItemQueryIterator <T>(queryDefinition); var iterator = queryResultSetIterator.GetAsyncEnumerator(); List <T> entities = new List <T>(); try { while (await iterator.MoveNextAsync()) { var entity = iterator.Current; entities.Add(entity); } } finally { if (iterator != null) { await iterator.DisposeAsync(); } } return(entities); } catch (CosmosException ex) { _logger.LogError($"Entities was not retrieved successfully - error details: {ex.Message}"); throw; } }
private async Task <Response> LoadDocuments(QueryDefinition query, Func <FeedResponse <EveneumDocument>, Task> callback, CancellationToken cancellationToken = default) { var iterator = this.Container.GetItemQueryIterator <EveneumDocument>(query, requestOptions: new QueryRequestOptions { MaxItemCount = this.QueryMaxItemCount }); double requestCharge = 0; var callbackProcessing = Task.CompletedTask; do { var response = await iterator.ReadNextAsync(cancellationToken); requestCharge += response.RequestCharge; await callbackProcessing; callbackProcessing = callback(response); }while (iterator.HasMoreResults); await callbackProcessing; return(new Response(requestCharge)); }
private async Task <List <Visiteur> > QueryItemsAsync(string query) { var sqlQueryText = (query == null) ? "SELECT * FROM c" : query; Debug.WriteLine($"query: {0}", sqlQueryText); QueryDefinition queryDefinition = new QueryDefinition(sqlQueryText); FeedIterator <Visiteur> queryResultSetIterator = _container.GetItemQueryIterator <Visiteur>(queryDefinition); List <Visiteur> visiteurs = new List <Visiteur>(); while (queryResultSetIterator.HasMoreResults) { FeedResponse <Visiteur> currentResultSet = await queryResultSetIterator.ReadNextAsync(); foreach (var visiteur in currentResultSet) { visiteurs.Add(visiteur); Debug.WriteLine("\tAjouter {0}\n", visiteur); } } return(visiteurs); }
// One of query or queryDefinition is to be passed in non-null private static async Task ValidateQueryResultsAsync( ContainerCore containerCore, string query = null, TestDoc expectedDoc = null, QueryDefinition queryDefinition = null) { QueryRequestOptions requestOptions = expectedDoc != null ? new QueryRequestOptions() { PartitionKey = new PartitionKey(expectedDoc.PK) } : null; FeedIterator <TestDoc> queryResponseIterator; if (query != null) { queryResponseIterator = containerCore.GetItemQueryIterator <TestDoc>(query, requestOptions: requestOptions); } else { queryResponseIterator = containerCore.GetItemQueryIterator <TestDoc>(queryDefinition, requestOptions: requestOptions); } FeedResponse <TestDoc> readDocs = await queryResponseIterator.ReadNextAsync(); Assert.AreEqual(null, readDocs.ContinuationToken); if (expectedDoc != null) { Assert.AreEqual(1, readDocs.Count); TestDoc readDoc = readDocs.Single(); Assert.AreEqual(expectedDoc, readDoc); } else { Assert.AreEqual(0, readDocs.Count); } }
private async Task<IEnumerable<T>> Results<T>(QueryDefinition queryDefinition, QueryRequestOptions queryRequestOptions, Func<List<T>, Task> batchAction, int itemsPerPage) { List<T> results = new List<T>(); using FeedIterator feedIterator = RepositoryContainer.GetItemQueryStreamIterator(queryDefinition, requestOptions: queryRequestOptions); while (feedIterator.HasMoreResults) { results.AddRange(await CosmosDbFeedIterator.GetDocuments<T>(feedIterator)); if (results.Count() >= itemsPerPage) { await batchAction(results); results.Clear(); } } if (results.Any()) { await batchAction(results); results.Clear(); } return results; }
public IEnumerable <IWorkItemSummary> GetWorkItemsBySavedQuery(string projectName, string queryFolderName, string queryName) { try { List <IWorkItemSummary> result = new List <IWorkItemSummary>(); QueryHierarchy queryRoot = store.Projects[projectName].QueryHierarchy; QueryFolder folder = (QueryFolder)queryRoot[queryFolderName]; QueryDefinition query1 = (QueryDefinition)folder[queryName]; WorkItemCollection queryResultsqueryResults = store.Query(query1.QueryText); foreach (WorkItem workItem in queryResultsqueryResults) { result.Add(new DefaultWorkItemSummary(workItem)); } return(result); } catch (Exception ex) { Exception exception = new Exception("Make sure you set TfsURL before calling this method, and that the query is valid. Check inner exception for more details.", ex); throw exception; } }
public override FeedIterator GetItemQueryStreamIterator( QueryDefinition queryDefinition, string continuationToken = null, QueryRequestOptions requestOptions = null) { QueryRequestOptions clonedRequestOptions; if (requestOptions != null) { clonedRequestOptions = (QueryRequestOptions)requestOptions.ShallowCopy(); } else { clonedRequestOptions = new QueryRequestOptions(); } return(new EncryptionFeedIterator( this.container.GetItemQueryStreamIterator( queryDefinition, continuationToken, clonedRequestOptions), this, clonedRequestOptions)); }
private async IAsyncEnumerable <ProviderDocument> ListWithQueryAsync(string queryString) { var container = await GetContainerAsync() .ConfigureAwait(false); var query = new QueryDefinition(queryString); var queryIterator = container .GetItemQueryIterator <ProviderDocument>(query, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey(Options.TenantName) }); while (queryIterator.HasMoreResults) { var queryResponse = await queryIterator .ReadNextAsync() .ConfigureAwait(false); foreach (var queryResult in queryResponse) { yield return(queryResult); } } }
public async Task <List <Highscore> > GetAll() { //Appconfig infos should be handled by a secret manager in production CosmosClient client = new CosmosClient(config.GetValue <string>("CosmosDb:Endpoint"), config.GetValue <string>("CosmosDb:PrimaryKey")); var container = client.GetDatabase(config.GetValue <string>("CosmosDb:Database")).GetContainer(config.GetValue <string>("CosmosDb:Container")); var sqlQueryText = "SELECT * FROM c ORDER BY c.Steps"; QueryDefinition queryDefinition = new QueryDefinition(sqlQueryText); FeedIterator <Highscore> queryResultSetIterator = container.GetItemQueryIterator <Highscore>(queryDefinition); var highscores = new List <Highscore>(); while (queryResultSetIterator.HasMoreResults) { FeedResponse <Highscore> currentResultSet = await queryResultSetIterator.ReadNextAsync(); foreach (Highscore highscore in currentResultSet) { highscores.Add(highscore); } } return(highscores); }
public async Task <IEnumerable <MatchDto> > GetLastGamesOfPlayer(string player, int limit) { if (_constr == null) { _logger.LogInformation($"Cosmos constr is null. No games returned for player {player}."); return(Enumerable.Empty <MatchDto>()); } var cResponse = await GetContainer(); var sqlQueryText = $"SELECT * FROM g WHERE g.playerName = '{player}' AND (NOT(IS_DEFINED(g.playFabMatchId)) OR IS_NULL(g.playFabMatchId)) ORDER BY g.whenUtc DESC"; var queryDefinition = new QueryDefinition(sqlQueryText); var rs = cResponse.Container.GetItemQueryIterator <MatchDto>(queryDefinition); var results = new List <MatchDto>(); while (rs.HasMoreResults && (limit <= 0 || results.Count < limit)) { var items = await rs.ReadNextAsync(); results.AddRange(items); } return(limit > 0 ? results.Take(limit).ToList() : results.ToList()); }
// return the first 10 rows from cities sorted by state in reverse private void menuItemCustomProcessor_Click(object sender, System.EventArgs e) { try { QueryFilter filter = new SqlExpressionFilter(null); // all rows QueryDefinition qd = new QueryDefinition(filter, "*"); string [] orderby = new string[1]; orderby[0] = "State Desc"; qd.OrderBy = orderby; SearchResultProcessor srp = new MySearchResultProcessor(10); // stop after 10 rows SearchInfo si = new SearchInfo(srp, qd); IResultSetFeatureCollection fc = _catalog.Search("usa", si); // set map view to show search results _map.SetView(fc.Envelope); // show results as selection SelectFeatureCollection(fc); } finally { Cursor.Current = Cursors.Default; } }
internal static QueryDefinition GetQueryDefinition( StreamId streamId, StreamVersion fromVersion, StreamReadFilter?filter) { var parameters = new Dictionary <string, object>(); var query = new StringBuilder(); query.Append("SELECT * FROM e WHERE e.pk = @partitionKey "); parameters["@partitionKey"] = streamId.Value; if (fromVersion != StreamVersion.Any && fromVersion != StreamVersion.NotEmpty) { query.Append("AND e.properties.version >= @fromVersion "); parameters["@fromVersion"] = fromVersion.Value; } if (filter?.IncludeEvents is not null && filter.IncludeEvents.Any()) { var index = 1; query.Append("AND ("); query.AppendJoin(" OR ", filter.IncludeEvents.Select(name => GetFilterExpression(name, $"@name{index++}", parameters))); query.Append(") "); } query.Append("ORDER BY e.properties.version"); var definition = new QueryDefinition(query.ToString()); foreach (var parameter in parameters) { definition.WithParameter(parameter.Key, parameter.Value); } return(definition); }
public async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "contacts/{contactType}")] HttpRequest req, string contactType) { IActionResult returnValue = null; try { QueryDefinition query = new QueryDefinition( $"SELECT * FROM {_contactContainer.Id} c WHERE c.ContactType = @ContactType") .WithParameter("@ContactType", contactType); FeedIterator <Contact> resultSet = _contactContainer.GetItemQueryIterator <Contact>( query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(contactType), MaxItemCount = 10 }); while (resultSet.HasMoreResults) { _logger.LogInformation($"Getting all contacts of {contactType} contact type"); FeedResponse <Contact> response = await resultSet.ReadNextAsync(); returnValue = new OkObjectResult(response); } } catch (Exception ex) { _logger.LogError($"Couldn't find all contacts of type {contactType}. Exception thrown: {ex.Message}"); returnValue = new StatusCodeResult(StatusCodes.Status500InternalServerError); } return(returnValue); }
private async Task TryCreateSampleTubes() { var sqlQueryText = $"SELECT * FROM c WHERE c.Type = 'SampleTube'"; //Console.WriteLine("Running query: {0}\n", sqlQueryText); QueryDefinition queryDefinition = new QueryDefinition(sqlQueryText); FeedIterator <SampleTube> queryResultSetIterator = this.container.GetItemQueryIterator <SampleTube>(queryDefinition); List <SampleTube> records = new List <SampleTube>(); if (!queryResultSetIterator.HasMoreResults) { var purple = new SampleTube("Purple", "Blood", 50.0); ItemResponse <SampleTube> responsePurp = await this.container.CreateItemAsync <SampleTube>(purple, new PartitionKey(purple.Type)); var red = new SampleTube("Red", "Urine", 75.5); ItemResponse <SampleTube> responseRed = await this.container.CreateItemAsync <SampleTube>(red, new PartitionKey(red.Type)); var grey = new SampleTube("Grey", "Blood", 55.0); ItemResponse <SampleTube> responseGrey = await this.container.CreateItemAsync <SampleTube>(grey, new PartitionKey(grey.Type)); var green = new SampleTube("Green", "Serum", 25.0); ItemResponse <SampleTube> responseGreen = await this.container.CreateItemAsync <SampleTube>(green, new PartitionKey(green.Type)); } }
public override FeedIterator GetItemQueryStreamIterator( QueryDefinition queryDefinition, string continuationToken = null, QueryRequestOptions requestOptions = null) { Action <DecryptionResult> DecryptionResultHandler; if (requestOptions is EncryptionQueryRequestOptions encryptionQueryRequestOptions) { DecryptionResultHandler = encryptionQueryRequestOptions.DecryptionResultHandler; } else { DecryptionResultHandler = null; } return(new EncryptionFeedIterator( this.container.GetItemQueryStreamIterator( queryDefinition, continuationToken, requestOptions), this.encryptor, DecryptionResultHandler)); }
public void MacroParserWithNoMacroDefinitionShouldNotReplaceAnyToken() { string expectedQuery = "SELECT System.ID, System.Title from workitems WHERE Project = @Project"; var queryDefinition = new QueryDefinition("test", expectedQuery); var parser = new MacroParser(Enumerable.Empty<IMacro>()); QueryDefinition parsedDefinition = parser.Replace(queryDefinition); Assert.AreEqual(expectedQuery, parsedDefinition.QueryText); }
// shows how to combine filters using logical And private void menuItemLogicalFilter_Click(object sender, System.EventArgs e) { try { Feature fChicago = _catalog.SearchForFeature("uscty_1k", MapInfo.Data.SearchInfoFactory.SearchWhere("City='Chicago'")); // build up a search info by hand (not using the factory) Distance d1 = new Distance(35, DistanceUnit.Mile); Distance d2 = new Distance(125, DistanceUnit.Mile); QueryFilter filterA = new MyCustomFilter(fChicago.Geometry, d1, d2); // build up a search info by hand (not using the factory) QueryFilter filterB = new SqlExpressionFilter("State='IL'"); QueryFilter filter = new LogicalFilter(LogicalOperation.And, filterA, filterB); QueryDefinition qd = new QueryDefinition(filter, "*"); SearchInfo si = new SearchInfo(null, qd); IResultSetFeatureCollection fc = _catalog.Search("uscty_1k", si); // set map view to show search results _map.SetView(fc.Envelope); // make a search geometry to show what we are doing FeatureGeometry buffer1 = fChicago.Geometry.Buffer(d1.Value, d1.Unit, 20, DistanceType.Spherical); FeatureGeometry buffer2 = fChicago.Geometry.Buffer(d2.Value, d2.Unit, 20, DistanceType.Spherical); ShowSearchGeometry(buffer1); ShowSearchGeometry(buffer2, false); Feature fIL = _catalog.SearchForFeature("usa", MapInfo.Data.SearchInfoFactory.SearchWhere("State='IL'")); ShowSearchGeometry(fIL.Geometry, false); // show results as selection SelectFeatureCollection(fc); } finally { Cursor.Current = Cursors.Default; } }
private void menuItemSqlExpressionFilter_Click(object sender, System.EventArgs e) { try { // build up a search info by hand (not using the factory) QueryFilter filter = new SqlExpressionFilter("Buses_91 * 3 < Trucks_91"); QueryDefinition qd = new QueryDefinition(filter, "*"); SearchInfo si = new SearchInfo(null, qd); IResultSetFeatureCollection fc = _catalog.Search("mexico", si); // set map view to show search results _map.SetView(fc.Envelope); // show results as selection SelectFeatureCollection(fc); } finally { Cursor.Current = Cursors.Default; } }
public void UpdateItems(object state) { string externalWiIdsText = string.Empty; WorkItemsToLink.Clear(); Dispatcher.Invoke((Action)delegate() { externalWiIdsText = wiIDsTextBox.Text; foundItemsListView.Items.Clear(); }); var itemsToLink = externalWiIdsText.Split(new[] {',',';',' ',}); List<int> updatedIdsList = new List<int>(); foreach (var strId in itemsToLink) { if (!String.IsNullOrWhiteSpace(strId)) { int id; if (int.TryParse(strId, out id)) { updatedIdsList.Add(id); } else { Dispatcher.Invoke((Action)delegate() { InsertButton.IsEnabled = false; foundItemsListView.Items.Add(new ListViewItem() { Content = String.Format(ResourceHelper.GetResourceString("MSG_INPUT_VALUE_INCORRECT"), strId), Background = new SolidColorBrush(Colors.LightCoral) }); }); } } } string wiNumbers = string.Empty; int wInotInCurrentProject = 0; foreach (var itemId in updatedIdsList) { wItem = Manager.GetWorkItem(itemId); string m = string.Empty; wiNumbers += itemId + ", "; if (wItem != null) { Dispatcher.Invoke((Action)delegate() { if (wItem != null && wItem.Project.Name != Project) { var textBlock = new TextBlock(); textBlock.Text = String.Format("• {0} {1} ({2}): {3} {4} ", wItem.Type.Name, wItem.Id, wItem.State, wItem.Title, ResourceHelper.GetResourceString("NOT_IN_CURRENT_DOCUMENT")); foundItemsListView.Items.Add(new ListViewItem() { Content = textBlock, Background = new SolidColorBrush(Colors.LightCoral) }); workItemNotCurrentProject.Visibility = System.Windows.Visibility.Visible; wInotInCurrentProject++; } else { //var rowN = new ListViewItem() { Content = String.Format("• {0} {1} ({2}): {3}", wItem.Type.Name, wItem.Id, wItem.State, wItem.Title) }; //foundItemsListView.Items.Add(rowN); var textBlock = new TextBlock(); textBlock.Text = String.Format("• {0} {1} ({2}): {3}", wItem.Type.Name, wItem.Id, wItem.State, wItem.Title); foundItemsListView.Items.Add(new ListViewItem() { Content = textBlock }); //foundItemsListView.Items.Add(String.Format("• {0} {1} ({2}): {3}", wItem.Type.Name, wItem.Id, wItem.State, wItem.Title)); } WorkItemsToLink.Add(wItem); }); } else { Dispatcher.Invoke((Action)delegate() { InsertButton.IsEnabled = false; foundItemsListView.Items.Add(new ListViewItem() { Content = String.Format(ResourceHelper.GetResourceString("MSG_ITEM_IS_NOT_FOUND"), itemId), Background = new SolidColorBrush(Colors.LightCoral) }); }); } } if (wInotInCurrentProject == 0) Dispatcher.Invoke((Action)delegate() { workItemNotCurrentProject.Visibility = System.Windows.Visibility.Hidden; }); if (updatedIdsList.Count == 0) { Dispatcher.Invoke((Action)delegate() { InsertButton.IsEnabled = false; tbxHeader.Text = string.Empty; PropertiesList.Items.Clear(); PropertiesListBody.Items.Clear(); }); } var n = foundItemsListView.Items; if (updatedIdsList.Count != 0) { wiNumbers = wiNumbers.Substring(0, wiNumbers.Length - 2); string queryText = string.Format("select [System.Id], [System.WorkItemType], [System.Title], [System.State], [System.AreaPath], [System.IterationPath] {0} from WorkItems where [System.TeamProject] = '{1}' and [System.Id] in ({2}) order by [System.ChangedDate] desc", Manager.tfsVersion == TfsVersion.Tfs2011 ? ", [System.Tags]" : string.Empty, Project, wiNumbers); queryDef = new QueryDefinition("Work Items list", queryText); if (wItem != null) { PopulateQueryFieldsFromQuerydef(queryDef); } } }
public override string GetValue(QueryDefinition definition) { return String.Format("\"{0}\"", this.tfsContext.CurrentUser); }
private void SetQueryItem(QueryFolder queryFolder, QueryFolder parentFolder, string sourceProjectName) { QueryItem newItem = null; foreach (QueryItem subQuery in queryFolder) { try { if (subQuery.GetType() == typeof(QueryFolder)) { newItem = new QueryFolder(subQuery.Name); if (!parentFolder.Contains(subQuery.Name)) { parentFolder.Add(newItem); store.Projects[projectName].QueryHierarchy.Save(); SetQueryItem((QueryFolder)subQuery, (QueryFolder)newItem, sourceProjectName); } else { logger.WarnFormat("Query Folder {0} already exists", subQuery); } } else { QueryDefinition oldDef = (QueryDefinition)subQuery; string queryText = oldDef.QueryText.Replace(sourceProjectName, projectName).Replace("User Story", "Product Backlog Item").Replace("Issue", "Impediment"); newItem = new QueryDefinition(subQuery.Name, queryText); if (!parentFolder.Contains(subQuery.Name)) { parentFolder.Add(newItem); store.Projects[projectName].QueryHierarchy.Save(); } else { logger.WarnFormat("Query Definition {0} already exists", subQuery); } } } catch (Exception ex) { if (newItem != null) newItem.Delete(); logger.ErrorFormat("Error creating Query: {0} : {1}", subQuery, ex.Message); continue; } } }
public override string GetValue(QueryDefinition definition) { return String.Format("{0}{1}{0}", SimpleQuote, definition.Project.Name); }
public override string GetValue(QueryDefinition definition) { return null; }
public void MacroParserWithMatchingMacroShouldReplaceToken() { //Arrange string query = "SELECT System.ID, System.Title from workitems WHERE Project = @Project"; var queryDefinition = new QueryDefinition("test", query); string expectedQuery = "SELECT System.ID, System.Title from workitems WHERE Project = \"TestProject\""; //Act QueryDefinition parsedQuery = parserWithMacros.Replace(queryDefinition); //Assert A.CallTo(() => projectMacroMock.GetValue(queryDefinition)).MustHaveHappened(); A.CallTo(() => projectMacroMock.Name).MustHaveHappened(); Assert.AreEqual(expectedQuery, parsedQuery.QueryText); }
public WorkItemQueryDefinitionModel(IWorkItemQueryCommandModel workItemQueryCommandModel, Project project, int depth, QueryDefinition queryDefinition) : base(workItemQueryCommandModel, depth) { QueryDefinition = queryDefinition; Project = project; }
public TfsQueryCache(QueryDefinition query) { this.Query = query; this.LastRefreshed = DateTime.MinValue; this.PayloadCache = string.Empty; }
private void DefineQuery(QueryDefinition query, TreeViewItem QueryFolder) { var item = new TreeViewItem {IsExpanded = true}; QueryTypes type; switch (query.QueryType) { case QueryType.List: type = QueryTypes.FView; break; case QueryType.OneHop: type = QueryTypes.DView; break; case QueryType.Tree: type = QueryTypes.HView; break; default: type = QueryTypes.None; break; } item.Header = CreateTreeItem(query.Name, type); item.Tag = query; QueryFolder.Items.Add(item); }
public static bool ExecuteQueryLinkTypes(QueryDefinition qdef, string ProjectName, out int[] qdata) { Hashtable context = new Hashtable(); StringBuilder strb = new StringBuilder(); List<int> lqdata = new List<int>(); context.Add("project", ProjectName); //@me, @today are filled automatically var query = new Query(Utilities.wistore, qdef.QueryText, context); if (query.IsLinkQuery) { foreach (var wilnk in query.RunLinkQuery()) { lqdata.Add(wilnk.TargetId); lqdata.Add(wilnk.SourceId); Utilities.OutputCommandString(string.Format("ParentID={0}, WorkItemID={1}", wilnk.SourceId, wilnk.TargetId)); } lqdata = lqdata.Distinct().ToList(); } else { foreach (WorkItem wi in query.RunQuery()) { lqdata.Add(wi.Id); Utilities.OutputCommandString(string.Format("WorkItemID={0}, Title={1}", wi.Id, wi.Title)); } } qdata = lqdata.ToArray(); return false; }
/// <summary> /// Add Query Definition under a specific Query Folder. /// </summary> /// <param name="query">Query Definition - Contains the Query Details</param> /// <param name="queryFolder">Parent Folder</param> void DefineQuery(QueryDefinition queryDef, TreeViewItem queryFolder) { var item = new TreeViewItem(); QueryTypes type; switch (queryDef.QueryType) { case QueryType.List: type = QueryTypes.FView; break; case QueryType.OneHop: type = QueryTypes.DView; break; case QueryType.Tree: type = QueryTypes.HView; break; default: type = QueryTypes.None; break; } item.Header = CreateTreeItem(queryDef.Name + " [...]", type); item.Tag = queryDef.Id; item.Selected += ItemOnSelected; item.Unselected += ItemUnselected; queryFolder.Items.Add(item); }
/// <summary> /// Executes the query. /// </summary> /// <param name="queryDef">The query definition.</param> /// <returns></returns> public IEnumerable<TfsItem> ExecuteQuery(QueryDefinition queryDef) { IList<TfsItem> tasks = new List<TfsItem>(); IEnumerable<WorkItem> workItems = null; Query query = new Query(TeamProject.Store, queryDef.QueryText,GetParamsDictionary()); if (queryDef.QueryType == QueryType.List) { workItems = query.RunQuery().Cast<WorkItem>(); } else { workItems = FlatLinkQuery(query); } // transform the workItems into TfsItem foreach (WorkItem item in workItems) { tasks.Add(item.ToTfsTask()); } return tasks; }
private void menuItemSetColumns_Click(object sender, System.EventArgs e) { try { // build up a search info by hand (not using the factory) QueryFilter filter = new SqlExpressionFilter("POP_90 < 1000000"); QueryDefinition qd = new QueryDefinition(filter, "MI_Key"); // to Add Columns qd.AppendColumns("State", "MI_Geometry"); // to set all new set of columns // not using MI_Geometry here string[] cols = new string[] {"MI_Key", "MI_Style", "State_Name", "POP_90", "Households_90"}; qd.Columns = cols; // Note: if you are doing a multi table search, the columns must apply to each table // alternatively, you can derive a new class from QueryDefinition and // override the GetColumns() method to return different columns for each table being searched SearchInfo si = new SearchInfo(null, qd); IResultSetFeatureCollection fc = _catalog.Search("mexico", si); // set map view to show search results _map.SetView(_map.Layers["mexico"] as FeatureLayer); // show results as selection SelectFeatureCollection(fc); } finally { Cursor.Current = Cursors.Default; } }
public abstract string GetValue(QueryDefinition definition);
public bool TryGetQueryDefinitionWorkItemCollection(out WorkItemCollection workItemCollection, TfsTeamProjectCollection tfsTeamProjectCollection, QueryDefinition queryDefinition, string projectName) { try { workItemCollection = _teamPilgrimTfsService.GetQueryDefinitionWorkItemCollection(tfsTeamProjectCollection, queryDefinition, projectName); return true; } catch (Exception ex) { this.Logger().DebugException(ex); LastException = ex; } workItemCollection = null; return false; }
public WorkItemCollection GetFlatQueryDefinitionWorkItemCollection(TfsTeamProjectCollection tfsTeamProjectCollection, QueryDefinition queryDefinition, string projectName) { this.Logger().Trace("GetQueryDefinitionWorkItemCollection QueryType: {0}", queryDefinition.QueryType); if (queryDefinition.QueryType != QueryType.List) throw new ArgumentException("Flat Queries only"); var context = new Dictionary<string, string> { { "project", projectName } }; var workItemStore = GetWorkItemStore(tfsTeamProjectCollection); return new Query(workItemStore, queryDefinition.QueryText, context).RunQuery(); }
// return the first 10 rows from cities sorted by state in reverse private void menuItemCustomProcessor_Click(object sender, System.EventArgs e) { try { QueryFilter filter = new SqlExpressionFilter(null); // all rows QueryDefinition qd = new QueryDefinition(filter, "*"); string [] orderby = new string[1]; orderby[0] = "State Desc"; qd.OrderBy = orderby; SearchResultProcessor srp = new MySearchResultProcessor(10); // stop after 10 rows SearchInfo si = new SearchInfo(srp, qd); IResultSetFeatureCollection fc = _catalog.Search("usa", si); // set map view to show search results _map.SetView(fc.Envelope); // show results as selection SelectFeatureCollection(fc); } finally { Cursor.Current = Cursors.Default; } }
private void DefineQuery(QueryDefinition query, TreeNode queryFolder) { var item = new TreeNode { Text = query.Name, Tag = query }; queryFolder.Nodes.Add(item); }
// uses intersect filter to get states that intersect florida private void menuItemIntersectFeature_Click(object sender, System.EventArgs e) { try { Feature fFlorida = _catalog.SearchForFeature("usa", MapInfo.Data.SearchInfoFactory.SearchWhere("State='FL'")); // build up a search info by hand (not using the factory) QueryFilter filter = new IntersectFilter(fFlorida.Geometry, IntersectType.Bounds); QueryDefinition qd = new QueryDefinition(filter, "*"); SearchInfo si = new SearchInfo(null, qd); IResultSetFeatureCollection fc = _catalog.Search("usa", si); // set map view to show search results _map.SetView(fc.Envelope); ShowSearchGeometry(fFlorida.Geometry); // show results as selection SelectFeatureCollection(fc); } finally { Cursor.Current = Cursors.Default; } }
/// <summary> /// Adds a query in "My Queries" /// </summary> /// <param name="queryTitle"></param> /// <param name="queryCommand"></param> /// <param name="parentFolder"></param> /// <returns></returns> public QueryDefinition AddNewQuery(string queryTitle, string queryCommand, QueryFolder parentFolder) { QueryDefinition query = new QueryDefinition(queryTitle, queryCommand, parentFolder); MyProject.QueryHierarchy.Save(); return query; }
public static void ViewQuery(QueryDefinition queryDefinition) { ViewQueryMethod.Value.Invoke(null, new object[] { queryDefinition }); }
public void PopulateQueryFieldsFromQuerydef(QueryDefinition queryDef) { Query query = new Query(Manager.ItemsStore, queryDef.QueryText); var allFields = Manager.GetAllAvailableWorkItemFieldsForProject(Project); List<string> displayFieldList = query.DisplayFieldList.Cast<FieldDefinition>().Select(f => f.Name).ToList(); if (displayFieldList != null) { Dispatcher.BeginInvoke((Action)delegate() { tbxHeader.Clear(); PropertiesList.Items.Clear(); PropertiesListBody.Items.Clear(); PopulateQueryFields(allFields, displayFieldList); InsertButton.IsEnabled = true; }); } }
/// <summary> /// Copies all queries from specified folder, adds them to specified folder without /// modifying the former folder's queries /// </summary> /// <param name="oldFolder"></param> /// <param name="newFolder"></param> public void CopyPreviousQueryFolderContent(QueryFolder oldFolder, QueryFolder newFolder) { // List of all the old folder's queries List<QueryDefinition> oldQueryList = new List<QueryDefinition>(); oldQueryList.AddRange(GetAllTeamQueries(oldFolder)); // List for the new folder's queries, copy of the previous list List<QueryDefinition> newQueryList = new List<QueryDefinition>(); newQueryList.AddRange(oldQueryList); // iterates through each query in copied list, adds newly constructed queries in new folder foreach (var queryItem in newQueryList) { QueryDefinition queryDefinition = new QueryDefinition(queryItem.Name, queryItem.QueryText); newFolder.Add(queryDefinition); } newFolder.Project.QueryHierarchy.Save(); }