Target Invocation Exception in async method - c#

I am trying to retrieve items from an rss feed but at times I get a TargetInvocationException 'unable to connect to remote server'. I am trying to use a try catch block to catch this error but I am not managing as I need the variable feed to be used throughout the other code and like this it is not visible. Any suggestions?
public static async Task<List<FeedItem>> getFeedsAsync(string url)
{
//The web object that will retrieve our feeds..
SyndicationClient client = new SyndicationClient();
//The URL of our feeds..
Uri feedUri = new Uri(url);
//Retrieve async the feeds..
try
{
var feed = await client.RetrieveFeedAsync(feedUri);
}
catch (TargetInvocationException e)
{
}
//The list of our feeds..
List<FeedItem> feedData = new List<FeedItem>();
//Fill up the list with each feed content..
foreach (SyndicationItem item in feed.Items)
{
FeedItem feedItem = new FeedItem();
feedItem.Content = item.Summary.Text;
feedItem.Link = item.Links[0].Uri;
feedItem.PubDate = item.PublishedDate.DateTime;
feedItem.Title = item.Title.Text;
try
{
feedItem.Author = item.Authors[0].Name;
}
catch(ArgumentException)
{ }
feedData.Add(feedItem);
}
return feedData;
}
}
}

This kind of error cannot be prevented. It is an exogenous exception.
There is only one way to deal with those kinds of errors: your application must be designed to expect them and react in a reasonable way (e.g., bring up an error dialog or notification).
In particular, don't try to ignore them with an empty catch block.

IAsyncOperationWithProgress<SyndicationFeed, RetrievalProgress> feed;
//Retrieve async the feeds..
try
{
feed = await client.RetrieveFeedAsync(feedUri);
}
catch (TargetInvocationException e)
{
}

Related

Cancellation Token Disposed Exception

I had this piece of code that initially worked fine. However, After adding it to a class where I store my methods that are reused, it keeps failing. The exception that is caught states that the CancellationTokenSource has been Disposed. Can someone point me in the right direction?
I have tried creating a new client and Adding CancellationToken.None to the PutAsync() method from HTTPClient Class but it still fails with the CancellationTokenSource Disposed exception.
public async void AddProduct(Product product)
{
string storeId = "";
try
{
var storeData = JObject.Parse(Connect.Json).SelectToken("store").ToString();
var stores = JsonConvert.DeserializeObject<List<Store>>(storeData);
var store = stores[0];
storeId = store.Id;
store.Products.Add(product);
ProdInfo info = new Info();
foreach(Product p in store.Products)
{
info.AddedProducts = + p.Id;
}
var content = JsonConvert.SerializeObject(info);
using (Connect.Client)
using (var response = await Connect.Client.PutAsync(_url + "/stores/" + storeId, new StringContent(content)))
{
var cont = response.Content;
string result = await cont.ReadAsStringAsync();
if ((int)response.StatusCode == 200)
{
this.JobResult = result;
//this.JobResult = "Store has been successfully updated";
}
else
{
this.JobResult = result;
//this.JobResult = "Store was not updated!";
}
}
}
catch (Exception ex)
{
//this.JobResult = "Store has not been updated due to an error.";
this.JobResult = ex.Message;
}
}
I was able to solve this by simple removing 'using(Connect.Client)' from all of my methods. As #sellotape stated, They were disposing of the HttpClient before I was able to use it again. Thank you all for your contributions.

Data structure to use when gathering response from async calls

