i recently started working with Xamarin and my level of noob its very high right now, i will resume my problem.
I am developing an app that can reach a WebService to send and import data from DB, right now i am currently working on a login page and i have a method so I can check if the user exits in the data base, when i added the service reference in Xamarin all the methods turned into async, and because of that i need to use tasks.
So, i implemented the Tasks and it worked perfectly but i had one problem i couldnĀ“t send the response of the server back, i did some research and found that tasks methods dont have returns and for that i could use Task < TResult>, and i implemented in this way:
CheckUser Method in Service
serclient = new Service.WebService1SoapClient()
public async Task<bool> CheckUser(string UserName)
{
var resp = await serClient.CheckUserAsync(UserName);
bool result = resp.Body.CheckUserResult;
return result;
}
gesTab.CheckUser Is the method to check the database.
public bool CheckUser(string username)
{
bool e = gestTab.CheckUser(username);
return e;
}
When the program is runnig just stops in the first line of that function and i cant understand why.
I already tried it by using pointers by keeping getting that pointers must only be used in unsafe context.
If i cant do it this way, what can i do for return the data?
Thank you all.
You must await the method which retrieves data from db or etc. like this ,
public async Task<bool> CheckUser(string username)
{
bool e = await gestTab.CheckUser(username);
return e;
}
Since your method making starting async request but not awaiting response, your application crashes unexpectedly.
Related
I'm a beginner and recently tried to get started with FireSharp, and even got some data transfered:
This was my first Code to send data to the server:
public static class Client
{
static IFirebaseClient client;
static IFirebaseConfig config = new FirebaseConfig
{
AuthSecret = "MyAuthSecret",
BasePath = "MyBasePath"
};
public static bool Start()
{
client = new FirebaseClient(config);
if (client != null)
{
return true;
} else {
return false;
}
}
public static void Send(Data data)
{
SetResponse response = await client.SetAsync("Testpath", data);
}
But at the line SetResponse response = await client.SetAsync("Testpath", data);, I got the following error message:
The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
I was still able to send data, simply by reducing the line to client.SetAsync("Testpath", data);. I knew it wasn't ideal, since I didn't got a response that way, but it worked!
The real problem was, that I didn't managed to come up with such a workaround for FirebaseResponse response = await client.GetAsync("Testpath");. That way I'm currently unable to get data from the server.
Does anyone have any idea on what the problem could be or how to fix it?
My ideas were:
Maybe it has something to do with the fact that I put all this in a static class.
Maybe the FireSharp Libary is broken in the current version.
Maybe I could manually mark the methods as async, since thats whats the error-message saying.
Or I could manually change it's return type, as the error-message says.
Maybe I understood the whole "await" and "async" thing wrong.
The manual says, "FirebaseClient uses Newtonsoft.Json by default. Maybe that could have anything to do with it.
But I havent tried any of them, since I don't know how. I have no idea whether it is possible and would make sence to change the code of the libary, or whatever the error-message means with "change the return type". I watched a tutorial and looked at the manual, but couldn't find any information about this problem.
I would really appreciate any help since I wasn't able to find any information about this problem on the Internet so far.
Your Send method must be async
public static async Task Send(Data data)
I am implementing facial recognition functionality. I can upload a person and an image but when I try to send image for comparison the DetectAsync method fails with no error message. I am not sure if the problem lies in the method (I have successfully implemented it in other projects) or in the way I am sending the webcam/image through javascript or something else.
I am using javascript to detect a face on webcam and take a picture. The picture is sent to converted to a stream and send to DetectAsync(stream). It's in a try-catch block but I don't get an exception, it just returns to the UI where it seems frozen and I can't reload the page or navigate to another page. In the Quickwatch window, it I type faceServiceClient.DetectAsync(stream) and then force execution I get the following:
Exception: null
Id: 643
Status: WaitingForActivation
results: null (not yet computed)
a few others but these seemed like the most relevent
I expect to get either an array of FaceIDs (GUIDS). One per face in the image. Or an error message. After I get GUIDS I can try to find a match against faces in my personGroup. If I find a match I return the username to my UI. I have gotten this to work in an MVC app. This is an ASP.NET app.
code:
public async Task<string> DoFacialRecognition(string image)
{
string response = "";
FaceServiceClient faceServiceClient = new FaceServiceClient(subscriptionKey);
try
{
var imageToSend = ConvertBase64ToImage(image.Substring(22));
Stream stream = ConvertToStream(imageToSend, ImageFormat.Png);
var faces = await faceServiceClient.DetectAsync(stream, true, false);
var faceIds = faces.Select(face => face.FaceId).ToArray();
}
....
}
The issue was with the thread or threads... Im not sure of the technicality or terms but I will explain as best I can. This was an aspx page making an ajax call to an async method. This was the behavior I was expecting:
aspx-> ajax-> async method A-> async method B-> back to A-> back to ajax-> ajax deals with response.
what was actually happening:
aspx-> ajax-> async method A-> async method B-> back to ajax or aspx.
But ajax is waiting for a response from method A so it is ignoring response from method B (probably not even in the right format anyway). The page is still 'active' but when user tries to do anything the server doesn't respond because method A is still waiting for a response from B and is locking the code.
If you know more about threads and async calls feel free to correct my understanding!
to resolve:
The info I needed to resolve was provided by Stephen Cleary in this post: How to call asynchronous method from synchronous method in C#?.
you need to 'hide' the async method from the ajax call. To do this Stephen has a nuget packages called Nito.AsyncEx.
the sequence then looks like:
aspx-> ajax-> method A-> async method B-> back to A-> back to ajax-> ajax deals with response.
Note that method A is no longer async.
and code looks like this:
using Nito.AsyncEx;
[WebMethod]
public static string CheckImage(string image)
{
var result = AsyncContext.Run(() => MyAsyncMethod(image));
return result;
}
private static async Task<string> MyAsyncMethod(string image)
{
//do async stuff
}
I have what I think is a fairly basic flow in an asychronous web api controller. The code looks like the following:
public async Task<IHttpActionResult> Put([FromBody] ObjectType myObject)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
this.callbasicMethod();
myObject = await myRepository.UpdateDB(myObject);
await myRepository.DeleteSomeStuff(myObject.someProperty);
var table = Helper.CreateDataTable(myObject.anotherProperty);
await myRepository.InsertSomeStuff(table);
returnOk(myObject);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
The problem is that none of the database calls (importantly the update call) ever execute. If I put a break point in this method around the update call, everything works just fine. It is like some sort of race condition is happening or something. Please let me know if you have an idea on how to fix this issue or what I am doing wrong.
Also, please let me know if you need any clarification, I had to obviously obfuscate the code to protect the intellectual property of the company I work for. If it helps any, the methods that are being called are implemented asynchronously themselves calling into asynchronous dapper methods to communicate with the database.
I finally found a work around, but not a true answer to why. Basically the two database calls that were being called were to delete some data from the table and then after that had been done add some data to the same table. I wrote one stored procedure to handle this and then one method within my data layer of my application and now everything is working.
I'm the new one in C# and UWP development and I'm trying to create an app for win-mobile 10.
One of the tasks of this app is reading SMS messages.
On one of my xaml pages I use this code:
public sealed partial class TileSettings : Page
{
public TileSettings()
{
this.InitializeComponent();
GetMessages();
}
public async Task GetMessages()
{
ChatMessageStore store = await ChatMessageManager.RequestStoreAsync();
}
}
Problem appears when I call the ChatMessageManager.RequestStoreAsync() function. The function is called but never returns any value and never exits from this function.
I have not a special permissions of Microsoft
as a developer. Can I use this function?
I'm trying to use Google and Stackoverflow search and found code like this with RequestStoreAsync() function, but it seems that no one ever faced this particular problem
May be I have logical error in the code and don't know how to use async functions in c# :)
Waiting for your comments about this behavior.
Best Regards.
You have to need Company account. Please check it out below URL what are the benefits
https://msdn.microsoft.com/windows/uwp/packaging/app-capability-declarations
I found a problem.
There is UnauthorizedAccessException in this function.
I coudn't see this exception cause call of this task is incorrect.
I try use this code:
public TileSettings()
{
this.InitializeComponent();
cts = new CancellationTokenSource();
Task.Run(() => GetMessages(), cts.Token);
}
private async void GetMessages()
{
ChatMessageStore store;
store = await ChatMessageManager.RequestStoreAsync();
var List = store.GetMessageReader();
}
and caught this exception.
Do I need a special permissions to use this function to get sms messages?
I am trying to load a document out of RavenDb via a WebAPI call. When I open an async IDocumentSession and call LoadAsync, I get no exception or result, and the thread exits instantly with no error code.
I was able to bypass all the structure of my API and reproduce the error.
Here is the code that will not work:
public IHttpActionResult GetMyObject(long id)
{
try
{
var session = RavenDbStoreHolderSingleton.Store.OpenAsyncSession();
var myObject= session.LoadAsync<MyObject>("MyObject/1").Result;
return Ok(myObject);
}
catch (Exception e)
{
return InternalServerError(e);
}
}
I simply hard coded the object's Id to 1 for testing, but calling the function for an object that doesn't exist (such as "MyObject/1") has the same result.
However, this code works:
public async Task<IHttpActionResult> GetMyObject(long id)
{
try
{
var session = RavenDbStoreHolderSingleton.Store.OpenAsyncSession();
var myObject= await session.LoadAsync<MyObject>("MyObject/1");
return Ok(myObject);
}
catch (Exception e)
{
return InternalServerError(e);
}
}
Things I tried/fiddled with:
Changing the exceptions that are caught in debugging
Carefully monitoring Raven Studio to see if I could find any problems (I didn't, but I'm not sure I was looking in the right places)
Running the API without the debugger attached to see if the error occurred or if something showed up in Raven Studio (no changes)
So I guess I have stumbled on a "fix", but can someone explain why one of these would fail in such an odd way while the other one would work perfectly fine?
In the real application, the API call did not have the async/await pair, but the code that was making the call was actually using async/await.
Here is the repository class that was failing which caused me to look into this issue:
public async Task<MyObject> Load(string id)
{
return await _session.LoadAsync<MyObject>(id);
}
The first part that is failing is as per design, for ASP.Net async call, you are blocking the Synchronization context, when you call the Result on a Task returned and same Synchronization context is required for call to return the data. Check out the following link by Stephen Cleary, where the same mechanism is explained in detail.
Second part works since that is correct way of using it and it's not getting into the deadlock anymore. First part can only work if you are using the Console application, which doesn't have a synchronization context to block, even other UI like winforms will have a similar issue and need to use the use the Second part of the code