I have gone through several SO and forums - spending over several hours attempting the several answers/comments I found on these sites. I still haven't been able to resolve the issue.
Note 1: It worked on my laptop before - all further developments were made on a separate branch. Neither the original branch nor the new branch works. It works on my team mate's laptop and we still haven't been able to figure out the issue.
Note 2: I have tried re-cloning the original branch in a separate directory and that fails too. Again, we couldnt reproduce the issue on my team mate's system.
Environment - Windows 10, Visual Studio 2019, WPF App (.NET Framework 4.8), C# 8
public class SomeClient
{
private readonly string _host;
private readonly HttpClient _client;
public SomeClient(HttpClient client, string host)
{
_host = host;
_client = client;
}
public async Task<string> GetResponse(string request)
{
HttpContent content = new StringContent(request, Encoding.UTF8, "application/xml");
HttpResponseMessage body = await _client.PostAsync(_host, content);
return await body.Content.ReadAsStringAsync().ConfigureAwait(false);
}
}
Calling Code (Test Method)
[TestClass]
public class SomeClientShould
{
[TestMethod]
public async Task ReturnResponse()
{
string request = "";
SomeClient client = new SomeClient(new HttpClient(), #"http:\\localhost:9888\");
string response = await client.GetResponse(request);
Assert.AreEqual("<RESPONSE>Server is Running</RESPONSE>", response);
}
}
Here I am not making any request, sending an empty string which should respond with the string shown in the Assert (passes on my team mate's system, Postman on my system works also).
I have tried various combo's of ConfigureAwait(false), also there is no blocking code - its async all the way. Even a simple test method shown above exits after the PostAsync line without executing the next line. Try-Catch is not catching any exception and Im having a breakdown.
So dummy me, first of all made a mistake with the host uri - the slashes had to be the other way round in the test project - "http://localhost:9888/". So the tests run now.
Next issue, between my projects I had a version mismatch of the Microsoft.Bcl.AsyncInterfaces library.
Somehow one project had the latest version referenced but the other didn't? Perhaps the issue came about during merging of the original branch - before my teammate and I created our respective dev branches for further development. Anyway it works now.
Related
I have a problem with azure function only when I publish.
the code run not in order, all the functions run at the same time.
ex :
var logger = context.GetLogger(nameof(MibProposalRequest));
logger.Log(LogLevel.Warning, $"Début de la fonction : MibProposalRequest {DateTime.UtcNow}");
try
{
var getStringResponse = await this.GetStringAsync(req, logger).ConfigureAwait(false);
if (getStringResponse.Error != null)
{
return new HttpResponseMessage()
{
StatusCode = getStringResponse.Error.StatusCode,
ReasonPhrase = getStringResponse.Error.Message
};
}
else
{
var requestBody = getStringResponse.Response.ToString();
var deserializeRequestBodyResponse = await this.DeserializeRequestBodyAsync(requestBody, logger).ConfigureAwait(false);
if (deserializeRequestBodyResponse.Error != null)
{
return new HttpResponseMessage()
{
StatusCode = deserializeRequestBodyResponse.Error.StatusCode,
ReasonPhrase = deserializeRequestBodyResponse.Error.Message
};
}
In this example I need to get the response of the function GETStringAsync and after go to the function : DeserializeRequestBodyAsync.
If I run the azure function in local (debug) it's all ok, everything it's in order.
First log the function start.
After Get the string
end deserializeObject.
But when I publish the function and I test it, when I'm loocking at the log in portal.azure.
All the function run not in good order.
So sometimes I get an error from deserializeObject function because no string to deserialize.
But its suppose to do the GetStringAsync function first.
Why this append?
Image of the log
as you can see the function start log is not the first to show up why ?
looks like all the code run completely not in order.
should be like this :
Log of vs debug
Everything is good each functions run in good order (so no problems)
Why this append only when the function is published ??
Ps: I tried to run the function not async but nothing change.
PS2: I tried to put all the code in the same function (Run) nothing changed.
PS3: I tried to put task.wait nothing changed.
I need help please 2 days I'm on this.
https://azure.microsoft.com/en-us/updates/general-availability-azure-functions-supports-net-5-in-production/?cdn=disable
From my experience this was a pain to get to work with Azure Functions on .NET 5. Either roll back to 3.1 or wait till 11/9/2021 for .NET 6 to release out of preview. .NEt 6 preview is allowed on Azure for testing.
Are you running .NET 5 in Azure in isolated mode? See link above.
"To support .NET 5, Azure Functions introduces a new isolated process model that runs .NET function apps in a separate worker process outside the Azure Functions host runtime."
I just found a solution in the code:
List<ProposalIdModel> list = (List<ProposalIdModel>)deserializeGuidsAsyncResponse.Response ?? new List<ProposalIdModel>();
Like this the list while never be null.
But it's wired in visual studio in debug no problem, but when I publish sometime the list get null.
So problem solved.
I also update to netCore6.
I've raised a bug item against the C# Bot Builder project on GitHub but to be honest I can't really get to the bottom of whether this is a bug with the framework or a sporadic problem originating on the Facebook side.
We have been building the bot for a couple of months and have been using in development and staging exvironments extensively and have not seen this issue once.
So we go live with our first customer and boom. This issue starts occuring.
Value cannot be null. Parameter name: invalid activity-missing From.Id
And also:
Value cannot be null. Parameter name: invalid activity-missing
Conversation.Id
The chats that produced this issue were started by users coming to the bot via the messenger web page and the Web Chat Plugin.
The users in both instances had used the "Get Started" button thus opting in to the chat. This opting in provides the bot with access to the users basic profile information.
Understandably this is pretty odd and I have been entirely unable to reproduce this issue in any testing in any of our environments (we have Dev, Staging and Live).
Has anyone else seen a similar issue?
What did you do to work around it?
At the moment since I cannot reproduce it anywhere I can't really close the bug or even have a vague level of confidence in it not happening again.
If your bot is designed with the Activity Handler, as demonstrated in the Samples-work-in-progress branch, you can add some code to the controller to log the entire Request.Body:
[Route("api/messages")]
[ApiController]
public class BotController : ControllerBase
{
private readonly IBotFrameworkHttpAdapter Adapter;
private readonly IBot Bot;
public BotController(IBotFrameworkHttpAdapter adapter, IBot bot)
{
Adapter = adapter;
Bot = bot;
}
[HttpPost]
public async Task PostAsync()
{
Request.EnableBuffering();
using (var buffer = new MemoryStream())
{
await Request.Body.CopyToAsync(buffer);
buffer.Position = 0L;
using (var bodyReader = new JsonTextReader(new StreamReader(buffer, Encoding.UTF8)))
{
Debug.Print(BotMessageSerializer.Deserialize(bodyReader).ToString());
buffer.Position = 0L;
}
}
Request.Body.Position = 0;
await Adapter.ProcessAsync(Request, Response, Bot);
}
}
This should provide more information on what type of message is being sent to the bot. My guess is that it has something to do with a Facebook Messenger specific web hook you have subscribed to. For instance, I don't think 'message_echoes' are currently sent to the bot with a .From or conversation.Id. However, we have recently modified our Connector Service to include these: the release should be within the next few weeks.
I have made a very simple Web API in ASP.NET and deployed it locally with IIS, but I cannot seem to use it. I've tried using it with HTTPClient in Xamarin, as well as in Java, but something in the ASP.NET project is not allowing me to access it. I am not sure if the problem is because it's deployed locally, though. Here are the errors I receive in Java and .NET:
Java:
javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
.NET:
at System.Net.Http.HttpClientHandler+<SendAsync>d__64.MoveNext () [0x00478] in <996a681f30a44cd685a4da54e11956e2>:0
Calling Method:
public async Task<List<School>> GetSchools()
{
try
{
var response = await client.GetAsync("schools");
string responseJson = await response.Content.ReadAsStringAsync();
List<School> schools = JsonConvert.DeserializeObject<List<School>>(responseJson);
return schools;
}
catch (HttpRequestException e)
{
return null;
}
}
The issue was caused by the program using an SSL Certificate. To fix, I just went into the projects properties and unchecked the setting 'Enable SSL'.
I have been able to get the Microsoft Translator API to work with creating a console project. I could only find examples with using console projects.
When trying to get the Translator API working within a controller I am not having any luck. I am using the same code.
Do I need to add some other type of reference to get the Translator to work with in MVC?
public async Task<string> GetAuthenticationToken(string key)
{
string endpoint = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "xxxxxxxxxxxxxxx501b7b1ce");
var response = await client.PostAsync(endpoint, null);
var token = await response.Content.ReadAsStringAsync();
return token;
}
}
Error Message
Is there any particular reason you have to create the console application first and then run it as such?
Instead of running the executable from your MVC project, I would recommend calling the TranslatorAsync() function instead.
My guess would be that the process.Start() and process.Close() calls are killing the process before it has a chance to do anything. However, without more specifics on how the function is failing, it's hard to give a better answer.
I had to change
TranslateAsync(productTest, getUserName).Wait;
to
await TranslateAsync(productTest, getUserName);
It’s working now.
I'm currently following a tutorial on how to show Twitter feeds with LINQ to XML in C#. However, seeing as Microsoft has replaced WebClient with HTTPClient, I'm unsure how to proceed on my quest of integrating this into my Windows 8 application.
The tutorial: http://www.codeproject.com/Articles/117614/How-to-query-twitter-public-status-using-LINQ-to-X
The thing is that I'm "halfway" used to DownloadStringCompleted, which I believe is not in the HTTPClient api. So after searching for a while on the async/await functionality, I mixed some of my knowledge together with some tutorials and snippets I found, but what I ended up with would not work:
public async Task<XElement> GetXmlAsync()
{
var client = new HttpClient();
var response = await client.GetAsync("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=VladimirPutin");
var text = response.Content.ReadAsStringAsync();
return XElement.Parse(text.Result);
XElement xmlTweets = XElement.Parse(text.Result);
listboxTweetsSecond.ItemsSource = from tweet in xmlTweets.Descendants("status")
select new UserTweet
{
UserImageSrc = tweet.Element("user").Element("profile_image_url").Value,
UserMessage = tweet.Element("text").Value,
UserName = tweet.Element("user").Element("screen_name").Value
};
}
(Yeah, the Twitter username is just a placeholder)
I do not need an entire code as an answer, but I'd love it if someone could point out where I should go from here, as well as what I should do in general, as this (of course) does not work (as in, it does not show anything when I run it/debug mode).
Comment out the line
return XElement.Parse(text.Result);
and it should probably work.
Having done that (i.e. you are no longer returning an XElement) you can probably change the method signature top return just a task.
public async Task GetXmlAsync()
{
// method body
}