I am having trouble with a demo from msdn
The demo
On the method updateUserName:
public static async Task updateUserName(TextBlock userName, Boolean signIn)
{
try
{
// Open Live Connect SDK client.
LiveAuthClient LCAuth = new LiveAuthClient();
LiveLoginResult LCLoginResult = await LCAuth.InitializeAsync();
try
{
//this is never reached
LiveLoginResult loginResult = null;
if (signIn)
......
the code hangs at ht InitialuzeAsync() method and never enters the try statement. Can someone who has used the live SDK please tell me what migh be wrong? The code is a direct copy-paste from the demo and the live SDK was installed via NuGet on VS2012.
I predict that you are calling Task.Wait or Task<T>.Result somewhere further up your call stack. As I describe on my blog, you are causing a deadlock because the await is attempting to resume on the UI thread.
The correct solution is to use await "all the way", which is one of the best practices I describe in my article. If you have a situation where you think you "can't" use await, then take a look at my async/OOP blog series, which describes various code patterns for async code, most notably constructors and properties.
Seems you have to associate your app with the store to use this feature, or else it hangs. After associating it, everything started working.
Related
I have an Oracle database that I am accessing through ODP.NET
This is my demo code
public static async Task<Field[][]> ReadAsync(string ExtractSql)
{
var connStr = ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString;
List<Field[]> ret = new List<Field[]>();
using (OracleConnection conn = new OracleConnection(connStr))
{
await conn.OpenAsync();
}
return ret.ToArray();
}
This code does not behave as async, the UI is completely blocked for seconds.
If I simply replace
await Task.Delay(10000); //conn.OpenAsync();
all works fine as expected.
Can I conclude that this is a bug in ODP.NET, is there a github repo or where can I report it or am I missing something trivial in C# async?
Is there anyone else using .NET for Oracle and experiencing a similar issue for async methods?
Please note
Of course I've added the code inside to open the command and read the data and the issue persists, here I'm showing the minimal amount of code that is sufficient to detect the problem. E.g. I have a firewall that can block the connection and in that case it times out, therefore the only "open" command can be enough to make the app stuck, if the db part is not async.
Thank you to #madreflection for the comments. I'm really happy to delete my answer and accept an answer from him, as I kindly asked.
Anyway, now it is clear by looking at Visual Studio intellisense that those async methods are not there but they are symply inherited from the generic System.Data.Common.DbConnection.
I should have also understood it at the first method that is not returning a Task or a Task<bool>, i.e. from the following line
OracleDataReader DR = (OracleDataReader) await cmd.ExecuteReaderAsync();
where I was forced to add an unexpected cast (now I understand why).
I'm going to wrap the API in a Task.Run because I can't block my UI.
See below the screenshot with the mouse over the OpenAsync.
From the doc you can read
This is the asynchronous version of Open(). Providers should override with an appropriate implementation
The default implementation invokes the synchronous Open() call and returns a completed task.
My person opinion is that the default implementation is doing the wrong/misleading thing, I would have rather preferred an exception "not implemented" thrown instead.
I am trying to implement Google SSO in my C# web application. It seemed to be pretty straightforward. Based on this tutorial, Google does its magic in the web browser to get an Id_Token JWT. I pass the token is passed it to my web service for validation and use it to match it to a user in the application.
Although I am not sure if my approach with the server-side Google API is correct yet, my big hangup is trying to figure out how to work with the async call in the Google API to see what I get back.
My code is pretty simple using the Google.Apis.Auth namespace:
public async Task<GoogleJsonWebSignature.Payload> wfValidateAsync(string pId_Token)
{
GoogleJsonWebSignature.Payload Sig = await GoogleJsonWebSignature.ValidateAsync(pId_Token, null, false);
return Sig;
}
Although brand new to this async/await paradigm, I do have some experience in AngularJS / NodeJS promises / callbacks. My challenge is that it seems async methods can only be called by other async methods all the way back up the call-stack. I think it means ending the service call before the async response finishes and the service can act on the result.
Also, for creating unit tests, putting async into the [TestMethod] method makes it completely disappear from the test explorer. I'm not sure how to test/debug this conundrum.
Thanks in advance to anyone who can help me screw my head back on straight with this.
Although brand new to this async/await paradigm, I do have some experience in AngularJS / NodeJS promises / callbacks.
But not use Typescript, right?
My challenge is that it seems async methods can only be called by other async methods all the way back up the call-stack.
They should. Bad things can happen if you don't.
I think it means ending the service call before the async response finishes and the service can act on the result.
No! The compiler generates a state machine for methods with the async modifier and the await keyword means "go do something else and I'll come back here when I'm done".
Also, for creating unit tests, putting async into the [TestMethod] method makes it completely disappear from the test explorer. I'm not sure how to test/debug this conundrum.
You're probably making your test methods async void. They should be async Task in order for the test engine to know when the test is done.
Have a look at Stephen Cleary's blog. He has lots of content on async-await.
Paulo, Thank you!!
I was able to get this working with your advice on the last part about the test method. I had to change this:
//THIS TEST METHOD DOESN'T SHOW IN THE TEST EXPLORER
[TestMethod]
public async void AuthenticateGoogle()
{
string lToken = "[JWT TOKEN HERE]";
wfUser lUser = new wfUser(_wfContext);
var lAuthenticateResult = await lUser.wfAuthenticateGoogle(lToken);
Assert.IsTrue(lAuthenticateResult, "JWT Token Validated");
}
To this:
//THIS TEST METHOD SHOWS IN THE TEST EXPLORER
[TestMethod]
public async Task AuthenticateGoogle()
{
string lToken = "[JWT TOKEN HERE]";
wfUser lUser = new wfUser(_wfContext);
var lAuthenticateResult = await lUser.wfAuthenticateGoogle(lToken);
Assert.IsTrue(lAuthenticateResult, "JWT Token Validated");
}
NOW -- as an additional gotcha that was hanging me up, this will also cause a unit test to disappear from the test explorer, which I found out through lazy copy/pasting a non-test method's definition and mindlessly just adding a return when the build output told me I needed to return a value.
//THIS TEST METHOD DOESN'T SHOW IN THE TEST EXPLORER DUE TO RETURN VALUE
[TestMethod]
public async Task<bool> AuthenticateGoogle()
{
string lToken = "[JWT TOKEN HERE]";
wfUser lUser = new wfUser(_wfContext);
var lAuthenticateResult = await lUser.wfAuthenticateGoogle(lToken);
Assert.IsTrue(lAuthenticateResult, "JWT Token Validated");
return true;
}
In addition to the excellent blog you shared, this article from MSDN Magazine entitled Async Programming : Unit Testing Asynchronous Code helped me get my brain around it too.
What was hanging me up with all of this was mixing synchronous and async methods which, to your point, was not working well. The code seemed to skip the debug points I had set after the await calls as if it never ran them or, if it did run them, ran them somewhere I could not see and couldn't log to the debugger.
It was one of those terrible moments late on a Friday night where a developer starts to question both competence and sanity! :)
Thanks again for the help!
p.s. I incorrectly typed Angular JS in my question and meant Angular 4...and I am using TypeScript there. Some day I'll stop incorrectly referring the newer versions of Angular as AngularJS.
My challenge is that it seems async methods can only be called by other async methods all the way back up the call-stack.
It's not entirely true. You can use async method in sync methods. Of course you are losing most of the 'async' effect, but sometimes you have to. As async methods returs tasks you have some options.
When Task is returning result, any reference to t.Result will block execution till it's known. Another option is to use Task.Wait(preferably with timeout). For example code to validate google jwt token:
public bool ValidateGoogleToken(string token)
{
try
{
if(GoogleJsonWebSignature.ValidateAsync(token).Wait(1000))
return true; //success
//timeout exceeded
}
catch (Exception e)
{
//tampered token
}
return false;
}
I have a tiny bit of code which in 'normal debug' just hangs executing "var folder =..."
async Task<StorageFolder> GetAssetsFolderAsync()
{
var folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(#"Assets");
return folder;
}
I placed two breakpoints as in...
If I break at the first I can Debug.StepOver to the line "return folder". If I use debug.Run instead in goes away and doesn't hit the next breakpoint. The method is called from MainPage_Loaded. Any idea how I can correct this problem. And the weirder thin is that it used to work without a problem and I haven't changed THOSE lines.ie lots of others)
After a long long search I found the answer from Mr Skeet and Mr Cleary. I was blocking the UI thread.
It is explained in far greater detail here:
Call to await GetFileAsync() never returns and app hangs in WinRT app
I don't think I would have thought of it. It was fixed with:
public async static Task<bool> StaticInitializeAsync()
{
recordingsFolder = await getRecordingsFolderAsync();
AssetsFolder = await Statics.InstallationFolder.GetFolderAsync(#"Assets");
defaultWavFile = await AssetsFolder.GetFileAsync("Default.wav");
return true;
}
I believe you get an exception which visual studio handles for you silently.
Try opening the exception settings and make sure it brakes on any exception.
Debug -> Windows -> Exception settings
Mark all the CLR exceptions
EDIT:
Also try to catch for AggregateException, these can wrap the true exception when dealing with TPL.
I've recently run into a use case where the "Async" suffix recommended by the .NET Task-based Asynchronous Pattern (TAP) conflicts with what's already in existence.
I'm dealing with System.Management.Automation.Runspaces.Runspace during the course of attempting PowerShell remoting to execute cmdlets as part of my app.
Ignoring the questions that arise around whether it's best practice to knock-up a remoting session each time you want to run a cmdlet (for an enterprise scale application this might be a lot) or to create a connection and attempt to maintain it during the app's lifetime (with reconnection logic)...
My application is based on TAP which proliferates from the WebApi2 controller all the way down to the backend, what I'm trying to do is asynchronously open a Runspace connection - but noticed that there's already an OpenAsync method which isn't awaitable and returns void - which is like some weird mash-up between async void (for event handlers), void (non-async) and the Async suffix.
I'm using Stephen Cleary's Nito.AsyncEx nuget package to provide me with a AsyncAutoResetEvent which I can asynchronously await before attempting connection/reconnection).
The question is: should I care about the fact that my code really isn't going to be properly "async" in using either Open or OpenAsync on the Runspace?
If I should care - what's the best practice in this situation? It doesn't look like Microsoft have released updated DLLs which provide awaitable Open methods for the Runspace. Strangely despite MS giving information on how to use these libraries, they've added the caveat on the nuget site:
Versions 6.1.7601.* are unofficial packages for .Net 4.0 and are not
supported by Microsoft.
There also seems to be this DLL-esque package on nuget from Microsoft, aagggghh!
Currently my plan is something akin to this:
public async Task<Result> StartAsync()
{
if (!IsConnected)
{
try
{
await _asyncRunspaceLock.WaitAsync();
if (!IsConnected)
{
var protocol = IsHttpsEnabled ? "https" : "http";
var serverUrl = $"{protocol}://{Fqdn}/OcsPowershell";
var uri = new Uri(serverUrl);
var connectionInfo = new WSManConnectionInfo(uri, ShelUri, PSCredential.Empty)
{
SkipRevocationCheck = true,
};
var runspace = runspaceFactory.CreateRunspace(connectionInfo);
runspace.OpenAsync();
}
}
catch (Exception ex)
{
// TODO: Handle logging the 3rd party exception at the lowest level.
return Result.Fail(ex.Message);
}
finally
{
_asyncRunspaceLock.Set();
}
}
return Result.Ok();
}
It's a work in progress, I guess the same issue crops up around the RunspaceFactory's CreateRunspace static method which isn't async (at least it isn't named with the Async suffix).
Any helpful advice or experience would be greatly appreciated.
Thanks
peteski
From the documentation:
If you're adding a TAP method to a class that already contains that method name with the Async suffix, use the suffix TaskAsync instead. For example, if the class already has a GetAsync method, use the name GetTaskAsync.
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