AspNet Core Razor View with PuppeteerSharp - asp.net-core

Can we use PuppeteerSharp with Razor View. I want to send the HTML from Razor View inside AspNetCore app and get the output as PDF. Any references or code samples would be helpful

You can inject the HTML using SetContentAsync and then call PdfAsync
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
Headless = false,
}))
using (var page = await browser.NewPageAsync())
{
await page.SetContentAsync("Hello World");
await page.PdfAsync("test.pdf");
}

According to github you can generate PDF file like this
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
var browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
Headless = false
});
var page = await browser.NewPageAsync();
await page.GoToAsync("http://localhost/your/page");
Stream pdfStream = await page.PdfStreamAsync();

Related

Send image in attachments by URL in Circuit JS SDK

I'm using a Circuit JS SDK and want to send message with attached image. I found on documentation that I should set the item.attachments to File[] object. But how can I do it if I have only image URL (like https://abc.cde/fgh.png)?
To be able to post an image in a conversation, the image needs to be uploaded to Circuit which is done internally in the addTextItem API as you already found out. And yes this API takes an array of File objects.
You will need to download the image via XMLHttpRequest as blob and then construct a File object.
const xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.open('GET',<url of image> , true);
xhr.onreadystatechange = async () => {
if (xhr.readyState == xhr.DONE) {
const file = new File([xhr.response], 'image.jpg', { lastModified: Date.now() });
const item = await client.addTextItem(convId.value, {
attachments: [file]
});
}
};
xhr.send();
Here is a jsbin https://output.jsbin.com/sumarub

How Do I get API Response Status Code Only with Blazor?

I need your help guys. I'm developing a front-end with Blazor which sends request to ASP.Net Core.
I have the following code which gets an API response, in this case it returns the entire body of the response. What I'm trying to get here is the status code of the response only, example (200).
await Http.SendJsonAsync(HttpMethod.Post, "https://da3.mock.pstmn.io/api/register", CurrentUser);
var response = await Http.GetStringAsync("/api/register");
Console.WriteLine(response);
Use the other GetAsync method.
//var response = await Http.GetStringAsync("/api/register");
//Console.WriteLine(response);
var response = await Http.GetAsync("/api/register");
Console.WriteLine(response.StatusCode); // also see response.IsSuccessStatusCode
For POST method you could use SendAsync, you need to use PMC to install Newtonsoft.Json package firstly:
var requestMessage = new HttpRequestMessage()
{
Method = new HttpMethod("POST"),
RequestUri = new Uri("https://localhost:5001/api/default"),
Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(CurrentUser))
};
requestMessage.Content.Headers.ContentType =
new System.Net.Http.Headers.MediaTypeHeaderValue(
"application/json");
var result = await Http.SendAsync(requestMessage);
var responseStatusCode = result.StatusCode;
For GET method,what Henk Holterman has suggested (use Http.GetAsync) works well.
Refer to
https://learn.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-3.0#httpclient-and-httprequestmessage-with-fetch-api-request-options

Xamarin.Forms Cookie/User Persistence and ASP.NET Core Authentication/Cookies

Hopefully I'm not misunderstanding something fundamental about ASP.NET Authentication, but here's what I'm trying to accomplish (and failing doing such):
I have a Xamarin.Forms app that needs to be able to go after ASP.NET web services. When I run the App itself, it works fine. The ASP.NET side of it uses Cookie Authentication and the App is capable of getting the Cookie from the Cookie Container -- and then serializing/storing it into secure storage:
For example:
var baseUri = new Uri(url);
baseUri = new Uri($"{baseUri.Scheme}://{baseUri.Host}");
var cookieContainer = new CookieContainer();
/*
authenticationCookie is stored locally and de/serialized via Json from SecureStorage:
var cookie = SecureStorage.GetAsync(AuthenticationCookieKey).Result;
if (!string.IsNullOrEmpty(cookie))
{
authenticationCookie = JsonConvert.DeserializeObject<Cookie>(cookie);
}
*/
cookieContainer.Add(authenticationCookie);
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
{
using (var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(content) })
{
using (var client = new HttpClient(handler))
{
return client.SendAsync(request).Result;
}
}
}
When I make a Login, I do the following on "success":
SetAuthenticationCookie(cookieContainer.GetCookies(baseUri)[0]);
This sets the local "authenticationCookie" in the class and then serializes it out to SecureStorage.
I've proven/checked that the authenticationCookie is correctly de/serializing and loads up when the Xamarin.Forms app does. I've attached it to my web request. However, when I make the calls, I get a Login request from the opposite end on ASP.NET Core.
The ASP.NET Core server itself works fine normally. If I have a browser instance, it never asks me to login and the browser "remembers" and applies the cookie from login correctly. However, it should seem that the Xamarin.Forms app does not.
What am I missing?
For the sake of argument, this is how I am setting up cookies via the Login method:
//user has a User loaded from EF at this point
var userPrincipal = new ClaimsPrincipal(
new ClaimsIdentity(
new List<Claim>()
{
new Claim(ClaimTypes.Name, user.EmailAddress)
}, "Login"));
var properties = new AuthenticationProperties()
{
IsPersistent = true
};
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, properties);
So, I was successful in using the answer UNDER the selected answer:
How do I set a cookie on HttpClient's HttpRequestMessage
Apparently setting the CookieContainer and then populating it with a Cookie and including that in the Message DID NOT WORK.
The solution was to manually add the Cookie doing the following:
private HttpResponseMessage GetDataResponse(string url)
{
using (var handler = new HttpClientHandler { UseCookies = false })
{
using (var request = new HttpRequestMessage(HttpMethod.Get, url))
{
request.Headers.Add("Cookie", $"{MyCookie.Name}={MyCookie.Value}");
using (var client = new HttpClient(handler))
{
return client.SendAsync(request).Result;
}
}
}
}
This works exactly as we would expect!

Can fetch() do responseType=document?

XHR's responseType='document' is awesome because it hands you back a DOM document that you can use querySelector, etc on:
var xhr = new XMLHttpRequest();
xhr.open('GET', '/', true);
xhr.responseType = 'document';
xhr.onload = function(e) {
var document = e.target.response;
var h2headings = document.querySelectorAll('h2');
// ...
};
Is this possible with the fetch method?
It's not natively supported in fetch as the API is a purely network-layer API with no dependencies on being in a web browser (see discussion), but it's not too hard to pull off:
fetch('/').then(res => res.text())
.then(text => new DOMParser().parseFromString(text, 'text/html'))
.then(document => {
const h2headings = document.querySelectorAll('h2');
// ...
});

how to upload file asynchronously in mvc with example without loading entire page

var formdata;
formdata = new FormData();
var fileInput = document.getElementById('fileToUploadinproposal');
//Iterating through each files selected in fileInput
for (i = 0; i < fileInput.fi.length; i++) {
//Appending each file to FormData object
formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', "/Contract/UploadProposalDocument/");
xhr.send("");
xhr.onreadystatechange = function () {
debugger;
if (xhr.readyState == 4 && xhr.status == 200) {
$("#fileToUploadinproposal").val("")
alert(xhr.responseText);
}
}
return false;
in client side formdata is not accepting and fileInput.files.length also not accepting
You can use this jquery plugin as i mostly use this asp.net mvc to upload file via ajax:
http://powerdotnetcore.com/asp-net-mvc/asp-net-mvc-simple-ajax-file-upload-using-jquery
or you can refer this tutorial i made and used it in some scenarios, it uses iframe to upload file:
http://developmentpassion.blogspot.com/2013/08/aspnet-mvc-ajax-file-uploading-using.html