How to I read in the body content in .net core 3.0? - .net-core-3.0

I am upgrading my solution from .net core 2.2 to 3.0, and I want to log the request data/body in the "proper" way. I am reading a lot that using the PipeReader is preferred to reading directly from the stream.
Previous to .net core 3.0, we used streams and the EnableRewind() method. It looked something like this:
HttpRequest.EnableRewind();
HttpRequest.Body.Position = 0;
var sr = new StreamReader(HttpRequest.Body);
var myData = sr.ReadToEnd();
HttpRequest.Body.Position = 0;
return myData;
I would like to understand how to properly use the PipeReader. Eg. what code is necessary to read in the HttpRequest body into a string? I see there is a ReadAsync() and TryRead() methods, but I'm not sure how to properly use these. I also see there is an AsStream() method which I've been able to use on the stream as I previously had (but without rewind).
I'd love to see any examples on how to do this, because it seems as though working with the pipe requires a great deal of pointer references. Lastly, if I work with the PipeReader.AsStream(), do I need to worry about rewind?

Here's how I do it:
HttpRequest.EnableBuffering();
using var streamReader = new StreamReader(HttpRequest.Body);
string data = await streamReader.ReadToEndAsync();
EnableBuffering() replaces EnableRewind().

Related

Accessing OpenWeather data elements

I am building a simple Visual Basic program, for personal use only, that shows some basic weather forecast information. I did some looking around and decided that OpenWeather is my best option for getting the data.
I wrote a simple program, using the NewtonSoft JSON framework, which includes:
Dim myWeatherData As HttpClient
response = Await myWeatherData.GetAsync(useUrl)
responseBody = Await response.Content.ReadAsStringAsync()
myJSON = JObject.Parse(responseBody)
This code fine as I was able to see the JSON data using JsonConvert.SerializeObject. My question is simply this: Using the above code, would you please show me how to get inside of myJSON to access, for example, the predicted temperature two days from now? Thanks.

How to encode URLs in Dart?

I'm trying to port some code from Python to Dart (for a Flutter application). However, I'm having a bit of trouble encoding URLs. I'm trying to do the equivalent of parsedData = urllib.parse.quote(STR_DATA). The closest I've gotten is with the Uri Dart class, with:
parsedData = Uri(queryParameters: STR_DATA);
parsedData = Uri.encodeComponent(parsedData.toString());
This gets close to what I'm trying to get but not quite. The result I get using Python is something like this (side note: it's only encoding after the period):
ig_sig_key_version=4&signed_body=efbcf4ac8577da5eb43f33f369cda4248dba52a407e88a565038b53933737bba.%7B%22phone_id%22%3A%20%22ee79227a-cf89-41c8-9598-d0c6f3931fa4%22%2C%20%22_csrftoken%22%3A%20%22BB1PRXVV1y6FgU0Rfmcda3jJG5eVFSPd%22%2C%20%22username%22%3A%20%22USERNAME%22%2C%20%22guid%22%3A%20%22c668814c-a1e9-487c-97f0-8491b2c07c1c%22%2C%20%22device_id%22%3A%20%22android-7eb57ab90e1e2c3e%22%2C%20%22password%22%3A%20%22PASSWORD%22%2C%20%22login_attempt_count%22%3A%20%220%22%7D
While with Dart, I get something like this:
ig_sig_key_version=4&signed_body=d1c26c132b536b3f4ffdd7f5c0524503e48216fb7f638b5f4cab65d74a9834de.%3Fphone_id%3D112626ab-1946-4ad0-bc63-b233f57033f9%26_csrftoken%3DhiPh0jSvjd0eP2dP4VUr83t3htYF7xci%26username%3DUSERNAME%26guid%3D999d2242-f52a-4044-96d9-2245c6757fbc%26device_id%3Dandroid-5daff5c3029f414c%26password%3DPASSWORD%26login_attempt_count%3D0
By the way, the reason why I need this to encode in the same way is because otherwise my HTTP request returns 400. Anyway, any help is appreciated; thank you in advance.
OTHER SIDE NOTE: I think this is what's causing my request to be rejected but I don't know, I haven't done a lot of web stuff. If you think it might be something else, feel free to correct me.
You are doing too much.
In this case, you only need to do: parsedData = Uri.encodeComponent(STR_DATA); to get the same result as the Python code.
Use Dart Uri Class
var uri = 'http://example.com/path/to/page?name=ferret john';
var encoded = Uri.encodeFull(uri);
assert(encoded == 'http://example.com/path/to/page?name=ferret%20john');
var decoded = Uri.decodeFull(encoded);
assert(uri == decoded);

Extracting Windows File Properties with http link

I am working on this problem and the proposed solution works for me.
However, now I need to make this work in my actual application which is an AWS Beanstalk .NET web application. My beanstalk application knows the url source of the picture. Knowing the url, I can get a stream and process the file (by creating a byte array and even a Bitmap object).
However, it seems that to get the file properties as mentioned above (such as the camera type or painting application that created the file), I really need a local file because that is the expected input argument.
This is a problem for me. I know the http link, I know the bytes but I have no such thing as a file path.
How can I solve this? I need the windows file properties.
If I understood you correctly, you want to read image metadata from a URL without saving it to a file first, i.e. directly from the Internet.
Here is one way that works for me:
string demoImageUrl = "https://raw.githubusercontent.com/ianare/exif-samples/master/jpg/Canon_40D.jpg";
byte[] imgData = null;
using (var wc = new WebClient())
{
imgData = wc.DownloadData(demoImageUrl);
}
using (var sr = new MemoryStream(imgData, false))
{
BitmapSource image = BitmapFrame.Create(sr);
BitmapMetadata md = (BitmapMetadata)image.Metadata;
string comment = md.Comment;
string title = md.Title;
string dateTaken = md.DateTaken;
}
You need to add references to PresentationCore and WindowsBase assemblies and also include the following namespace:
using System.Windows.Media.Imaging;

What is basic difference between UploadData and DownloadString in asp.net webclient?

I am new to webclient.
I have seen some examples to POST data to a server. I am worrying which one to be used over other. Can any one please tell me what to use when?
UploadData:
system.net.webclient.uploaddata(uri, byte[]);
DownloadString:
WebClient client = new WebClient();
var result = client.DownloadString(someurl);
Suggestions welcome..!
the basic difference between both - Uploaddata method can be used to retrieve data based on provided inputs from specified URI(address of service) while DownloadString can be used to retrieve data without sending any inputs parameters.

Write XML stream to an xml file

I know this must be a rookie question, but how do i accomplish that?
Because from what i have seen here : http://msdn.microsoft.com/en-us/library/system.io.streamwriter or at XMLWriter is not helping me, because i just want to save all, not write specific lines.
Basically i have an httpRequest that returns back an XML response. I am getting that in a stream, and from that i want to save it to an xml file, for later use.
Part of the code:
HttpWebResponse response = (HttpWebResponse)httpRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
XDocument blabla = XDocument.Parse(responseString);
// Here is where the saving to a file should occur
streamResponse.Close();
streamRead.Close();
Why do you need to parse the file? In .NET 4 you can just write it directly to disk using a file stream like this:
using (var fileStream = File.Create("file.xml"))
{
streamResponse.CopyTo(fileStream);
}
If you are using an earlier version of the .NET framework, you can use the method described here to copy data from one stream to another.
Have a look at this:
http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.save.aspx
Should help you get the job done!
As you already have the XML response as a string, I think what you need is to use a StreamWriter class to write the response string straight to a file.
There is an MSDN example of its use here: How to: Write Text to a File

Resources