Using geolocalisation with windows phone, await error - asynchronous

I'm trying to get the current location of an user, but the code show me an error...
// try get user location
Geolocator geo = new Windows.Devices.Geolocation.Geolocator();
geo.DesiredAccuracyInMeters = 10;
try {
Geoposition position = await geo.GetGeopositionAsync();
} catch (Exception e) { }
My problem is that the compiler show me an error at await geo.GetGeopositionAsync();
The 'await' operator can only be used when its containing method or lambda expression is marked with the 'async' modifier.
But from what I have seen, this is the same code as shown by Microsoft
I already restart VS12 and the pc (which is a VM but still) and the error is still here...
What's going wrong ?
I also try this and still get the same error:
Geoposition position = await geo.GetGeopositionAsync().asTask<Geoposition>();

You need to mark your method with async:
void **async** themethod()
{
// try get user location
Geolocator geo = new Windows.Devices.Geolocation.Geolocator();
geo.DesiredAccuracyInMeters = 10;
try {
Geoposition position = await geo.GetGeopositionAsync();
} catch (Exception e) { }
}

Related

How to resolve problem to Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript

[HttpGet("vulnerability")]
public IActionResult vulnerability(string input)
{
object content = 0;
try
{
content = new Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript(input).EvaluateAsync().Result;
}
catch (Exception)
{
content = "";
}
return View("Example", new { vuln = content });
}
I'm going to implement a "code injection" vulnerability in .net core.
The vulnerable configuration takes input to input and tries to execute it as an eval.
Yes)
Input: 1+1
Result screen: 2
by the way
Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript(input).EvaluateAsync().Result;
An error occurs in the portion. Occurrence Error - CS0712
EvaluateAsync()
Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript(input).EvaluateAsync().Result;
An error occurs in the portion. CS0712
EvaluateAsync() Occurrence Error - CS1501
How can I solve this?
I tried to solve the problem by referring to the official document.
Your code should like below:
[HttpGet("vulnerability")]
public async Task<IActionResult> vulnerability(string input)
{
object content = 0;
try
{
content = await CSharpScript.EvaluateAsync(input);
}
catch (Exception)
{
content = "";
}
return Ok(new { vuln = content });
}
And the test result:

Missing method calling puppeteer LaunchAsync

