Non buffered output in ASP.NET Core 6 - c#

I am trying to achieve a simple streaming (non buffered output) using really basic ASP.NET Core 6 app.
The following simple code should output the hello world text to the client and then close the connection (even by adding the document IHttpResponseBodyFeature option) :
app.MapGet("/a", async (ctx) =>
{
var gg = ctx.Features.Get<Microsoft.AspNetCore.Http.Features.IHttpResponseBodyFeature>()!;
gg.DisableBuffering();
await ctx.Response.Body.WriteAsync(Encoding.UTF8.GetBytes("Hello, World!"));
await ctx.Response.Body.FlushAsync();
await Task.Delay(2000);
});
This is of course a simple example of a behavior I am trying to achieve.
Simple curl request to the app can show that the hello world text is reaching to the client only after the 2 seconds wait.
On the .NET Framework the following code works as expected:
Response.Clear();
Response.Buffer = false;
Response.BufferOutput = false;
Response.Output.WriteLine("Hello World!");
Response.Output.Flush();
System.Threading.Tasks.Task.Delay(2000).Wait();
Response.End();
Simple curl request shows the "hello world" text shown immediately and after 2 seconds the connection get closed.
Thanks in advance.

After few more tries and searches i came upon the following issue on github :
https://github.com/dotnet/aspnetcore/issues/26565
Using the code there i managed to came up with a simple way for working non buffered output (also works on app.MapGet as shown on the question):
HttpContext.Response.StatusCode = 200;
await using var bodyStream = HttpContext.Response.BodyWriter.AsStream();
await HttpContext.Response.StartAsync();
for (var i = 0; i < 3; i++)
{
await bodyStream.WriteAsync(Encoding.UTF8.GetBytes(Convert.ToBase64String(new byte[128 * 1])));
await bodyStream.FlushAsync();
await Task.Delay(2000);
}
await HttpContext.Response.CompleteAsync();
return Ok();
My app had some middle-ware which made debugging worse, disabling it made everything much simpler on my app/scenario.
Thanks for the comments , i hope this helps.

Related

How do I fix a "System.Net.Http.HttpRequestException: TypeError: Failed to fetch" in Blazor WebAssembly?

The code below, runs for about fifteen seconds on the "dataFs = await _Http.GetStreamAsync(BODIST_DATA_HTTPNAME)" line before failing with a "System.Net.Http.HttpRequestException: TypeError: Failed to fetch".
public async Task<Double> EffectivePipCount(HttpClient _Http, Int64 _PositionId)
{
Double retVal = Double.NaN;
using (Stream locnFs = await _Http.GetStreamAsync(BODIST_LOCATION_FILENAME)
, dataFs = await _Http.GetStreamAsync(BODIST_DATA_FILENAME))
{
retVal = EffectivePipCount(_PositionId, locnFs, dataFs);
}
return retVal;
}
The file in question is about four gigabytes in size.
This is in Blazor WebAssembly app, so I want an Http equivalent to a FileStream, where I can seek and then read the hundreds of bytes I want. Small files in the same directory work fine.
If the problem is a timeout because of the file size, what should I be using instead of HttpClient.GetStreamAsync()?
My best guess is that GetStreamAsync() pulls down the whole file. Using http.GetFromJsonAsync solves the problem.

Showing Images using XF ImagePicker Without Putting Image in Resources

In Xamarin.Forms prerelease they have released a media picker: https://learn.microsoft.com/en-us/xamarin/essentials/media-picker?tabs=android
This is obviously a great addition and the fact that you don't have to use any 3rd party-library is great!
I'm creating an event management app - in the app the user can select an image for the event and be able to see it.
Here is my code:
public async void OnSelectPhotoCommand()
{
var photo = await MediaPicker.PickPhotoAsync();
await LoadPhotoAsync(photo);
}
async Task LoadPhotoAsync(FileResult photo)
{
var newFile = Path.Combine(FileSystem.CacheDirectory, photo.FileName);
using (var stream = await photo.OpenReadAsync())
using (var newStream = File.OpenWrite(newFile)) { await stream.CopyToAsync(newStream); }
ImagePath = newFile;
}
The problem is the image is not showing or appearing whatsoever - I've tried to modify my code and debug it but I am unable to locate the source of the problem.
I want the user to be actually able to see the image - but I am unsure on how to do that using the MediaPicker without putting it in the Android Resources folder?
Thank you,
tommy
From the xamarin essentials documentation be sure to be running it from the UI Thread.
InvokeOnMainThread ( () => {
OnSelectPhotoCommand();
});