I am running this piece of code in my application.
public Task<BulkResponse<JObject>> GetRelatedObjectsAsync(IEnumerable<PrimaryObjectInfo> primaryObjectInfos)
{
var allSecondaries = new List<Tuple<int, List<JObject>>>();
var exceptionsDict = new ConcurrentDictionary<int, Exception>();
var relatedObjectsTasks = primaryObjectInfos.Select(async primaryObjectInfo =>
{
try
{
var secondaryObject = await objectManager.GetRelatedObjectsAsync(primaryObjectInfo);
allSecondaries.Add(Tuple.Create(primaryObjectInfo.Index, secondaryObject.ToList()));
}
catch (Exception ex)
{
exceptionsDict.TryAdd(primaryObjectInfo.Index, ex);
}
});
await Task.WhenAll(relatedObjectsTasks);
return ConvertToBulkResponse(allSecondaries, exceptionsDict);
}
When I run this code allSecondaries object sometimes returns valid list of results and sometimes the code ends up catching exceptions for the parallel threads I have for each primaryObjectInfo.
Async method objectManager.GetRelatedObjectsAsync() internally call 4-5 async functions and there are functions where parameters are passed by reference. (ref keyword)
Question:
Am I using the right data structure to consolidate the result from all parallel threads ?
If yes, what could be the reason I am getting different result every time?
You'd better split the execution from the results gathering:
public Task<BulkResponse<JObject>> GetRelatedObjectsAsync(
IEnumerable<PrimaryObjectInfo> primaryObjectInfos)
{
var relatedObjectsTasks = primaryObjectInfos
.Select(
async primaryObjectInfo =>
(primaryObjectInfo.Index,
await objectManager.GetRelatedObjectsAsync(primaryObjectInfo)))
.ToList();
try
{
await Task.WhenAll(relatedObjectsTasks);
}
catch
{
// observe each task's, exception
}
var allSecondaries = new List<(int index, List<JObject> related)>();
var exceptionsDict = new Dictionary<int, Exception>();
foreach (var relatedObjectsTask in relatedObjectsTasks)
{
try
{
allSecondaries.Add(relatedObjectsTask.Result);
}
catch (Exception ex)
{
exceptionsDict.Add(relatedObjectsTask.index, ex);
}
}
return ConvertToBulkResponse(allSecondaries, exceptionsDict);
}
You could look into each task's IsFaulted/Exception and IsCancelled properties instead of causing exceptions to be thrown:
foreach (var relatedObjectsTask in relatedObjectsTasks)
{
if (relatedObjectsTask.IsCancelled)
{
exceptionsDict.Add(
relatedObjectsTask.index,
new TaskCancelledException(relatedObjectsTask));
}
else if (relatedObjectsTask.IsFaulted)
{
exceptionsDict.TryAdd(relatedObjectsTask.index, ex);
}
else
{
allSecondaries.Add(relatedObjectsTask.Result);
}
}