When I try to use puppeteersharp in AX I get a error
"Method not found: 'Void Microsoft.Extensions.Logging.LoggerExtensions.LogError(Microsoft.Extensions.Logging.ILogger, System.Exception, System.String, System.Object[])'."
I have a custom DLL added to my AX project where I create a PDF but I call this method from AX. The DLL alone is working fine since I tested it outside of my AX project yet when I call it from AX the error occours. I tried different verions but there is always a problem with Microsoft.Extensions.Logging DLL.
EDIT!
As I looked at code the method I seek is in Microsoft.Extensions.Logging.Abstractions. Since in AX i found that the DLL version is 1.1.2 and has no 4th method for LogError where you can add Exception value. Is there any safe way to update DLL in AX365 onprem?
//X++ code
class ConvertXMLtoPDF
{
public static void main(Args _args)
{
try
{
helper.PuppeteerPDF();
}
catch(Exception::CLRError)
{
System.Exception ex = CLRInterop::getLastException();
info(ex.ToString());
}
}}
C# code
using PuppeteerSharp;
using PuppeteerSharp.Media;
using Microsoft.Extensions.Logging;
public async void PuppeteerPDF()
{
string path = #"C:\Temp\test\tes2t.pdf";
string save = #"C:\Temp\test\test.html";
var options = new LaunchOptions
{
Headless = true,
ExecutablePath = "C:\\Program Files\\Google\\Chrome\\Application\\Chrome.exe"
};
try
{
using (var browser = await Puppeteer.LaunchAsync(options)) // <--- here the error occours
using (var page = await browser.NewPageAsync())
{
await page.GoToAsync(save);
var result = await page.GetContentAsync();
await page.PdfAsync(path, new PdfOptions
{
Format = PaperFormat.A4,
DisplayHeaderFooter = true,
Scale = (decimal)0.5,
PrintBackground = true,
});
await page.DisposeAsync();
await browser.DisposeAsync();
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
logger.LogError(ex, "test");
logger.LogInformation(ex, "test");
}
}

How to timeout Firebase Task in Unity

This issue is driving me nuts :)
Assuming that I have a simple async Task:
async Task AddPoints()
{
await usersDbReference.Child(currentUser).Child("Score").SetValueAsync(newScore).ContinueWith(task =>
{
if(task.IsFaulted || task.IsCanceled)
{
Debug.Log("Couldn't complete task");
}
});
}
What is the simplest way to add the timeout, for example 10 seconds, after which I will show pop up to the user to check his/her internet connection?
Thank you in advance!
EDIT:
I tried below code but it makes the unity crash:
int timeout = 1000;
var task = SomeOperationAsync();
if (await Task.WhenAny(task, Task.Delay(timeout)) == task) {
// task completed within timeout
} else {
// timeout logic
}
I'm using Unity (api compatibility level .Net Standard 2.0, I assume that crash is because of this?)
What I want to achieve:
In case the user doesn't have the internet connection I want to either timeout the task and cancel it or just cancel it after finding out there is no internet connection.
EDIT:
I modified the code. So I have a simple task with cancel token:
async Task CheckTask(CancellationToken csToken)
{
string firstChild = "user";
string secondChild = "testuser";
await FirebaseDatabase.DefaultInstance.RootReference.Child(firstChild).Child(secondChild).GetValueAsync().ContinueWith(task =>
{
if(task.IsFaulted || task.IsCanceled)
{
Debug.Log("Task was canceled");
}
});
}
Then I'm calling it from async void:
public async void FirebaseLogin()
{
bool taskDidntComplete = false;
Debug.Log("Started task");
CancellationTokenSource cs = new CancellationTokenSource();
try
{
var loginTask = CheckTask(cs.Token);
if(loginTask.IsCanceled)
{
Debug.Log("Canceled");
}
if (await Task.WhenAny(loginTask, Task.Delay(10000)) == loginTask)
{
taskDidntComplete = false;
}
else
{
taskDidntComplete = true;
Debug.Log(taskDidntComplete);
cs.Cancel();
throw new TimeoutException();
}
}
catch (Exception e)
{
Debug.Log(e);
}
finally
{
}
}
And while everything works fine and it shows the exception, it doesn't cancel the task. Would be very grateful if someone could tell me what I'm doing wrong.
EDIT2: Works perfect in Unity, doesnt work on Android... Anyone can help? I'm desperate now haha
public async void FirebaseLogin()
{
Debug.Log("Started task");
CancellationTokenSource cs = new CancellationTokenSource();
try
{
var loginTask = CheckTask(cs.Token);
if(loginTask.IsCanceled)
{
Debug.Log("Canceled");
netTestCheck.text = "Canceled";
}
if (await Task.WhenAny(loginTask, Task.Delay(10000)) == loginTask)
{
//netTestCheck.text = "Completed";
}
else
{
netTestCheck.text = "Failed";
cs.Cancel(false);
//throw new TimeoutException();
}
cs.Token.ThrowIfCancellationRequested();
}
catch (Exception e)
{
netTestCheck.text = "Failed2";
Debug.Log(e);
}
finally
{
}
It would help if you could share the exception or stack trace of the crash (integrating Crashlytics could help if you're already in the Firebase ecosystem).
Although I can't spy anything that looks particularly bad in your sample code, if the actual Task fails for whatever reason (say you turn on airplane mode to test, and a suitable exception is raised before your timeout) an exception will get raised there that you aren't handling.
I'd suggest putting a try/catch around your block like:
try {
int timeout = 1000;
var task = SomeOperationAsync();
if (await Task.WhenAny(task, Task.Delay(timeout)) == task) {
// task completed within timeout
} else {
// timeout logic
}
} catch (Exception e) {
Debug.LogError($"{e} occurred!");
}
It's likely to be a DatabaseException, but I'd check first before you get more specific than Exception.
Let me know if that helps!
--Patrick
It unfortunately won't work on Android because app will keep on calling to Firebase. Fortunately found the way around :D

Xamarin.Forms failing to use EvoHtmlToPdfclient in order to convert html string to a pdf file

I'm using Xamarin.Forms and I am trying to convert an html string to a pdf file using EvoPdfConverter, but the problem is that when I try to do so, on the line htmlToPdfConverter.ConvertHtmlToFile(htmlData, "", myDir.ToString()); in the code snippet below, the app just freezes and does nothing, seems like it wants to connect to the given IP, but it can't, however I don't get any errors or exceptions! not even catch!! does anybody know what I should do to resolve this issue? and here is my code for this:
public void ConvertHtmlToPfd(string htmlData)
{
ServerSocket s = new ServerSocket(0);
HtmlToPdfConverter htmlToPdfConverter = new
HtmlToPdfConverter(GetLocalIPAddress(),(uint)s.LocalPort);
htmlToPdfConverter.TriggeringMode = TriggeringMode.Auto;
htmlToPdfConverter.PdfDocumentOptions.CompressCrossReference = true;
htmlToPdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Best;
if (ContextCompat.CheckSelfPermission(Android.App.Application.Context, Manifest.Permission.WriteExternalStorage) != Permission.Granted)
{
ActivityCompat.RequestPermissions((Android.App.Activity)Android.App.Application.Context, new String[] { Manifest.Permission.WriteExternalStorage }, 1);
}
if (ContextCompat.CheckSelfPermission(Android.App.Application.Context, Manifest.Permission.ReadExternalStorage) != Permission.Granted)
{
ActivityCompat.RequestPermissions((Android.App.Activity)Android.App.Application.Context, new String[] { Manifest.Permission.ReadExternalStorage }, 1);
}
try
{
// create the HTML to PDF converter object
if (Android.OS.Environment.IsExternalStorageEmulated)
{
root = Android.OS.Environment.ExternalStorageDirectory.ToString();
}
htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c=";
htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait;
Java.IO.File myDir = new Java.IO.File(root + "/Reports");
try
{
myDir.Mkdir();
}
catch (Exception e)
{
string message = e.Message;
}
Java.IO.File file = new Java.IO.File(myDir, filename);
if (file.Exists()) file.Delete();
htmlToPdfConverter.ConvertHtmlToFile(htmlData, "", myDir.ToString());
}
catch (Exception ex)
{
string message = ex.Message;
}
}
Could you try to set a base URL to ConvertHtmlToFile call as the second parameter? You passed an empty string. That helps to resolve the relative URLs found in HTML to full URLs. The converter might have delays when trying to retrieve content from invalid resources URLs.

interesting service behaviour in silverlight

I have a Silverlight project which takes some encrypted string thru its Service Reference: DataService (service which is done in an ASP.NET project).
The method from TransactionServices.cs to get the encrypted string is:
public void GetEncryptedString(string original)
{
DataService.DataServiceClient dataSvc = WebServiceHelper.Create();
dataSvc.GetEncryptedStringCompleted += new EventHandler<SpendAnalyzer.DataService.GetEncryptedStringCompletedEventArgs>(dataSvc_GetEncryptedStringCompleted);
dataSvc.GetEncryptedStringAsync(original);
}
On completing, put the result in encodedString var (which is initialized with an empty value):
void dataSvc_GetEncryptedStringCompleted(object sender, SpendAnalyzer.DataService.GetEncryptedStringCompletedEventArgs e)
{
if (e.Error == null)
{
try
{
if (e.Result == null) return;
this.encodedString = e.Result;
}
catch (Exception ex)
{
Logger.Error("TransactionService.cs: dataSvc_GetEncryptedStringCompleted: {0} - {1}",
ex.Message, ex.StackTrace);
MessageBox.Show(ex.ToString());
}
}
}
Now I want to get the encoded string from my MainPage.xaml like:
TransactionService ts = new TransactionService();
ts.GetEncryptedString(url);
Console.WriteLine(ts.encodedString);
I do not uderstand why ts.encodedString is empty. When I do the debug I see that it actually prints out empty and AFTER that it goes to the void dataSvc_GetEncryptedStringCompleted to take the result and fill it.
Can you point me what I've done wrong? Is there a way to wait for the encodedString to be fetched and only after that to continue?
Thanks a lot.
When you call the ts.GetEncryptedString(url); you just started async operation. And therefor the value you are accessing is will be set only in the callback method.
But you access it before the value is modified by the callback.
The solution which I am using will looks similar to folowing:
Redefine the GetEncryptedString method signature.
public void GetEncryptedString(string original, Action callback)
{
DataService.DataServiceClient dataSvc = WebServiceHelper.Create();
dataSvc.GetEncryptedStringCompleted += (o,e) =>
{
dataSvc_GetEncryptedStringCompleted(o,e);
callback();
}
dataSvc.GetEncryptedStringAsync(original);
}
Call it like this:
ts.GetEncryptedString(url, OtherLogicDependantOnResult);
where
OtherLogicDependantOnResult is
void OtherLogicDependantOnResult()
{
//... Code
}

Resources