I have used GetGeoPositionAsync() in my app and it works fine in the code of another feature, however when using it in the feature I am currently implementing, it freezes the first time I try to call it, and works the second time. I call this function when navigating from another page. Here's the code:
private async Task GetLocation()
{
Geolocator myGeolocator = new Geolocator();
Geoposition myGeoposition = null;
try
{
myGeoposition = await myGeolocator.GetGeopositionAsync();
}
catch (Exception ex)
{
if ((uint)ex.HResult == 0x80004004)
{
MessageBox.Show("Unauthorized access.");
}
}
}
I tried browsing SO, but haven't found a working solution for this. Why does it work in some pieces of code, and in some it just doesn't. What is the cause of this behaviour?
Ok, so I found a solution:
try
{
IAsyncOperation<Geoposition> locationTask = null;
try
{
locationTask = myGeolocator.GetGeopositionAsync(TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(3));
myGeoposition = await locationTask;
}
finally
{
if (locationTask != null)
{
if (locationTask.Status == AsyncStatus.Started)
locationTask.Cancel();
locationTask.Close();
}
}
}
This sounds like the position is cached! The first time you call the method it tries to get your position (this can take many seconds if you are inside a building), the second time it seems to use the cached position.
Related
If someone doesn't have a profile picture, a NotFound exception kicks me out of the code. How can I work around this?
My Method:
if(graphManager.Client.Users[user.Id].Photo.Content.Request().GetAsync().IsNull())
{
Debug.Log("profilepicture not found");
}
else
{
var photo = await graphManager.Client.Users[mitarbeiter.Id].Photo.Content.Request().GetAsync();`
}
Response: It skips the if cause it thinks it's not null
What I need is a Method to create a Debug.Log if the exception happens and not throw me out
It seems that getting an exception when a photo is not found is a valid case. See docs on errors.
Try to handle it in the following way:
try
{
Stream photoContent = await graphManager.Client.Users[user.Id].Photo.Content.Request().GetAsync();
}
catch (ServiceException ex) when (ex.IsMatch(GraphErrorCode.ItemNotFound.ToString()))
{
Debug.Log("profilepicture not found");
}
P.S. I'm not sure precisely which GraphErrorCode should be used here.
I don't know the library you are using but is it possible that in the moment you do
graphManager.Client.Users[user.Id].Photo.Content.Request().GetAsync().IsNull()
what happens is you are basically doing
var asyncResult = graphManager.Client.Users[user.Id].Photo.Content.Request().GetAsync();
if(asyncResult.IsNull())
which of course would be true since you didn't give it any time to actually perform the request and finish.
It should probably rather be
var photo = await graphManager.Client.Users[mitarbeiter.Id].Photo.Content.Request().GetAsync();
if(photo.IsNull() )
{
Debug.Log("profilepicture not found");
}
else
{
...
}
I've encountered a few dificulties trying to handle some errors in the best way possible. One of my cases for example is NullReferenceException.
To be more clear let me explain it in a few words. When I make a call to a server to receive some pieces of information, in some cases the server might have some problems and it will return of course null.
What I've done is I display an alert to let the user know that he can try later again. After this I try to send him in the previous page for example. And after all this my app still crushes.
What I'd like to do is to simply display the alert and then let the user stay in the same page without the application crushing.
These are a few pieces of my code:
tasks.cs
public async Task<List<Idea>> GetIdeaAsync(string accesToken)
{
List<Idea> ideas = null;
try
{
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accesToken);
var json = await client.GetStringAsync("http://www.getdata.de/api/ideas/");
var ideas = JsonConvert.DeserializeObject<List<Idea>>(json);
}
catch (Exception ex)
{
await Application.Current.MainPage.DisplayAlert("Server Error", "There has been an server error. Please try later.", "OK");
if (ideas == null)
{
await Application.Current.MainPage.Navigation.PopAsync(); //actually I would like to stay in the same page
}
}
return ideas;
}
view.xaml.cs
private async void Button_Clicked(object sender, EventArgs e)
{
Tasks ts = new Tasks();
var ideas = await ts.GetIdeasAsync();
if (ideas == null)
{
Debug.WriteLine("hello");
//do nothing since the display alert is already shown
}
else
{
//code here
}
I would really appreciate if anyone can guide me to a "best-practice" approach. Thanks :)
You are declaring ideas in the try block, and then trying to access it in the catch block, where it is out of scope. (Visual Studio should give an Intellisense error)
Also, whenever manipulating the UI, you should always do it on the main thread. so move your DisplayAlert() code into
Device.BeginInvokeOnMainThread(async () =>
{
// await DisplayAlert(); move it into here
});
In addition, any PopAsync or PushAsync calls should also be done on the main UI thread. But calling PopAsync after an asynchronous call to an API not be a good idea, as the user may have already pressed the back button by the time the call returns.
As for the NullReferenceException, check to see if json is null before passing it to the DeserializeObject() function.
The problem it was pretty obvious actually since I after catch-ing the exception I would later continue with the code. So what I did was :
public async Task<List<Idea>> GetIdeaAsync(string accesToken)
{
List<Idea> ideas = null;
try
{
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accesToken);
var json = await client.GetStringAsync("http://www.getdata.de/api/ideas/");
var ideas = JsonConvert.DeserializeObject<List<Idea>>(json);
}
catch (Exception ex)
{
await Application.Current.MainPage.DisplayAlert("Server Error", "There has been an server error. Please try later.", "OK");
if (ideas == null)
{
//actually I would like to stay in the same page
return null; //-- added this line
}
}
return ideas;
}
Maybe it's not the best idea but it's working for me. Any other approach would be highly appreciated. :)
Scratching my head on this one.
I've got a background task in my UWP application which is registered to run every 15 minutes (using TimeTrigger) and whenever the internet becomes available (using a SystemTrigger). I know for a fact that these are registered correctly as both appear in the "Lifecycle Events" when debugging using visual studio. Nevertheless, my code for registering them is below:
bool registered1 = false;
bool registered2 = false;
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
if (task.Value.Name == "BackgroundGPS")
{
registered1 = true;
}
if (task.Value.Name == "InternetAvailGPS")
{
registered2 = true;
}
}
await BackgroundExecutionManager.RequestAccessAsync();
if (!registered1)
{
var builder1 = new BackgroundTaskBuilder();
builder1.Name = "BackgroundGPS";
builder1.TaskEntryPoint = "BackgroundTasks.BackgroundGPSTask";
var triggerTime = new TimeTrigger(15, false);
builder1.SetTrigger(triggerTime);
BackgroundTaskRegistration task1 = builder1.Register();
}
if (!registered2)
{
var builder2 = new BackgroundTaskBuilder();
builder2.Name = "InternetAvailGPS";
builder2.TaskEntryPoint = "BackgroundTasks.BackgroundGPSTask";
var triggerIA = new SystemTrigger(SystemTriggerType.InternetAvailable, false);
builder2.SetTrigger(triggerIA);
BackgroundTaskRegistration task2 = builder2.Register();
}
I have ensured that the tasks are declared correctly in my manifest. If they weren't, my app would be throwing an exception when trying to register them.
If I run in debug mode I can see that both BackgroundGPS and InternetAvailGPS are shown in the Lifecycle Events. However, when I click on either of them to force them to execute, I get the following in the output window:
The program '[4728] backgroundTaskHost.exe' has exited with code 1 (0x1).
I have a breakpoint set at the first line of code in my 'Run' method of the background task but this is never hit. The background task is never loaded nor run, and I've no idea why. This probably isn't an issue with my Run method, but it looks like this (I've omitted much of the meat of it, and just included the beginning and end)
public async void Run(IBackgroundTaskInstance taskInstance)
{
Debug.WriteLine("GPS Started");
int errCode = 0;
try
{
_deferral = taskInstance.GetDeferral();
saveGPSStatus(DateTime.Now.ToString(), "", " ");
var access = await Geolocator.RequestAccessAsync();
if (access != GeolocationAccessStatus.Allowed)
{
Debug.WriteLine("No access");
saveGPSStatus("", "", "No GPS Access");
return;
}
Geolocator locator = new Geolocator();
locator.DesiredAccuracyInMeters = 100;
Geoposition position = await locator.GetGeopositionAsync();
//Stuff goes on in here
_deferral.Complete();
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
saveGPSStatus("", "", "Unexpected error. Err code "+errCode+". " + e.Message);
_deferral.Complete();
}
}
I have tried this both on a Windows Phone and a Windows Tablet both running build 10.0.10586.164, and they both do not execute my background task.
As I said above, these were working perfectly a few weeks ago and have only realised something was wrong as some of the app's users have been complaining!
Any help is greatly appreciated.
Got it working in the end, I was simply missing a reference to my background task project within my main project. I must have deleted it by accident at some point before that.
Just to expand on not having it referenced, not having the correct TaskEntryPoint namespace and class name will also cause this error. For me, I misspelt the class name.
I have an Excel Add-In written in C#, .NET 4.5. It will send many web service requests to a web server to get data. E.g. it sends 30,000 requests to web service server. When data of a request comes back, the addin will plot the data in Excel.
Originally I did all the requests asynchronously, but sometime I will get OutOfMemoryException
So I changed, sent the requests one by one, but it is too slow, takes long time to finish all requests.
I wonder if there is a way that I can do 100 requests at a time asynchronously, once the data of all the 100 requests come back and plot in Excel, then send the next 100 requests.
Thanks
Edit
On my addin, there is a ribbon button "Refresh", when it is clicked, refresh process starts.
On main UI thread, ribbon/button is clicked, it will call web service BuildMetaData,
once it is returned back, in its callback MetaDataCompleteCallback, another web service call is sent
Once it is returned back, in its callback DataRequestJobFinished, it will call plot to plot data on Excel. see below
RefreshBtn_Click()
{
if (cells == null) return;
Range firstOccurence = null;
firstOccurence = cells.Find(functionPattern, null,
null, null,
XlSearchOrder.xlByRows,
XlSearchDirection.xlNext,
null, null, null);
DataRequest request = null;
_reportObj = null;
Range currentOccurence = null;
while (!Helper.RefreshCancelled)
{
if(firstOccurence == null ||IsRangeEqual(firstOccurence, currentOccurence)) break;
found = true;
currentOccurence = cells.FindNext(currentOccurence ?? firstOccurence);
try
{
var excelFormulaCell = new ExcelFormulaCell(currentOccurence);
if (excelFormulaCell.HasValidFormulaCell)
{
request = new DataRequest(_unityContainer, XLApp, excelFormulaCell);
request.IsRefreshClicked = true;
request.Workbook = Workbook;
request.Worksheets = Worksheets;
_reportObj = new ReportBuilder(_unityContainer, XLApp, request, index, false);
_reportObj.ParseParameters();
_reportObj.GenerateReport();
//this is necessary b/c error message is wrapped in valid object DataResponse
//if (!string.IsNullOrEmpty(_reportObj.ErrorMessage)) //Clear previous error message
{
ErrorMessage = _reportObj.ErrorMessage;
Errors.Add(ErrorMessage);
AddCommentToCell(_reportObj);
Errors.Remove(ErrorMessage);
}
}
}
catch (Exception ex)
{
ErrorMessage = ex.Message;
Errors.Add(ErrorMessage);
_reportObj.ErrorMessage = ErrorMessage;
AddCommentToCell(_reportObj);
Errors.Remove(ErrorMessage);
Helper.LogError(ex);
}
}
}
on Class to GenerateReport
public void GenerateReport()
{
Request.ParseFunction();
Request.MetacompleteCallBack = MetaDataCompleteCallback;
Request.BuildMetaData();
}
public void MetaDataCompleteCallback(int id)
{
try
{
if (Request.IsRequestCancelled)
{
Request.FormulaCell.Dispose();
return;
}
ErrorMessage = Request.ErrorMessage;
if (string.IsNullOrEmpty(Request.ErrorMessage))
{
_queryJob = new DataQueryJob(UnityContainer, Request.BuildQueryString(), DataRequestJobFinished, Request);
}
else
{
ModifyCommentOnFormulaCellPublishRefreshEvent();
}
}
catch (Exception ex)
{
ErrorMessage = ex.Message;
ModifyCommentOnFormulaCellPublishRefreshEvent();
}
finally
{
Request.MetacompleteCallBack = null;
}
}
public void DataRequestJobFinished(DataRequestResponse response)
{
Dispatcher.Invoke(new Action<DataRequestResponse>(DataRequestJobFinishedUI), response);
}
public void DataRequestJobFinished(DataRequestResponse response)
{
try
{
if (Request.IsRequestCancelled)
{
return;
}
if (response.status != Status.COMPLETE)
{
ErrorMessage = ManipulateStatusMsg(response);
}
else // COMPLETE
{
var tmpReq = Request as DataRequest;
if (tmpReq == null) return;
new VerticalTemplate(tmpReq, response).Plot();
}
}
catch (Exception e)
{
ErrorMessage = e.Message;
Helper.LogError(e);
}
finally
{
//if (token != null)
// this.UnityContainer.Resolve<IEventAggregator>().GetEvent<DataQueryJobComplete>().Unsubscribe(token);
ModifyCommentOnFormulaCellPublishRefreshEvent();
Request.FormulaCell.Dispose();
}
}
on plot class
public void Plot()
{
...
attributeRange.Value2 = headerArray;
DataRange.Value2 = ....
DataRange.NumberFormat = ...
}
OutOfMemoryException is not about the too many requests sent simultaneously. It is about freeing your resources right way. In my practice there are two main problems when you are getting such exception:
Wrong working with immutable structures or System.String class
Not disposing your disposable resources, especially graphic objects and WCF requests.
In case of reporting, for my opinion, you got a second one type of a problem. DataRequest and DataRequestResponse are good point to start the investigation for the such objects.
If this doesn't help, try to use the Tasks library with async/await pattern, you can find good examples here:
// Signature specifies Task<TResult>
async Task<int> TaskOfTResult_MethodAsync()
{
int hours;
// . . .
// Return statement specifies an integer result.
return hours;
}
// Calls to TaskOfTResult_MethodAsync
Task<int> returnedTaskTResult = TaskOfTResult_MethodAsync();
int intResult = await returnedTaskTResult;
// or, in a single statement
int intResult = await TaskOfTResult_MethodAsync();
// Signature specifies Task
async Task Task_MethodAsync()
{
// . . .
// The method has no return statement.
}
// Calls to Task_MethodAsync
Task returnedTask = Task_MethodAsync();
await returnedTask;
// or, in a single statement
await Task_MethodAsync();
In your code I see a while loop, in which you can store your Task[] of size of 100, for which you can use the WaitAll method, and the problem should be solved. Sorry, but your code is huge enough, and I can't provide you a more straight example.
I'm having a lot of trouble parsing your code to figure out is being iterated for your request but the basic template for batching asynchronously is going to be something like this:
static const int batchSize = 100;
public async Task<IEnumerable<Results>> GetDataInBatches(IEnumerable<RequestParameters> parameters) {
if(!parameters.Any())
return Enumerable.Empty<Result>();
var batchResults = await Task.WhenAll(parameters.Take(batchSize).Select(doQuery));
return batchResults.Concat(await GetDataInBatches(parameters.Skip(batchSize));
}
where doQuery is something with the signature
Task<Results> async doQuery(RequestParameters parameters) {
//.. however you do the query
}
I wouldn't use this for a million requests since its recursive, but your case should would generate a callstack only 300 deep so you'll be fine.
Note that this also assumes that your data request stuff is done asynchronously and returns a Task. Most libraries have been updated to do this (look for methods with the Async suffix). If it doesn't expose that api you might want to create a separate question for how to specifically get your library to play nice with the TPL.
I recently encountered this very strange problem.
Initially I have this block of code
public async Task<string> Fetch(string module, string input)
{
if (module != this._moduleName)
{
return null;
}
try
{
var db = new SQLiteAsyncConnection(_dbPath);
ResponsePage storedResponse = new ResponsePage();
Action<SQLiteConnection> trans = connect =>
{
storedResponse = connect.Get<ResponsePage>(input);
};
await db.RunInTransactionAsync(trans);
string storedResponseString = storedResponse.Response;
return storedResponseString;
}
catch (Exception e)
{
return null;
}
}
However control will never be handed back to my code after the transaction finishes running. I traced the program and it seems that after the lock is release, the flow of program stops. Then I switched to using the GetAsync method from SQLiteAsyncConnection class. Basically it did the same thing so I was still blocked at await. Then I removed the async calls and used the synchronous api like below:
public async Task<string> Fetch(string module, string input)
{
if (module != this._moduleName)
{
return null;
}
try
{
var db = new SQLiteConnection(_dbPath);
ResponsePage storedResponse = new ResponsePage();
lock (_dbLock)
{
storedResponse = db.Get<ResponsePage>(input);
}
string storedResponseString = storedResponse.Response;
return storedResponseString;
}
catch (Exception e)
{
return null;
}
}
Only then can the logic flows back to my code. However I can't figure out why is this so.
Another problem is that for this kind of simple query is there any gain in terms of query time if I use aysnc api instead of sync api? If not I'll stick to the sync version then.
You are most likely calling Result (or Wait) further up the call stack from Fetch. This will cause a deadlock, as I explain on my blog and in a recent MSDN article.
For your second question, there is some overhead from async, so for extremely fast asynchronous operations, the synchronous version will be faster. There is no way to tell whether this is the case in your code unless you do profiling.