Windows Phone. Result of ReadToEndAsync() corrupted by app deactivation

I've got some troubles with StreamReader.ReadToEndAsync();
//some get response code ...
using (var response = getResponseTask.Result)
{
using (var responseStream = response.GetResponseStream())
{
using (var responseStreamReader = new StreamReader(responseStream))
{
var readToEndTask = responseStreamReader.ReadToEndAsync();
var responseResult = await readToEndTask;
//and some json parse code here
}
}
}
So, when I press the Home button on the device (whatever phone or emulator) while ReadToEndAsync task is in process, result string is not full length on app reactivation... i.e. it's ending just cut out without any exceptions or warning.
As result, I can't parse my json-data to object.
How can I fix it or avoid this situation ?
Thanks everybody in advance!
For this, you need to run your code as a background task. Background tasks will run even your app is deactivated. You can refer : https://learn.microsoft.com/en-us/windows/uwp/launch-resume/support-your-app-with-background-tasks to learn background tasks.
There are two types of background tasks, in process & out process.

Windows Phone 8.1 MediaCapture's FocusAsync does not work

I'm implementing a Windows Phone 8.1 App with a QR Code reader. I use ZXing.NET to analyze the taken image and try to parse the QR. To increase it's efficiency I also set autofocus to the camera. It works pretty well at the first start, but not with the second try (f.e. after suspend - resume or restart capturing). As I tested, the FocusAsync method doesn't return sometimes and blocks everything.
What happens here? What could be the problem?
Here is my current code.
Focus
var focusSettings = new Windows.Media.Devices.FocusSettings();
focusSettings.AutoFocusRange = Windows.Media.Devices.AutoFocusRange.Normal;
focusSettings.Mode = Windows.Media.Devices.FocusMode.Auto;
CaptureManager.VideoDeviceController.FocusControl.Configure(focusSettings);
MainProcess
... Initialization ...
ImageEncodingProperties imaggeProperties = ImageEncodingProperties.CreateJpeg();
imaggeProperties.Width = ViewModel.ImageWidth;
imaggeProperties.Height = ViewModel.ImageHeight;
InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream();
LoggingAdapter.Instance.WriteDebugLog("Scanning is in progress. " + Environment.CurrentManagedThreadId);
await CaptureManager.VideoDeviceController.FocusControl.FocusAsync();
await CaptureManager.CapturePhotoToStreamAsync(imaggeProperties, memoryStream);
LoggingAdapter.Instance.WriteDebugLog("Photo captured.");
var bcReader = new BarcodeReader();
... Processing the barcode ...
Cleaning
if (CaptureManager != null)
{
if (InProgress)
{
InProgress = false;
await CaptureManager.StopPreviewAsync();
}
CaptureManager.Dispose();
Capture.Source = null;
}
Thanks for advance!
I succeeded to implement a working solution. I set the the WaitForFocus to false in the FocusSettings and it seems to be working fine, also with suspending or cancelling.

Assistance with Oauth2 authentication to use with DropBox

