xamarin for android throws NullReferenceException when trying to request location updates - xamarin

I can't seem to figure out, why is this causing an exception.
GPSListener gps = new GPSListener(); // <- implements ILocationListener interface
(LocationManager)GetSystemService(LocationService).RequestLocationUpdates(LocationManager.GpsProvider, 0, 0, gps); // <- System.NullReferenceException
Calling IsProviderEnabled for the "gps" provider returns true.
GetSystemService does also return a valid LocationManager and not a null. gps object is also not null. ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION are also added to the manifest.
The call stack
at Android.Runtime.JNINativeWrapper._unhandled_exception (System.Exception e) [0x0000e] in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Android.Runtime/JNINativeWrapper.g.cs:12
at Android.Runtime.JNINativeWrapper.Wrap_JniMarshal_PP_V (_JniMarshal_PP_V callback, System.IntPtr jnienv, System.IntPtr klazz) [0x0001c] in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Android.Runtime/JNINativeWrapper.g.cs:23
at (wrapper native-to-managed) Android.Runtime.JNINativeWrapper.Wrap_JniMarshal_PP_V(intptr,intptr)
The internal exception message is "Object reference not set to an instance of an object."
How can i find out more information what is actually not set in this situation. And how could i fix it. The error happens both in emulator (API 30) and physical phone with Android 7.

Please make sure your app has been granted the permission about the location by the user, not only declare it in the AndroidManifest.xml. And you can add the following code into the oncreate method of the activity to do that.
var status = await Permissions.RequestAsync<Permissions.LocationWhenInUse>();
In addition, if you call the method in the background service, you need to add the ACCESS_BACKGROUND_LOCATION in the AndroidManifest.xaml and use the following code:
var status = await Permissions.RequestAsync<Permissions.LocationAlways>();

Related

How disable location in Xamarin.Forms UI Test

How can I disable location while single UI test in xamarin forms (I am using Android 8.1 simulator)? In one test case I want cancel location permission, and in other simulate that the GPS can not find user location.
I thought about backdors, but I did not found nothing useful or up to date on msdn and stack (some links pasted bellow).
I have tried something like this (and much more similar 'mutations'):
Droid.MainActivity:
[Export("GpsBackdoor")]
public void GpsBackdoor()
{
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.PutExtra("enabled", Java.Lang.Boolean.False);
SendBroadcast(intent);
}
UITests.Test:
[Test]
public void SetCurrentUserLocation_WhenGPSisOff_ShouldShowAlert()
{
app.WaitForElement(x => x.Text("Nearest stops"));
app.Invoke("GpsBackdoor");
app.Tap(x => x.Text("Nearest stops"));
var result = app.WaitForElement("Could not obtain position");
}
After running test I am getting message:
System.Exception : Error while performing Invoke("GpsBackdoor", null)
----> System.Net.Http.HttpRequestException : An error occurred while sending
the request.
----> System.Net.WebException : The underlying connection was closed: The
connection was closed unexpectedly.
at Xamarin.UITest.Utils.ErrorReporting.With[T](Func`1 func, Object[] args,
String memberName)
at Xamarin.UITest.Android.AndroidApp.Invoke(String methodName, Object
argument)
at BusMap.Mobile.UITests.NearestStopsMapPageTests.
SetCurrentUserLocation_WhenGPSisOff_ShouldShowAlert() in
<source>\NearestStopsMapPageTests.cs:line 40
--HttpRequestException
at Xamarin.UITest.Shared.Http.HttpClient.SendData(String endpoint, String
method, HttpContent content, ExceptionPolicy exceptionPolicy, Nullable`1
timeOut)
at Xamarin.UITest.Shared.Http.HttpClient.Post(String endpoint, String
arguments, ExceptionPolicy exceptionPolicy, Nullable`1 timeOut)
at Xamarin.UITest.Android.AndroidGestures.Invoke(String methodName, Object[]
arguments)
at Xamarin.UITest.Utils.ErrorReporting.With[T](Func`1 func, Object[] args,
String memberName)
--WebException
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
I've also tried turn off Wifi or cellular data, which gave me the same error.
I will be grateful for any help.
P.S. Some links which I've found:
Enable/Disable wifi using Xamarin UiTest
How to start GPS ON and OFF programatically in Android

Bot Framework: Can't get ActivityTypes.Typing to work.

I've been programming a lot with the MS Bot Framework but I can't seem to make this seemingly trivial part work: sending a Typing activity.
This fails every time:
"Object reference not set to an instance of an object"
What is going on?
Try it like this (if inside a dialog):
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
{
var activity = await result as Activity;
var activity2 = activity.CreateReply();
activity2.Type = ActivityTypes.Typing;
await context.PostAsync(activity2);
context.Wait(MessageReceivedAsync);
}
This is most likely because you are using MakeMessage() but not actually setting any of the fields it needs, you are only setting Type so some property in the activity created is throwing the null object reference error.

Microsoft Bot Framework: Exception: The data is changed

