OWIN ReadAsAync does not return - owin

I have a solution with a WebAPI and a Test Winforms app. I am trying to access the Wepapi from the Winform.
HttpResponseMessage response = await client.GetAsync("api/serialnumbers");
if (response.IsSuccessStatusCode)
{
var x = await response.Content.ReadAsAsync<SerialNumber>(); //This does not return
button1.Text = snlist[0].ComputerName;
}
The client.GetAsync call can be followed to the server and I see it in the Get then the StatusCode is OK and the ReadAsSync gets called but I don't know where it goes on the server and it does not return.
I am able to browse to the /api/serialnumbers url and get data.

This worked for me
snlist = response.Content.ReadAsAsync>().Result;

You most likely have a call to Wait or Result further up your call stack. This will cause a deadlock that I describe on my blog.
The proper solution is to remove every call to Wait or Result with await.

Related

Firebase cloud functions throws timeout exception but standalone works fine

I am trying to call a third party API using my Firebase cloud functions. I have billing enabled and all my other function are working fine.
However, I have one method that throws Timeout exception when it tries to call third API. The interesting thing is, when I run the same method from a standalone nodeJS file, it works fine. But when I deploy it on Firebase cloud or start the function locally, it shows timeout error.
Following is my function:
exports.fetchDemo = functions.https.onRequest(async (req, response) =>
{
var res = {};
res.started = true;
await myMethod();
res.ended = true;
response.status(200).json({ data: res });
});
async function myMethod() {
var url = 'my third party URL';
console.log('Line 1');
const res = await fetch(url);
console.log('Line 2'); // never prints when run with cloud functions
var data = await res.text();
console.log(`Line 3: ${data}`);
}
Just now I also noticed, when I hit the same URL in the browser it gives the following exception. It means, it works only with standalone node.
<errorDTO>
<code>INTERNAL_SERVER_ERROR</code>
<uid>c0bb83ab-233c-4fe4-9a9e-3f10063e129d</uid>
</errorDTO>
Any help will be appreciated...
It turned out that one of my colleague wrote a new method with the name fetch. I was not aware about it. So when my method was calling to the fetch method, it was actually calling his method he wrote down the file. I just took git update and did not notice he wrote this method.

Handling asynchronous calls in bot framework

