Tfs WIQL to object converter - parsing

this is my first question :)
I was wondering, if there is something like a WIQL (TFS Work Item Query Language) parser.
I'm dealing with TFS Queries and i have to programatically change some fields of them. Searching for a parses or something had no results to me. Can you help me?
NOTE: I have to change the queries themselves. Not any workitems.
Thank you Guys.

You can use REST api or the .net api:
REST API:
POST https://{instance}/defaultcollection/[{project}/]_apis/wit/wiql?api-version={version}
Content-type: Application/json
{
"query": string
}
.net API:
// credentials if required
System.Net.ICredentials credentials = new System.Net.NetworkCredential("User", "Password", "Domain");
// create the collection
Microsoft.TeamFoundation.Client.TfsTeamProjectCollection teamProjectCollection =
new Microsoft.TeamFoundation.Client.TfsTeamProjectCollection(new Uri(#"http://tfsServer:8080/tfs/collection"), credentials);
// check we are authenticated
teamProjectCollection.EnsureAuthenticated();
// create the work item store
Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore Store =
(Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore)
teamProjectCollection.GetService(typeof(Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore));
// create a query to select tasks
string query = "SELECT * FROM WorkItems WHERE [System.WorkItemType] = 'Task' AND [System.IterationPath] = '#IterationPath' ORDER BY [System.WorkItemType], [System.Id]";
// replace the iteration
query = query.Replace("#IterationPath", "IterationPath");
// query the store!
Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemCollection WIC = Store.Query(query);

Related

Graph API .net SDK - Filter Me.MemberOf based on displayName of groups

I am trying to filter out the groups of a user he is a member of based on some words that the group name may contain.
I am using this code -
var groups = _graphServiceClient.Me.MemberOf.Request().Filter($"displayName -eq 'abhi'").GetAsync().Result;
but I am getting the error that filter request is invalid.
Any help with this is always appreciated, thanks.
Based on aad advanced queries here your request is supported when the request headers contains ConsistencyLevel = eventual and count = true
To get it to work here is the sample code:
List<Option> options = new List<Option>();
options.Add(new HeaderOption("ConsistencyLevel", "eventual"));
options.Add(new QueryOption("$filter", $"displayName eq 'abhi'"));
options.Add(new QueryOption("$count", "true"));
var groups = await graphServiceClient.Me
.MemberOf
.Request(options)
.GetAsync();

Odata Query Batch Request - Filter not working

We are using SAP SDK 3.25.0 and calling a batch request Read query passing some filters. I am getting the response of all the records and it can be seen that the filter is not working properly.
I have referred this blog here but I am getting the same issue of decode URL issue YY1_QuantityContractTracki?$filter=((CustomerName eq %27Ford%27) and (SalesSchedulingAgreement eq %270030000141%27)) and (PurchaseOrderByCustomer eq %27TEST%27)&$select=SalesSchedulingAgreement,PurchaseOrderByCustomer,Customer,CustomerName,SalesSchedulingAgreementItem,Material,MaterialByCustomer&$format=json
Below is the query program which I am using.
Am I missing something here. Please let us know
Thanks,
Arun Pai
final BatchRequestBuilder builder = BatchRequestBuilder.withService("/sap/opu/odata/sap/YY1_QUANTITYCONTRACTTRACKI_CDS");
for (Contract contract : contracts) {
FilterExpression mainFilter = new FilterExpression("CustomerName", "eq", ODataType.of(contract.getCustomerName()))
.and(new FilterExpression("SalesSchedulingAgreement", "eq", ODataType.of(contract.getSchAgrmntNo())))
.and(new FilterExpression("PurchaseOrderByCustomer", "eq", ODataType.of(contract.getCustRefNo())));
final ODataQuery oDataQuery = ODataQueryBuilder
.withEntity(sapConfig.getEssentialsContractServiceUrl(),
sapConfig.getEssentialsContractListEntity())
.select("SalesSchedulingAgreement", "PurchaseOrderByCustomer", "Customer", "CustomerName",
"SalesSchedulingAgreementItem", "Material", "MaterialByCustomer")
.filter(mainFilter)
.build();
builder.addQueryRequest(oDataQuery);
}
final BatchRequest batchRequest = builder.build();
final BatchResult batchResult = batchRequest.execute(httpClient);
Update
I have changed the version to 3.35.0 today with connectivity version 1.40.11 but it did'nt work either.
Below is the log request which gets printed in the console
2021-01-15 19:15:03.831 INFO 42640 --- [io-8084-exec-10] c.s.c.s.o.c.impl.BatchRequestImpl : --batch_123
Content-Type: application/http
Content-Transfer-Encoding: binary
GET YY1_QuantityContractTracki?%24filter%3D%28%28CustomerName+eq+%2527Ford27%29+and+%28SalesSchedulingAgreement+eq+%25270030000141%2527%29%29+and+%28PurchaseOrderByCustomer+eq+%2527TEST%2527%29%26%24select%3DSalesSchedulingAgreement%2CPurchaseOrderByCustomer%2CCustomer%2CCustomerName%2CSalesSchedulingAgreementItem%2CMaterial%2CMaterialByCustomer%26%24format%3Djson HTTP/1.1
Accept: application/json;odata=verbose
--batch_123--
For your information: with the release of SAP Cloud SDK 3.41.0 we enabled support for read operations in OData batch requests on the type-safe API. Please find the chapter in the respective documentation. You would no longer need to use the Generic OData Client of SAP Cloud SDK as suggested in the other response. Example:
BusinessPartnerService service;
BusinessPartnerAddress addressToCreate1;
BusinessPartnerAddress addressToCreate2;
BusinessPartnerFluentHelper requestTenEntities = service.getAllBusinessPartner().top(10);
BusinessPartnerByKeyFluentHelper requestSingleEntity = service.getBusinessPartnerByKey("bupa9000");
BatchResponse result =
service
.batch()
.addReadOperations(requestTenEntities)
.addReadOperations(requestSingleEntity)
.executeRequest(destination);
List<BusinessPartner> entities = result.getReadResult(requestTenEntities);
BusinessPartner entity = result.getReadResult(requestSingleEntity);
Update (22.03.2021)
With the release of SAP Cloud SDK 3.41.0 this week we'll enable support for read operations in OData batch requests on the type-safe API. Please find the chapter in the respective documentation.
Example:
BusinessPartnerService service;
BusinessPartnerAddress addressToCreate1;
BusinessPartnerAddress addressToCreate2;
BusinessPartnerFluentHelper requestTenEntities = service.getAllBusinessPartner().top(10);
BusinessPartnerByKeyFluentHelper requestSingleEntity = service.getBusinessPartnerByKey("bupa9000");
BatchResponse result =
service
.batch()
.addReadOperations(requestTenEntities)
.addReadOperations(requestSingleEntity)
.executeRequest(destination);
List<BusinessPartner> entities = result.getReadResult(requestTenEntities);
BusinessPartner entity = result.getReadResult(requestSingleEntity);
Original response:
I'm from the SAP Cloud SDK team. Generally we recommend our users to generate classes for their OData service interactions. This way you can easily make sure that requests are according to specification, while type safety is taken care of.
Unfortunately I cannot help you with the API of BatchRequestBuilder, BatchRequest or BatchResult because they are not directly a part of SAP Cloud SDK and not maintained by us. Instead we suggest our own request builders.
If the generation of classes, as linked above, is not an option for you, then I would suggest to try our expert API featuring the Generic OData Client of SAP Cloud SDK. This is the code that we would also use internally for our generated request builders:
String servicePath = "/sap/opu/odata/sap/YY1_QUANTITYCONTRACTTRACKI_CDS";
ODataRequestBatch requestBatch = new ODataRequestBatch(servicePath, ODataProtocol.V2);
Map<Contract, ODataRequestRead> batchedRequests = new HashMap<>();
// iterate over contracts, construct OData query objects and add them to the OData batch request builder
for (Contract contract : contracts) {
String entityName = sapConfig.getEssentialsContractListEntity();
String serviceUrl = sapConfig.getEssentialsContractServiceUrl();
StructuredQuery structuredQuery = StructuredQuery.onEntity(entityName, ODataProtocol.V2);
structuredQuery.select("SalesSchedulingAgreement", "PurchaseOrderByCustomer", "Customer", "CustomerName", "SalesSchedulingAgreementItem", "Material", "MaterialByCustomer");
structuredQuery.filter(FieldReference.of("SalesSchedulingAgreement").equalTo(contract.getSchAgrmntNo()));
structuredQuery.filter(FieldReference.of("PurchaseOrderByCustomer").equalTo(contract.getCustRefNo()));
String encodedQuery = structuredQuery.getEncodedQueryString();
ODataRequestRead requestRead = new ODataRequestRead(serviceUrl, entityName, encodedQuery, ODataProtocol.V2);
batchedRequests.put(contract, requestRead);
requestBatch.addRead(requestRead);
}
// execute the OData batch request
ODataRequestResultMultipartGeneric batchResult = requestBatch.execute(httpClient);
// extract information from batch response, by referring to the individual OData request references
for( Map.Entry<Contract, ODataRequestRead> requestMapping : batchedRequests.entrySet() ) {
ODataRequestResultGeneric queryResult = batchResult.getResult(requestMapping.getValue());
List<Map<String, Object>> itemsForQuery = queryResult.asListOfMaps();
}
Kind regards
Alexander

VSTS/TFS Extension Development - URL Limit for GET Request for getWorkItems() Method

We are developing a VSTS/TFS Extension. We are also querying Work Items data using Rest Client provided by VSTS/TFS. We are using below method to Get Details of all the work items -
https://learn.microsoft.com/en-us/azure/devops/extend/reference/client/api/tfs/workitemtracking/restclient/workitemtrackinghttpclient2_1?view=vsts#method_getWorkItems
The method getWorkItems generates a GET request. All the Work Item IDs are passed as query parameters which exceed the URL Limit of 2048 characters. Thus to tackle that, for now, we are splicing the work items Ids in smaller chunks. But then it increases the Rest API calls.
Is there any other method through which I can Get details of all work Items using any method in VSTS/TFS defined list?
Using queryById() or queryByWiql() function in TFS/WorkItemTracking/RestClient to retrieve work items through Query.
For example:
witClient.queryById('7633dab2-89e4-4da9-b03d-a16728ab71c5', projectId)
.then(function (workitemResult) {....})
query = {
query: "SELECT [System.Id] "
+ "FROM WorkItem WHERE [System.WorkItemType] = 'Feature' "
+ "AND [System.State] NOT IN ('Closed','Completed','Removed','Done') "
+ "AND [System.TeamProject] = #project"
};
witClient.queryByWiql(query, projectId, allteams[0].id).then(function (result) {
console.log(result);
});
Here's the answer
let client = VssService.getCollectionClient(WitClient.WorkItemTrackingHttpClient5);
client.getWorkItemsBatch(<WitContracts.WorkItemBatchGetRequest>{ ids: [1, 2, 3] })

Audit.net with azure table storage

How can i store audit data in azure table storage,audit.net provides (https://github.com/thepirat000/Audit.NET#data-providers-included)
sqldataprovider only can you please help me.
Thanks
Now you can use the Azure Table data provider to store your audit events on azure tables. It is included from version 12.1.9 on the Audit.NET.AzureStorage package.
You can configure the columns dynamically via an anonymous object or dictionary, or implementing your own TableEntity class.
For example:
Audit.Core.Configuration.Setup()
.UseAzureTableStorage(_ => _
.ConnectionString("your cnn string")
.TableName("Events")
.EntityBuilder(e => e
.PartitionKey($"Events{ev.StartDate:yyyyMM}")
.Columns(c => c.FromObject(ev => new
{
Date = ev.StartDate,
User = ev.Environment.UserName,
...
}))));
Take a look at the README file here.
For further problems, note you can also open an issue instead of asking on SO. or ask on the Audit.NET Gitter chat
Audit.Core.Configuration.DataProvider = new AzureTableDataprovider()
{
ConnectionString = ConfigurationManager.ConnectionStrings["AuditDbConnection"].ToString(),
Schema = "dbo",
TableName = "tblbateventsauditing",
IdColumnName = "EventId",
JsonColumnName = "Data"
};

How to fetch the list of Tags in TFS 2015 Update 3

Is there a way to fetch the list of tags created for a team project, basically we need information such as creation date, created by user etc.
Can we fetch these information using TFS RestApi? If so it would be helpful if code snippets are provided.
There isn't the information of created by user, you can check it in dbo.tbl_TagDefinition table of collection database.
To fetch the list of Tags, you can refer to Giulio’s answer, for example:
[collection URL]/_apis/tagging/scopes/[Team Project ID]/tags?api-version=1.0
To get Team Project ID, you can call this REST API:
[Collection URL]/_apis/projects?api-version=1.0
Simple code for C#:
String MyURI = "[collection URL]/_apis/tagging/scopes/f593de42-d419-4e07-afc7-1f334077c212/tags?api-version=1.0";
WebRequest WReq = WebRequest.Create(MyURI);
WReq.Credentials =
new NetworkCredential("[user name]", "[password]", "[domain"");
WebResponse response = WReq.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
There is a REST API to manage Tags, but there is not auditing information as per your request.
If you want to learn how to call a REST API there is plenty of sources, starting from the Get started page.

Resources