Program terminates when calling WorkItemTrackingHttpClient.QueryByWiqlAsyc() - azure

I am working on a program that gets a list of workitems in the committed state from Azure DevOps for a specific area path and iteration path. My code is based on an example found at the following link: https://learn.microsoft.com/en-us/azure/devops/integrate/quickstarts/work-item-quickstart?view=azure-devops
The issue I am running into is when QueryByWiqlAsync() is called, the program terminates and there are no errors for why it terminated. Below is the code in question. I tried calling QueryByWiqlAsync() with and without the ConfigureAwait(false) and that did not seem to make a difference. Any suggestions on what to try or what to fix are appreciated.
static async void GetWorkItemsToTaskFromADO(string tfs_project, string accessToken)
{
var credentials = new VssBasicCredential(string.Empty, accessToken);
var wiql = new Wiql()
{
Query = #"Select [Id] From WorkItems WHERE [System.TeamProject] = 'SampleADOProject' AND [System.AreaPath] = 'Sample\ADO\AreaPath' AND [System.IterationPath] = 'Sample\ADO\IterationPath' AND [System.State] = 'Committed'"
};
using (var httpClient = new WorkItemTrackingHttpClient(new Uri(tfs_project), credentials))
{
try
{
var result = await httpClient.QueryByWiqlAsync(wiql).ConfigureAwait(false);
var ids = result.WorkItems.Select(item => item.Id).ToArray();
var fields = new[] { "System.Id", "System.Title", "System.State" };
var workItems = await httpClient.GetWorkItemsAsync(ids, fields, result.AsOf).ConfigureAwait(false);
// output results to test what came back...
foreach (var workItem in workItems)
{
Console.WriteLine(
"{0}\t{1}\t{2}",
workItem.Id,
workItem.Fields["System.Title"],
workItem.Fields["System.State"]
);
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
Console.Read();
}
}
}

Related

How to mock Azure blobContainerClient.GetBlobsAsync()

I have a Azure blob container which I am accessing using below code -
var blobContainerClient = GetBlobContainer(containerName);
if (blobContainerClient != null)
{
// List all blobs in the container
await foreach (BlobItem blobItem in blobContainerClient.GetBlobsAsync())
{
queuedBlobsList.Add(new QueuedBlobs { BlobName = blobItem.Name, LastModified = blobItem.Properties.LastModified });
}
}
private BlobContainerClient GetBlobContainer(string containerName)
{
return gen2StorageClient != null
? gen2StorageClient.GetBlobContainerClient(containerName)
: gen1StorageClient.GetBlobContainerClient(containerName);
}
The clients are initialised in constructor -
public class BlobService : IBlobService
{
private readonly BlobServiceClient gen1StorageClient, gen2StorageClient;
public BlobService(BlobServiceClient defaultClient, IAzureClientFactory<BlobServiceClient> clientFactory)
{
gen1StorageClient = defaultClient;
if (clientFactory != null)
{
gen2StorageClient = clientFactory.CreateClient("StorageConnectionString");
}
}
}
And my unit test where I am setting GetBlobsAsync is like this -
But I want to add list of BlobItems to test another loop.
private static Mock<BlobContainerClient> GetBlobContainerClientMockWithListOfBlobs()
{
var blobContainerClientMock = new Mock<BlobContainerClient>("UseDevelopmentStorage=true", EnvironmentConstants.ParallelUploadContainer);
var cancellationToken = new CancellationToken();
var blobs = new List<BlobItem>();
//AsyncPageable<BlobItem> blobItems = new AsyncPageable<BlobItem>(); -- Not allowing
blobContainerClientMock.Setup(x => x.GetBlobsAsync(BlobTraits.All, BlobStates.All, null, cancellationToken)).Returns(It.IsAny<AsyncPageable<BlobItem>>());
return blobContainerClientMock;
}
I came to this question because I also had the same issue.
Based on this article
AsyncPageable<T> and Pageable<T> are classes that represent collections of models returned by the service in pages.
The method GetBlobsAsync returns an AsyncPageable.
To Create an AsyncPageable you need first to create a BlobItem Page.
To create a Page<T> instance, use the Page<T>.FromValues method, passing a list of items, a continuation token, and the Response.
So let's start creating the list of items:
var blobList = new BlobItem[]
{
BlobsModelFactory.BlobItem("Blob1"),
BlobsModelFactory.BlobItem("Blob2"),
BlobsModelFactory.BlobItem("Blob3")
};
Note: BlobItem has an internal constructor but I found in this answer that there's a BlobsModelFactory.
After having the list of blobs is time to create a Page<BlobItem>:
Page<BlobItem> page = Page<BlobItem>.FromValues(blobList, null, Mock.Of<Response>());
And finally, create the AsyncPageable<BlobItem>
AsyncPageable<BlobItem> pageableBlobList = AsyncPageable<BlobItem>.FromPages(new[] { page });
And now you are able to use this to mock GetBlobsAsync method:
blobContainerClientMock
.Setup(m => m.GetBlobsAsync(
It.IsAny<BlobTraits>(),
It.IsAny<BlobStates>(),
It.IsAny<string>(),
It.IsAny<CancellationToken>()))
.Returns(pageableBlobList);
I hope this helps others with this issue.
André

Await for ChangeResourceRecordSetsAsync hangs forever when trying to create Route53 DNS record

I am trying to create a TXT record in AWS Route53, but while awaiting the call, it will never complete.
The record is not being created in the hosted zone. The account has the correct permissions which I tested using the AWS CLI.
I am able to list hosted zones as also shown in the code below.
public static async Task CreateRecordAsync()
{
var route53Client = new AmazonRoute53Client("<myAccessKey>", "<mySecretKey>", RegionEndpoint.EUCentral1);
var test = new ListHostedZonesByNameRequest();
var testResponse = route53Client.ListHostedZonesByNameAsync(test);
foreach (var zone in testResponse.Result.HostedZones)
{
Console.WriteLine($"{zone.Name}{zone.Id}");
}
var response = await route53Client.ChangeResourceRecordSetsAsync(new ChangeResourceRecordSetsRequest
{
ChangeBatch = new ChangeBatch
{
Changes = new List<Change> {
new Change {
Action = "CREATE",
ResourceRecordSet = new ResourceRecordSet {
Name = "my.domain.net",
Type = "TXT",
TTL = 60,
ResourceRecords = new List<ResourceRecord>
{
new ResourceRecord
{
Value = "test txt value"
}
}
}
}
},
Comment = "Test Entry"
},
HostedZoneId = "Z2Q***********"
});
}
The problem was that the TXT record had to be enclosed in double quotes. I just had to catch the correct exception.
try
{
....
ChangeResourceRecordSetsResponse recordsetResponse =
await route53Client.ChangeResourceRecordSetsAsync(recordsetRequest);
....
}
catch (InvalidChangeBatchException ex)
{
Console.WriteLine(ex);
}
Which means that I should have constructed my record like this using.
ResourceRecordSet recordSet = new ResourceRecordSet
{
Name = chosenDomain,
TTL = 60,
Type = RRType.TXT,
ResourceRecords = new List<ResourceRecord>
{
new ResourceRecord
{
Value = "\"This is my test txt record\""
}
}
};

C# how to call async await in a for loop

I am developing a quartz.net job which runs every 1 hour. It executes the following method. I am calling a webapi inside a for loop. I want to make sure i return from the GetChangedScripts() method only after all thread is complete? How to do this or have i done it right?
Job
public void Execute(IJobExecutionContext context)
{
try
{
var scripts = _scriptService.GetScripts().GetAwaiter().GetResult();
}
catch (Exception ex)
{
_logProvider.Error("Error while executing Script Changed Notification job : " + ex);
}
}
Service method:
public async Task<IEnumerable<ChangedScriptsByChannel>> GetScripts()
{
var result = new List<ChangedScriptsByChannel>();
var currentTime = _systemClock.CurrentTime;
var channelsToProcess = _lastRunReader.GetChannelsToProcess().ToList();
if (!channelsToProcess.Any()) return result;
foreach (var channel in channelsToProcess)
{
var changedScripts = await _scriptRepository.GetChangedScriptAsync(queryString);
if (changedScriptsList.Any())
{
result.Add(new ChangedScriptsByChannel()
{
ChannelCode = channel.ChannelCode,
ChangedScripts = changedScriptsList
});
}
}
return result;
}
As of 8 days ago there was a formal announcement from the Quartz.NET team stating that the latest version, 3.0 Alpha 1 has full support for async and await. I would suggest upgrading to that if at all possible. This would help your approach in that you'd not have to do the .GetAwaiter().GetResult() -- which is typically a code smell.
How can I use await in a for loop?
Did you mean a foreach loop, if so you're already doing that. If not the change isn't anything earth-shattering.
for (int i = 0; i < channelsToProcess.Count; ++ i)
{
var changedScripts =
await _scriptRepository.GetChangedScriptAsync(queryString);
if (changedScriptsList.Any())
{
var channel = channelsToProcess[i];
result.Add(new ChangedScriptsByChannel()
{
ChannelCode = channel.ChannelCode,
ChangedScripts = changedScriptsList
});
}
}
Doing these in either a for or foreach loop though is doing so in a serialized fashion. Another approach would be to use Linq and .Select to map out the desired tasks -- and then utilize Task.WhenAll.

Suitescript Code stops for no apparent Reason

I have the following code which executes a search, then just stops.
for (var i=1; i<=numberItems; i++ ) {
nlapiInsertLineItem(SUBLIST_Items,1);
var itemID = vendorItems[i].getId();
nlapiSetCurrentLineItemValue(SUBLIST_Items,'custrecordvpri_item',itemID );
var avgCost = Round(nlapiLookupField(itemType,itemID,'averagecost'),4);
var stdCost = Round(nlapiLookupField(itemType,itemID,'custitem_costrepl'),4);
var lastCost = Round(nlapiLookupField(itemType,itemID,'lastpurchaseprice'),4);
if (isNaN(avgCost)) { avgCost = '' };
if (isNaN(stdCost)) { stdCost = '' };
if (isNaN(lastCost)) { lastCost = '' };
nlapiSetCurrentLineItemValue(SUBLIST_Items,'custrecordvpri_costavg', avgCost );
nlapiSetCurrentLineItemValue(SUBLIST_Items,'custrecordvpri_costlast', lastCost );
nlapiSetCurrentLineItemValue(SUBLIST_Items,'custrecordvpri_coststd', stdCost );
nlapiSetCurrentLineItemValue(SUBLIST_Items,'custrecordvpri_vendorcurrency',vendorItems[i].getValue('vendorpricecurrency'));
nlapiSetCurrentLineItemValue(SUBLIST_Items,'custrecordvpri_currentprice',vendorItems[i].getValue('vendorcost'));
nlapiCommitLineItem(SUBLIST_Items);
}
It is all running as a client script, triggered by a button on the supplier record.
There are some sub functions within this functon (ie. a search etc...).
I cannot find a reason why the code would stop.
if I comment out the "while" loop, it executes the new window etc... and the main record (VprRecord) is created, but with no sublist items.
Is there something I'm missing here?? I'm not an experienced JS programmer, but the basics are there. Is there a limited number of nested functions permitted or something like that?
I only have the one record creation, so governance shouldn't be an issue.
Adding my search function which returns the search result object:
function getVendorItems(vendorid) {
try {
var filters = new Array();
var columns = new Array();
filters[0] = new nlobjSearchFilter('vendorcost', null, 'greaterthan', 0);
filters[1] = new nlobjSearchFilter('internalid', 'vendor', 'anyof', vendorid );
columns[0] = new nlobjSearchColumn('itemid');
columns[1] = new nlobjSearchColumn('entityid', 'vendor');
columns[2] = new nlobjSearchColumn('vendorcost');
columns[3] = new nlobjSearchColumn('vendorcode');
columns[4] = new nlobjSearchColumn('vendorpricecurrency');
//columns[5] = new nlobjSearchColumn('preferredvendor');
var searchresults = nlapiSearchRecord('item', null, filters, columns );
return searchresults;
} catch (err) { logError(err,'VPR_getVendorItems: (Vendor: '+vendorid+')' ) }
}
The code does not execute because there are unhandled javascript errors.
put your code in try catch block and on error log on console eg:
try { ...} catch(e){console.dir(e);}
Use browser's console using F12 to see the error
Also, make sure that you operate on searchResults as array not nlobjSearchResult

What is the PostFileWithRequest equivalent in ServiceStack's 'New API'?

I want to post some request values alongside the multipart-formdata file contents. In the old API you could use PostFileWithRequest:
[Test]
public void Can_POST_upload_file_using_ServiceClient_with_request()
{
IServiceClient client = new JsonServiceClient(ListeningOn);
var uploadFile = new FileInfo("~/TestExistingDir/upload.html".MapProjectPath());
var request = new FileUpload{CustomerId = 123, CustomerName = "Foo"};
var response = client.PostFileWithRequest<FileUploadResponse>(ListeningOn + "/fileuploads", uploadFile, request);
var expectedContents = new StreamReader(uploadFile.OpenRead()).ReadToEnd();
Assert.That(response.FileName, Is.EqualTo(uploadFile.Name));
Assert.That(response.ContentLength, Is.EqualTo(uploadFile.Length));
Assert.That(response.Contents, Is.EqualTo(expectedContents));
Assert.That(response.CustomerName, Is.EqualTo("Foo"));
Assert.That(response.CustomerId, Is.EqualTo(123));
}
I can't find any such method in the new API, nor any overrides on client.Post() which suggest that this is still possible. Does anyone know if this is a feature that was dropped?
Update
As #Mythz points out, the feature wasn't dropped. I had made the mistake of not casting the client:
private IRestClient CreateRestClient()
{
return new JsonServiceClient(WebServiceHostUrl);
}
[Test]
public void Can_WebRequest_POST_upload_binary_file_to_save_new_file()
{
var restClient = (JsonServiceClient)CreateRestClient(); // this cast was missing
var fileToUpload = new FileInfo(#"D:/test/test.avi");
var beforeHash = this.Hash(fileToUpload);
var response = restClient.PostFileWithRequest<FilesResponse>("files/UploadedFiles/", fileToUpload, new TestRequest() { Echo = "Test"});
var uploadedFile = new FileInfo(FilesRootDir + "UploadedFiles/test.avi");
var afterHash = this.Hash(uploadedFile);
Assert.That(beforeHas, Is.EqualTo(afterHash));
}
private string Hash(FileInfo file)
{
using (var md5 = MD5.Create())
{
using (var stream = file.OpenRead())
{
var bytes = md5.ComputeHash(stream);
return BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLower();
}
}
}
None of the old API was removed from the C# Service Clients, only new API's were added.
The way you process an uploaded file inside a service also hasn't changed.

Resources