We are using a Bot configured via Microsoft Bot Framework written in NodeJS. During the execution flow of a dialog, we present the user with certain information and then some server processing is done via SOAP and the result of this SOAP response would be needed before the next waterfall method starts.
In short, we have the below piece of code:
bot.dialog('changedefaultlogingroupDialog', [
async function (session, args, next) {
wargs[0] = 'change default login group';
var sourceFile = require('./fetchSharePointUserDetail.js');
session.privateConversationData.userSharepointEmail = global.DEVSharepointBotRequestorEmailID;
console.log('\nsession.privateConversationData.userSharepointEmail:'+session.privateConversationData.userSharepointEmail);
var get_SharepointUserId_args = ['get Sharepoint user id', session.privateConversationData.userSharepointEmail];
sourceFile.login(get_SharepointUserId_args);
setTimeout(() => {
global.DEVSharepointTeamcenterUserID = require('./fetchSharePointUserDetail.js').DEVTeamcenterUserId;
console.log('\nglobal.DEVSharepointTeamcenterUserID:'+global.DEVSharepointTeamcenterUserID+'\n');
console.log("Request has been made from directline channel by user id <"+global.DEVSharepointTeamcenterUserID+">");
session.privateConversationData.requestor_id = global.DEVSharepointTeamcenterUserID;
session.privateConversationData.create_ques = session.message.text;
next();
}, 3000);
},
async function (session, result, next) {
Do processing here that is dependent on session.privateConversationData.requestor_id
}
As you can see from the above example, the setTimeout method is waiting for 3 seconds to have the SOAP response retrieved. While this worked in DEV landscape, it failed in our PRD landscape. So I wanted to know what is the more appropriate way of doing this. Is 'await' a correct case for using in this context?. I am asking this as this is in BOT Framework Context and not sure if that has any side affects.
Please suggest.
Thanks,
Pavan.
Await is the correct way to look at this.
I'm not familiar with the bot framework, but I'm guessing that they asynchronous part of your code happens during the login.
await sourceFile.login(get_SharepointUserId_args);
Would be where the asynchronous call is. It could also be in the fetchSharePointUserDetail.js
There is likely a better way to load that file as a module so that you are calling functions on a returned object, rather than returning variables from some code that is obviously executing something.

RestSharp POST not returning anything from Azure environment, but does locally

I've made this type of call dozens of times, but for some reason this isn't working in my testing environment in Azure, but works on my localhost just fine. The result never returns from my service, not even a timeout error or "0" response, nothing. What could I be missing when calling an api endpoint? No errors in my logs either.
The only way I'm able to get a response is if I remove the Timeout = 2700000, which in that case it returns "0" response. But my call is taking more than a few minutes, so without the Timeout set, it will always return a "0" response.
UPDATE: I've also tried using await/async calls, no luck either.
UPDATE: I switched from restsharp and used a Httpclient call instead, and still same results. So I don't even think its a restsharp issue alone.
var appSettings = ConfigurationManager.AppSettings;
var restClient = new RestClient(appSettings["Url"]);
var request = new RestRequest("api/Sync")
{
Method = Method.POST,
Timeout = 2700000,
RequestFormat = DataFormat.Json
};
request.AddHeader("authUser", appSettings["username"]);
request.AddHeader("authPass", appSettings["password"]);
request.AddHeader("Content-Type", "application/json");
var body = JsonConvert.SerializeObject(deserializeItem);
request.AddParameter("application/json; charset=utf-8", body, ParameterType.RequestBody);
var result = restClient.Execute(request);
var response = JsonConvert.DeserializeObject<ResultObj>(result.Content);
So in order to fix this issue, I had to put:
System.Net.ServicePointManager.SetTcpKeepAlive(true, 180000, 60000);
The connection between my web job and service was timing out due to idle inactivity.

node js session replaces if request comes at same time

I have built a node.js application and it is working as expected. The only problem that i am facing now is when the code receives same request from two different session then the result(outcome) is changing. That is First request is getting the the result of second request and second request result is same.
my code :
app.get('/userpage',function(req,res){
if(req.session.user){
var a = req.session.user; //stored in redis server.
var b = req.session.userid //stored in redis server
//call function(req,res,a,b);
}
}
//Function
exports.functionname = function(req,res,a,b){
//do something
result = a+b;
return result;
}
the result of first request is replacing with the second session result. And if i refresh page again individually i get the correct result for both the sessions. This only happens if i put the same request and same time. Please help!
Note: I am storing the session details in Redis server. nopt inserting anytthing to my db
i figured it by myself, it was happening because of missing callbacks. Node js needs to have callback in order to wait for the output

Choosing strategy to handle response from asynchronous API call

There is a web application which does not have any own database, but communicates with remote through API. Performing a call to API takes some time and we do it asynchronously. The responsiveness of the application must be high from the user point of view.
Let's assume that the user is changing some data. To store the data we need to make a call. We start showing the new data right after making the call. But what can we do if the response of the call is unsuccessful? We need to restore the old values and show some kind of warning to the user. But the user may leave the page, where data were changed and see completely different page. What are general patterns to handle such situations?
If you are using .Net 4.5 you can do this using async/await. If your web client that you are calling provides an asynchronous API that returns a Task you can simply await the call inside a try/catch block. The await will cause the method to return immediately so the user will continue to observe the old data while it is executing. Once the we client call completes the method "resumes" after the await and you can update your data.
If the web client call causes an exception, the method will resume in the catch block and you can display an error to the user.
public async Task CallAPI()
{
try
{
var client = ...
await client.CallAPI();
}
catch(Exception ex)
{
// show warning message
}
}
If your web client does not provide an asynchronous API you can achieve the equivalent with the Task Parallel Library.
public void CallAPI1()
{
Task.Factory.StartNew( () =>
{
var client = ...
client.CallAPI();
}).ContinueWith( t =>
{
if(t.Exception != null)
{
// display error
}
else
{
// update web page with
}
},
null,
CancellationToken.None, TaskScheduler.FromCurrentSynchronizationContext());
}
This article has more information on async/await. And this one has some of the best practices to follow.

Resources