I have a bot with the following conversation scenario:
Send text to LUIS
LUIS intent calls context.Call(...) to launch a Dialog
This dialog terminates, save some info in the userData:
private static async Task storeBotData(IDialogContext context, BotData userData)
{
Activity activity = (Activity)context.Activity;
StateClient sc = activity.GetStateClient();
await sc.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
}
And after it call another dialog, again with context.Call(...).
Then the last dialog runs and terminates.
My problem is that when updating the user data at the end of the first dialog (step 3), I have the following exception in the Bot Framework Channel Emulator:
`Exception: The data is changed [File of type 'text/plain']`...
What happens here ? I think that when a dialog terminates, it call setUserData by itself, but I don't understand why I can't update userData anywhere in the code...
I have tried to catch the exception, but nothing is catched.. But I know that the userData is updated, because when I try to retrieve it back, it is updated...
Any help is welcome :)
Thanks
Botframework restores/saves state of conversation after each act of activity, so under the covers typical flow looks like the following:
[23:15:40] <- GET 200 getUserData
[23:15:47] <- GET 200 getConversationData
[23:15:47] <- GET 200 getPrivateConversationData
...
[23:16:42] <- POST 200 setConversationData
[23:16:42] <- POST 200 setUserData
[23:16:42] <- POST 200 setPrivateConversationData
As it is mentioned here : These botData objects will fail to be stored if another instance of your bot has changed the object already. So in your case the exception occurs at the termination of dialog, when framework calls setUserData by himself and figures out that the BotData has been changed already (by your explicit call of BotState.SetUserDataAsync). I suppose that's why you were not able to catch the exception.
Solution:
I used the following code and it fixed the issue:
private static void storeBotData(IDialogContext context, BotData userData)
{
var data = context.UserData;
data.SetValue("field_name", false);
}
The reason it works is that we modify the object of UserData but allow botFramework to "commit" it himself, so there is no conflict
I agree with #Artem (this solved my issue too, thanks!). I would just add the following guideline.
Use
var data = context.UserData;
data.SetValue("field_name", false);
whenever you have a IDialogContext object available, so you let the Bot Framework commit changes.
Use instead
StateClient sc = activity.GetStateClient();
await sc.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
when you don't have an IDialogContext object, e.g. in the MessageController class.

Use of undefined keyword value 1 for event TaskScheduled

When debugging my universal Windows (8.1) app i encounter the following error from time to time:
System.ArgumentException was unhandled
_HResult=-2147024809
_message=Use of undefined keyword value 1 for event TaskScheduled.
HResult=-2147024809
IsTransient=false
Message=Use of undefined keyword value 1 for event TaskScheduled.
Source=mscorlib
StackTrace:
at System.Diagnostics.Tracing.ManifestBuilder.GetKeywords(UInt64 keywords, String eventName)
at System.Diagnostics.Tracing.ManifestBuilder.StartEvent(String eventName, EventAttribute eventAttribute)
at System.Diagnostics.Tracing.EventSource.CreateManifestAndDescriptors(Type eventSourceType, String eventSourceDllName, EventSource source)
at System.Diagnostics.Tracing.EventSource.EnsureInitialized()
at System.Diagnostics.Tracing.EventSource.SendCommand(EventListener listener, Int32 perEventSourceSessionId, Int32 etwSessionId, EventCommand command, Boolean enable, EventLevel level, EventKeywords matchAnyKeyword, IDictionary`2 commandArguments)
at System.Diagnostics.Tracing.EventSource.OverideEventProvider.OnControllerCommand(ControllerCommand command, IDictionary`2 arguments, Int32 perEventSourceSessionId, Int32 etwSessionId)
at System.Diagnostics.Tracing.EventProvider.EtwEnableCallBack(Guid& sourceId, Int32 controlCode, Byte setLevel, Int64 anyKeyword, Int64 allKeyword, EVENT_FILTER_DESCRIPTOR* filterData, Void* callbackContext)
I can then skip this error and am able to proceed using the app in debug mode but when installed on a device the app will crash.
I have searched for an answer for some time now but the only answer i have come across here is to disable breaking on these kind of exceptions which is of course not a very good answer.
Thanks in advance.
EDIT 1:
Ok, i have a very simple sample project with which this error is easily reproduced. I created a Universal App Blank app in Visual Studio 2013 Ultimate and added the following code to the App.xaml.cs.
The exception posted above is raised on the line with await.
Can anybody help because this is plagueing me for months now.
public App()
{
this.InitializeComponent();
this.Suspending += this.OnSuspending;
callService();
}
async public Task callService()
{
string url = "http://eu.battle.net/api/d3/profile/bunnynut-2128/";
HttpClient client = new HttpClient();
string data = await client.GetStringAsync(url);
client.Dispose();
}

handle some errors in Global.asax

I have a web application on .NET4 and MVC3 (razor) .
I want to handle my application errors in Global.asax. I have created application_error function.
I have noticed and found some errors.
one of them returns this string in Application_Error when I am trying to add break point on line Response.Clear(); and that error is generic.
how can I find which codes or part of my codes makes it?
my code:
protected void Application_Error()
{
var exception = Server.GetLastError();
var httpException = exception as HttpException;
Response.Clear();
Server.ClearError();
}
error on httpException:
{System.Web.HttpException (0x80004005): File does not exist.
at System.Web.StaticFileHandler.GetFileInfo(String virtualPathWithPathInfo, String
physicalPath, HttpResponse response)
at System.Web.StaticFileHandler.ProcessRequestInternal(HttpContext context, String
overrideVirtualPath)
at System.Web.DefaultHttpHandler.BeginProcessRequest(HttpContext context,
AsyncCallback callback, Object state) at
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionSt
ep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&
completedSynchronously)}
i found the solution
string errorLocation = Request.Path;
this syntax in Application_Error() tel you where is the problem :)
Just to state my experience with this exception, in my case the reason was that there was no webpage specified as the start page for the site.

Resources