I am building a Windows c# app that needs to upload files to DropBox. Basically I have everything I need for my app(app secret and app key), but I need to have the client tokens saved to my sql DB for future use. According to Dropbox I am unable to save user login info which is good, but finding a good lib is getting tough.I have tried many different DropBox based libraries but run across the following issues:
SharpBox: seems easy enough to use, but need some kind of deserializer to save the client key and client secret anywhere.
OAuth2 Authorizer: Not enough documentation that I can find, in order for me to actually implement this.
DropNet: This is one that looked promising. It's async and looked good, but again I can't find an example of how to perform the auth function and save the variables to a file/DB/Reg/ or anything.
DropBox.API: This is the method that I currently use and it's working. Problem is it's not Async and requires .NET 4.5. I was ok with all the downs but lately found that's it's very touchy about different versions of JSON and other libraries.
I was hoping someone could give me some assistance in getting any of the above OAUTH libs actually working, Just to get the 3 legged auth process working.
UPDATE::
ok so i am going to include some of the code that I am using at the moment, that uses dropbox.api:
// Get Oauth Token
private static OAuthToken GetAccessToken()
{
string consumerKey = "mykey";
string consumerSecret = "myseceret";
var oauth = new OAuth();
var requestToken = oauth.GetRequestToken(new Uri(DropboxRestApi.BaseUri), consumerKey, consumerSecret);
var authorizeUri = oauth.GetAuthorizeUri(new Uri(DropboxRestApi.AuthorizeBaseUri), requestToken);
Process.Start(authorizeUri.AbsoluteUri);
MessageBox.Show("Once Registration is completed Click OK", "Confirmation");
return oauth.GetAccessToken(new Uri(DropboxRestApi.BaseUri), consumerKey, consumerSecret, requestToken);
}
// Complete Oauth function and write to file
private void button5_Click(object sender, EventArgs e)
{
DialogResult result1 = MessageBox.Show("Please register for dropbox before continuing with authentication. The authorization process will take 1 minute to complete. During that time the backup utility window will be unresponsive. Click yes if you are ready to begin the authorization. HAVE YOU REGISTERED FOR DROPBOX YET?", "DO YOU HAVE A DROPBOX ACCOUNT?", MessageBoxButtons.YesNo);
if (result1 == DialogResult.Yes)
{
try
{
u_w.Enabled = false;
var accesstoken = GetAccessToken();
StringBuilder newFile = new StringBuilder();
string temptoken = "";
string tempsecret = "";
string tempprovider = "";
string tempstatus = "";
string[] file = System.IO.File.ReadAllLines(#"C:\cfg\andro_backup.ini");
foreach (string line in file)
{
if (line.Contains("dbkey:"))
{
temptoken = line.Replace("dbkey:", "dbkey:" + accesstoken.Token);
newFile.Append(temptoken + "\r\n");
continue;
}
if (line.Contains("dbsecret:"))
{
tempsecret = line.Replace("dbsecret:", "dbsecret:" + accesstoken.Secret);
newFile.Append(tempsecret + "\r\n");
continue;
}
if (line.Contains("Provider:"))
{
tempprovider = line.Replace("Provider:", "Provider:DropBox");
newFile.Append(tempprovider + "\r\n");
continue;
}
if (line.Contains("Status:"))
{
tempstatus = line.Replace("Status:", "Status:Connected");
newFile.Append(tempstatus + "\r\n");
continue;
}
newFile.Append(line + "\r\n");
}
System.IO.File.WriteAllText(#"C:\cfg\andro_backup.ini", newFile.ToString());
MessageBox.Show("Completed Backup Provider Setup", "Provider Setup Complete");
Configuration.Reload();
The Above works at the moment and I can upload, download files. The issue is it's not Async and I would like to attempt to stay within the .NET 4.0 if possible, this code requires 4.5
Trying to do the same thing with dropnet, I am unable to get it to work at all even using the examples he has given on the page located here https://github.com/dkarzon/DropNet.
I attempted to look at the demos he has on there as well , but they explaing having the user login everytime to perform any functions, where I need the app to be authorized so it can do it's deeds when it needs to. As far as the code I am using for drop net, I literally just copied and pasted what he had there, just to even see if I can get it to connect and still no go.
If you are using DropNet similar to the examples all you need to do is save the return object from the GetAccessToken method. That returns an instance of a UserLogin object which has the Token and secret on it. Or if you are using the async methods for it then the callback parameter.
Checkout the sample here:
https://github.com/dkarzon/DropNet/blob/master/DropNet.Samples/DropNet.Samples.WP7/MainPage.xaml.cs#L69
Post the code you are using for it so I can give you a better explanation for it.

Categories

Resources