How disable location in Xamarin.Forms UI Test - xamarin

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

Related

Following Microsoft AZ-204 Learning Path, Encountered error "Unhandled exception. System.NotSupportedException: Stream does not support reading."

I am following the AZ-204: Develop solutions that use Blob storage / Work with Azure Blob storage tutorial located here.
The code is copy/paste but I have encountered an error. I am not a .net developer and I have no idea how to resolve this. Microsoft offers no troubleshooting resources with this self-led material. I'm hoping to find help for resolving this error.
The file I am attempting to run:
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
Console.WriteLine("Azure Blob Storage exercise\n");
// Run the examples asynchronously, wait for the results before proceeding
ProcessAsync().GetAwaiter().GetResult();
Console.WriteLine("Press enter to exit the sample application.");
Console.ReadLine();
static async Task ProcessAsync()
{
// Copy the connection string from the portal in the variable below.
string storageConnectionString = "[redacted]";
// Create a client that can authenticate with a connection string
BlobServiceClient blobServiceClient = new BlobServiceClient(storageConnectionString);
// COPY EXAMPLE CODE BELOW HERE
// CREATE A CONTAINER
//Create a unique name for the container
string containerName = "wtblob" + Guid.NewGuid().ToString();
// Create the container and return a container client object
BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);
Console.WriteLine("A container named '" + containerName + "' has been created. " +
"\nTake a minute and verify in the portal." +
"\nNext a file will be created and uploaded to the container.");
Console.WriteLine("Press 'Enter' to continue.");
Console.ReadLine();
// UPLOAD BLOBS TO A CONTAINER
// Create a local file in the ./data/ directory for uploading and downloading
string localPath = "./data/";
string fileName = "wtfile" + Guid.NewGuid().ToString() + ".txt";
string localFilePath = Path.Combine(localPath, fileName);
// Write text to the file
await File.WriteAllTextAsync(localFilePath, "Hello, World!");
// Get a reference to the blob
BlobClient blobClient = containerClient.GetBlobClient(fileName);
Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);
// Open the file and upload its data
using (FileStream uploadFileStream = File.OpenWrite(localFilePath))
{
await blobClient.UploadAsync(uploadFileStream);
uploadFileStream.Close();
}
Console.WriteLine("\nThe file was uploaded. We'll verify by listing" +
" the blobs next.");
Console.WriteLine("Press 'Enter' to continue.");
Console.ReadLine();
// LIST THE BLOBS IN A CONTAINER
// List blobs in the container
Console.WriteLine("Listing blobs...");
await foreach (BlobItem blobItem in containerClient.GetBlobsAsync())
{
Console.WriteLine("\t" + blobItem.Name);
}
Console.WriteLine("\nYou can also verify by looking inside the " +
"container in the portal." +
"\nNext the blob will be downloaded with an altered file name.");
Console.WriteLine("Press 'Enter' to continue.");
Console.ReadLine();
// DOWNLOAD BLOBS
// Download the blob to a local file
// Append the string "DOWNLOADED" before the .txt extension
string downloadFilePath = localFilePath.Replace(".txt", "DOWNLOADED.txt");
Console.WriteLine("\nDownloading blob to\n\t{0}\n", downloadFilePath);
// Download the blob's contents and save it to a file
BlobDownloadInfo download = await blobClient.DownloadAsync();
using (FileStream downloadFileStream = File.OpenWrite(downloadFilePath))
{
await download.Content.CopyToAsync(downloadFileStream);
}
Console.WriteLine("\nLocate the local file in the data directory created earlier to verify it was downloaded.");
Console.WriteLine("The next step is to delete the container and local files.");
Console.WriteLine("Press 'Enter' to continue.");
Console.ReadLine();
// DELETE A CONTAINER
// Delete the container and clean up local files created
Console.WriteLine("\n\nDeleting blob container...");
await containerClient.DeleteAsync();
Console.WriteLine("Deleting the local source and downloaded files...");
File.Delete(localFilePath);
File.Delete(downloadFilePath);
Console.WriteLine("Finished cleaning up.");
}
I am able to verify the container was created in the azure portal, then the code runs up to line 46 where "Uploading to Blob storage as blob:" is logged, then encounters the error.
The console output (including prior to the error):
Azure Blob Storage exercise
A container named 'wtblob167d9a9b-d4c0-4b2c-9ea3-21d2c90fd386' has been created.
Take a minute and verify in the portal.
Next a file will be created and uploaded to the container.
Press 'Enter' to continue.
Uploading to Blob storage as blob:
https://[redacted].blob.core.windows.net/wtblob167d9a9b-d4c0-4b2c-9ea3-21d2c90fd386/wtfilebfbd8b5e-d5b3-487c-885b-364db2fe126a.txt
Unhandled exception. System.NotSupportedException: Stream does not support reading.
at System.IO.Strategies.BufferedFileStreamStrategy.CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
at System.IO.FileStream.CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
at Azure.Storage.NonDisposingStream.CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
at Azure.Core.RequestContent.StreamContent.WriteToAsync(Stream stream, CancellationToken cancellation)
at Azure.Core.Pipeline.HttpClientTransport.PipelineRequest.PipelineContentAdapter.SerializeToStreamAsync(Stream stream, TransportContext context, CancellationToken cancellationToken)
at System.Net.Http.HttpContent.<CopyToAsync>g__WaitAsync|56_0(ValueTask copyTask)
at System.Net.Http.HttpConnection.SendRequestContentAsync(HttpRequestMessage request, HttpContentWriteStream stream, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
at Azure.Core.Pipeline.HttpClientTransport.ProcessAsync(HttpMessage message, Boolean async)
at Azure.Core.Pipeline.HttpPipelineTransportPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline)
at Azure.Core.Pipeline.ResponseBodyPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async)
at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.<ProcessAsync>g__ProcessAsyncInner|4_0(HttpMessage message, ReadOnlyMemory`1 pipeline)
onary`2 metadata, IDictionary`2 tags, BlobRequestConditions conditions, Nullable`1 accessTier, BlobImmutabilityPolicy immutabilityPolicy, Nullable`1 legalHold, IProgress`1 progressHandler, UploadTransferValidationOptions transferValidationOverride, String operationName, Boolean async, CancellationToken cancellationToken)
at Azure.Storage.Blobs.Specialized.BlockBlobClient.<>c__DisplayClass64_0.<<GetPartitionedUploaderBehaviors>b__0>d.MoveNext()
--- End of stack trace from previous location --- at Azure.Storage.PartitionedUploader`2.UploadInternal(Stream content, Nullable`1 expectedContentLength, TServiceSpecificData args, IProgress`1 progressHandler, Boolean async, CancellationToken cancellationToken) at Azure.Storage.Blobs.BlobClient.StagedUploadInternal(Stream content, BlobUploadOptions options, Boolean async, CancellationToken cancellationToken)
at Azure.Storage.Blobs.BlobClient.UploadAsync(Stream content) at Program.<<Main>$>g__ProcessAsync|0_0() in C:\Users\[redacted]\Documents\devops\working with blob storage module\az204-blob\Program.cs:line 51
at Program.<Main>$(String[] args) in C:\Users\[redacted]\Documents\devops\working with blob storage module\az204-blob\Program.cs:line 7
I copied the code from the tutorial and tried to run it following the given instructions. It starts out fine but throws an error when trying to upload the new file to the blob. I expected the new file to be written to the blob, and the remaining instructions to be executed.
I was able to repro the issue locally with the same code and after doing below changes I was able to upload it successfully:
Old Code:
// Open the file and upload its data
using (FileStream uploadFileStream = File.OpenWrite(localFilePath))
{
await blobClient.UploadAsync(uploadFileStream);
uploadFileStream.Close();
}
// Modified Code
FileStream uploadFileStream = File.Open(localFilePath, FileMode.Open);
blobClient.Upload(uploadFileStream);
uploadFileStream.Close();
Let me know if that helps !

xamarin for android throws NullReferenceException when trying to request location updates

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>();

Xamarin Android Httppost Request

I am trying to make a post call to my web Api which is on local host. But I am getting following error
result = {System.Net.WebException: The remote server returned an
error: (415) Unsupported Media Type. at
System.Net.HttpWebRequest.EndGetResponse (System.IAsyncResult
asyncResult) [0x0005e] in
/Users/builder/data/lanes/3511/f4db8a57/source/mono/mcs/class/System/Sy...
Can anyone help? Below is my code:
private void click (Object sender, EventArgs e)
{
UserInfo user = new UserInfo(1, "hellohello#gmail.com", "helloss");
String data = JsonConvert.SerializeObject(user);
WebClient wc = new WebClient();
wc.UploadStringAsync(new Uri("http://192.168.206.2:155/api/register"), data);
wc.UploadStringCompleted += Wc_UploadStringCompleted;
}
private void Wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
var result = e.Error;
}
So far, the Server only get's a string from you and can't know if, it is json, xml or something else. You just have to tell him.
You can to this on a WebClient via:
wc.Add("Content-Type", "aplication/json");
If you are using the HttpClient you have to set ist via the Content property:
request.Content = new StringContent("json", Encoding.UTF8, "application/json");
The HTTP specification states:
415 Unsupported Media Type
The 415 (Unsupported Media Type) status code indicates that the origin server is refusing to service the request because the payload is in a format not supported by the target resource for this method. The format problem might be due to the request's indicated Content- Type or Content-Encoding, or as a result of inspecting the data directly.
It seems your server is having troubles with the format... try adding the headers with .Add("Accept", "aplication/json");

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