How to catch CLR exception in my code block (C#)

Here is my code:
private Message SendMessage(ref Message message, string serviceURL)
{
Message result = null;
try
{
IRequestChannel channel = null;
BasicHttpBinding binding = ...;
using (var cf = new ChannelFactory<IRequestChannel>(binding, new EndpointAddress(serviceURL)))
{
foreach (OperationDescription op in cf.Endpoint.Contract.Operations)
{
op.Behaviors.Remove<DataContractSerializerOperationBehavior>();
}
cf.Open();
channel = cf.CreateChannel();
channel.Open();
result = channel.Request(message);
channel.Close();
cf.Close();
channel = null;
}
binding = null;
}
catch (Exception ex)
{
Logger.LogError("Error parsing SOAP", ex.Message);
}
return result;
}
On line result = channel.Request(message);
I get an error posted below in a picture. However, I get it only when I turn "Break when" CLR exceptions occur. When I don't debug, my code doesn't go to the catch block.
Looks like you try serialize or deserialize string with value = 'X' to bool. I think you should check contract or check your message object.
Somewhere inside .net code calls XmlConvert.ToBoolean(String) method. Valid values for it 0 or 1 Link to doc

Microsoft.Azure.NotificationHub - Async call in sync method

I currently have to provide a sync as async method in my API: Please find the code below. The only problem is that I don’t have a
sync method in the backend. I use Azure.NotificationHub client. That client has only *Async methods. Is my way reasonable?
public PushHubNotificationResult SendPushMessage(string userId, string message)
{
PushHubNotificationResult result = new PushHubNotificationResult();
try
{
result = SendPushMessageAsync(userId, message).GetAwaiter().GetResult();
} catch (Exception ex)
{
result.Status = PushHubNotificationResultType.Error;
result.Error = ex.Message;
result.Exception = ex;
}
return result;
}
public async Task<PushHubNotificationResult> SendPushMessageAsync(string userId, string message)
{
PushHubNotificationResult result = new PushHubNotificationResult();
// EnableTestSend see: https://azure.microsoft.com/en-us/documentation/articles/notification-hubs-push-notification-fixer/#self-diagnose-tips
// Create a new Notification Hub client.
Microsoft.Azure.NotificationHubs.NotificationHubClient hub =
Microsoft.Azure.NotificationHubs.NotificationHubClient.CreateClientFromConnectionString(NotificationHub, NotificationHubName);
// Sending the message so that all template registrations that contain "messageParam"
// will receive the notifications. This includes APNS, GCM, WNS, and MPNS template registrations.
Dictionary<string, string> templateParams = new Dictionary<string, string>();
templateParams["messageParam"] = message;
string userTag = "_UserId:" + userId; // That line sets the IMEI or SerialNo (WLAN only device) == userId to which the push message is sent
try
{
// Send the push notification and log the results.
NotificationOutcome outcome = await hub.SendTemplateNotificationAsync(templateParams, userTag);
result.Status = PushHubNotificationResultType.Success;
foreach (RegistrationResult hubResult in outcome.Results)
{
result.PushNotificationHub = hubResult.ApplicationPlatform;
result.RegistrationId = hubResult.RegistrationId;
result.Outcome = hubResult.Outcome;
}
}
catch (System.Exception ex)
{
result.Status = PushHubNotificationResultType.Error;
result.Error = ex.Message;
result.Exception = ex;
}
return result;
}
thanks for any advice,
Eric
If you want to use sync-over-async, it's very important that you use ConfigureAwait(false) in your async code, otherwise you are very likely to get a deadlock.
NotificationOutcome outcome =
await hub.SendTemplateNotificationAsync(templateParams, userTag).ConfigureAwait(false);
The async method already converts exceptions to PushHubNotificationResultType.Error, why does the sync version do it too?

reduce complexity of service class

I am developing a web api using WCF Web Api preview 5. At the moment I have a resource class fully functional, how ever I noticed my methods inside this resouce are getting complex.
For example:
[WebInvoke(UriTemplate = "{EhrID}/PhysicalTest",Method="POST")]
public HttpResponseMessage<DTO.PhysicalTest> PostPhysicalTest(int EhrID, DTO.PhysicalTest PhysicalTestDTO)
{
var EHR = repository.FindById(EhrID);
var PhysicalTest = Mapper.Map<DTO.PhysicalTest, PhysicalTest>(PhysicalTestDTO);
if (PhysicalTest == null)
{
var response = CreateResponseForException("No object to store", HttpStatusCode.BadRequest);
throw new HttpResponseException(response);
}
try
{
if (EHR.PhysicalTests == null)
{
EHR.PhysicalTests = new List<PhysicalTest>();
}
PhysicalTest.CreationDate = DateTime.Now;
EHR.PhysicalTests.Add(PhysicalTest);
_unitOfWork.Commit();
return new HttpResponseMessage<DTO.PhysicalTest>(PhysicalTestDTO, HttpStatusCode.Created);
}
catch (Exception ex) {
var response = CreateResponseForException("Cannot create Physical Test", HttpStatusCode.InternalServerError);
throw new HttpResponseException(response);
}
}
As you may notice this method has the task of posting a new Physical Test, but it's actually validating my model too (I'm missing lots of validations still, property validations), which should not be this class concern. If there any approachable way to reduce the complexity of the methods inside de resource?
I would split it up into smaller more focused methods. I might also start using instance variables instead of passing all these arguments around, but for the sake of this post I've rewritten it without pushing stuff to instance variables.
[WebInvoke(UriTemplate = "{EhrID}/PhysicalTest",Method="POST")]
public HttpResponseMessage<DTO.PhysicalTest> PostPhysicalTest(int EhrID, DTO.PhysicalTest PhysicalTestDTO)
{
var EHR = repository.FindById(EhrID);
var PhysicalTest = Mapper.Map<DTO.PhysicalTest, PhysicalTest>(PhysicalTestDTO);
if (PhysicalTest == null)
{
var response = CreateResponseForException("No object to store", HttpStatusCode.BadRequest);
throw new HttpResponseException(response);
}
PostPhysicalTest(EHR, PhysicalTest);
return new HttpResponseMessage<DTO.PhysicalTest>(PhysicalTestDTO, HttpStatusCode.Created);
}
private void PostPhysicalTest(EHR ehr, PhysicalTest physicalTest)
{
try
{
CreatePhysicalTest(ehr, physicalTest);
}
catch (Exception ex) {
var response = CreateResponseForException("Cannot create Physical Test", HttpStatusCode.InternalServerError);
throw new HttpResponseException(response);
}
}
private void CreatePhysicalTest(EHR ehr, PhysicalTest physicalTest)
{
if (ehr.PhysicalTests == null)
{
ehr.PhysicalTests = new List<PhysicalTest>();
}
physicalTest.CreationDate = DateTime.Now;
ehr.PhysicalTests.Add(physicalTest);
_unitOfWork.Commit();
}

Categories