Puppeteer LaunchAsync throwing exception - puppeteer-sharp

I have an existing ASPNET Web Application. The front end is HTML/JavaScript and the backend is WebAPI 2. We have been using NRECO.PDFGenerator to drop PDFs to the users, this uses a the QT browser and debugging is becoming a chore. I found PuppeteerSharp and figured I'd give it a try.
I installed the libs using nuget, added an Async method to one of my Web Api Controllers but when I call it the LaunchAsync method just crashed.
[Route("api/pdf/v2/download")]
public IHttpActionResult V2Download([FromBody] Models.PDF.List _pdf) {
Models.Message.Response _return = new Models.Message.Response();
_return.Message = "Success!";
_return.Now = DateTime.Now;
try
{
string[] argu = null;
Meh(argu);
}
catch (Exception ex)
{
_return.Message = ex.Message;
_return.Severity = 3;
}
return Ok(_return);
}
public static async Task Meh(string[] args)
{
var options = new LaunchOptions
{
Headless = true,
Args = new[] {"--no-sandbox" }
};
Debug.WriteLine("Downloading chromium");
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
Debug.WriteLine("Navigating google");
using (var browser = await Puppeteer.LaunchAsync(options))
using (var page = await browser.NewPageAsync())
{
Debug.WriteLine("Navigating to page");
await page.GoToAsync("http://www.google.com");
Debug.WriteLine("Generating PDF");
await page.PdfAsync(Path.Combine(Directory.GetCurrentDirectory(), "google.pdf"));
Debug.WriteLine("Export completed");
if (!args.Any(arg => arg == "auto-exit"))
{
Console.ReadLine();
}
}
}
I'm not sure where to go from here. This is the console output. There's more...
Navigating google
The thread 0x3418 has exited with code 0 (0x0).
Exception thrown: 'System.NullReferenceException' in System.Web.dll
Exception thrown: 'System.NullReferenceException' in mscorlib.dll
The project is using framework 4.7.2
Solution
Everything that touches the Async method needs to also be Async. Also, Passing null args will cause problems as well.
Here's a code sample.
//[Authorize]
[Route("api/pdf/v2/download")]
public async Task<IHttpActionResult> V2Download([FromBody] Models.PDF.List _pdf) {
Models.Message.Response _return = new Models.Message.Response();
_return.Message = "Success!";
_return.Now = DateTime.Now;
try
{
string[] argu = { };
await Meh(argu);
}
catch (Exception ex)
{
_return.Message = ex.Message;
_return.Severity = 3;
}
return Ok(_return);
}
public static async Task Meh(string[] args)
{
var options = new LaunchOptions
{
Headless = true
};
Debug.WriteLine("Downloading chromium");
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
Debug.WriteLine("Navigating google");
using (var browser = await Puppeteer.LaunchAsync(options))
using (var page = await browser.NewPageAsync())
{
Debug.WriteLine("Navigating to page");
await page.GoToAsync("http://www.google.com");
Debug.WriteLine("Generating PDF");
await page.PdfAsync(Path.Combine(Directory.GetCurrentDirectory(), "google.pdf"));
Debug.WriteLine(Path.Combine(Directory.GetCurrentDirectory(), "google.pdf"));
Debug.WriteLine("Export completed");
if (!args.Any(arg => arg == "auto-exit"))
{
Console.ReadLine();
}
}
}

Related

ASP.NET Core: Fetch image from external site and save on Server

I want to fetch an image from an external site and save it on the web applicationĀ“s server.
My current code downloads the file, but it won't open because of wrong format, it says.
private Uri _uri;
private HttpClient _client;
[HttpPost]
public async Task WmsExport(ExportImagePostData postData)
{
try
{
PrepareUri(postData);
ValidateUrl(postData);
PrepareRequest(postData);
await FetchImageAndSave_async(postData);
}
catch (TaskCanceledException)
{
HttpContext.Response.StatusCode = 408;
}
catch (Exception ex)
{
var statusCode = 500;
HttpContext.Response.StatusCode = statusCode;
_logger.LogError(ex, ex.Message);
}
}
private void PrepareRequest(ExportImagePostData postData)
{
_client = _customClientFactory.CreateHttpClient();
_client.BaseAddress = _uri;
_client.CopyRequestHeaders(HttpContext);
_client.DefaultRequestHeaders.Add("Accept", "image/png");
}
public async Task FetchImageAndSave_async(ExportImagePostData postData)
{
using (var contentStream = await _client.GetStreamAsync(_client.BaseAddress.OriginalString))
{
await SaveImageOnServer_async(postData, contentStream);
}
}
private async Task SaveImageOnServer_async(ExportImagePostData postData, Stream downloadStream)
{
var filename = "wmsexp" + DateTime.Now.ToString("HHmm") + "." + postData.ImageType;
var directory = "wwwroot/Images/uploads/";
var path = Path.Combine(Directory.GetCurrentDirectory(), directory, filename);
using (var outStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 1048576, true))
{
await downloadStream.CopyToAsync(outStream);
}
}
Here is how the images look like in my folder, when I try to open them:
****SOLVED** **
I got help from Roman Marusyk, here on Stack Overflow. Thanks Roman! If you write an answer I be happy to set it as the answer!
The issue seem to have been that I added wrong HTTP-headers, and that some of my paths to the images where incorrect.

TaskContinuation.cs not found exception while accessing WebAPI Task

I'm trying to fetch records from a db cursor from the Client app.
Debugging Web API shows that the Cursor returns records but when returning to the Client it throws mscorlib.pdb not loaded window and clicking on Load option it throws TaskContinuation.cs not found exception
Code snippets as below ( removed irrelevant codes for readability )
WebAPI
[HttpPost("{values}")]
public async Task<ActionResult> Post([FromBody] JToken values)
{
// code removed for readility
string[] cursors = { };
cursors = await cursor.GetRpts();
CursorClass firstCursor = JsonConvert.DeserializeObject<CursorClass>(cursors[0]);
return new OkObjectResult(cursors);
}
public async Task<string[]> GetRpts()
{
try
{
DataTable[] dataTables;
CursorClass[] cursorClasses = new CursorClass[5];
//stripped some code
using (DataAccess dataAccess = new DataAccess()
{
ParamData = PrepareDoc(),
ProcedureName = Constants.Rpt,
RecordSets = this.CursorNumbers,
})
{
Int32 errorNumber = await dataAccess.RunComAsync();
dataTables = dataAccess.TableData;
};
//fetching code stripped off
string[] _cursors = Array.ConvertAll(cursorClasses, JsonConvert.SerializeObject);
return _cursors;
}
catch (Exception ex)
{
string tt = ex.Message;
}
}
public async Task<Int32> RunComAsync()
{
Int32 returnValue = 0;
try
{
//open db connection
//---------- Running the Command in asysnc mode ----------
Task<int> task = new Task<int>(oracleCommand.ExecuteNonQuery);
task.Start();
returnValue = await task;
//--------------------------------------------------------
OracleRefCursor[] refCursor = { null, null, null, null, null };
for (int _sub = 0; _sub < RecordSets; _sub++)
{
//DT declaration / connection code removed
dataAdapter.Fill(dataTable, refCursor[_sub]);
TableData[_sub] = dataTable;
}
}
catch (Exception ex)
{
return LogMsg(ex);
}
finally
{
this.Dispose(true);
}
CloseConnection();
return LogMsg(null,"Successful Operation");
}
Client
private async Task<HttpStatusCode> CallService()
{
HttpResponseMessage _response = null;
try
{
using (HttpRequestMessage requestMessage = new HttpRequestMessage()
{
Content = new System.Net.Http.StringContent(JsonRepo, System.Text.Encoding.UTF8, HeaderJson),
RequestUri = new Uri(UriString),
Method = HttpMethod.Post,
})
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Utils.TOKEN) ;
_response = await httpClient.SendAsync(requestMessage);
if (_response.IsSuccessStatusCode)
{
string httpResponse = await _response.Content.ReadAsStringAsync();
httpString = JsonConvert.DeserializeObject<string[]>(httpResponse);
}
}
}
return ErrorCode;
}
Is that something related to async operation? while debugging the API it confirms the Datatable with records . Any inputs are deeply appreciated.
error image
TIA

I get invalid need: expected Wait, have None in my Bot code

I get "invalid need: expected Wait, have None" exception in RootDialog, MessageReceivedAsync method's context.Forward line. Why could this be happening? what correction should I make? Please find my code below.
I use -C#, Visual Studio 2015, Microsoft Bot Framework, Bot emulator. This is for Web Chat.
MessageController
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
if (activity.Type == ActivityTypes.Message)
{
await Conversation.SendAsync(activity, () => new RootDialog());
}
else
if (activity.Type == ActivityTypes.ConversationUpdate)
{
var greeting = activity.CreateReply("Hi! I'm Cmon. Enter the Id of the Employee you want to know about.");
await connector.Conversations.ReplyToActivityAsync(greeting);
}
else
{
this.HandleSystemMessage(activity);
}
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
RootDialog -
public async Task StartAsync(IDialogContext context)
{
context.Wait(this.MessageReceivedAsync);
}
public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
{
var message = await result;
try
{
if (message.Text != null)
{
await context.Forward(new DirectoryDialog(), null, message,CancellationToken.None);
}
}
catch (Exception ex)
{
await context.PostAsync($"Oops! Something went wrong :-(");
}
}
DirectoryDialog -
public async Task StartAsync(IDialogContext context)
{
var message = context.Activity as IMessageActivity;
var query = DirectoryQuery.Parse(message.Text);
await context.PostAsync($"Searching for {query.SearchKey}...");
try
{
await SearchEmployee(context, query);
}
catch (FormCanceledException ex)
{
await context.PostAsync($"Oops! Something went wrong :-(");
}
}
private async Task SearchEmployee(IDialogContext context, DirectoryQuery searchQuery)
{
DirectoryDal dal = new DirectoryDal();
DataSet ds = dal.GetEmployeeSearch(searchQuery.SearchKey);
if (ds.Tables.Count > 0 & ds.Tables[0].Rows.Count > 0)
{
StringBuilder employeeSearchMessageBuilder = new StringBuilder(100);
//do something with data table data
var employeeSearchReply = context.MakeMessage();
employeeSearchReply.Type = ActivityTypes.Message;
employeeSearchReply.TextFormat = TextFormatTypes.Markdown;
employeeSearchReply.Text = employeeSearchMessageBuilder.ToString();
await context.PostAsync(employeeSearchReply);
}
}
By passing null here:
await context.Forward(new DirectoryDialog(), null, message,CancellationToken.None);
you are breaking the dialog chain. You have to define your Resume method.
The Troubleshooting section of the documentation has a good section about that, here:
Ensure all dialog methods end with a plan to handle the next message.
All IDialog methods should complete with IDialogStack.Call,
IDialogStack.Wait, or IDialogStack.Done. These IDialogStack methods
are exposed through the IDialogContext that is passed to every IDialog
method. Calling IDialogStack.Forward and using the system prompts
through the PromptDialog static methods will call one of these methods
in their implementation.
I was able to resolve the issue by making the following modifications to my DirectoryDialog.
DirectoryDialog code -
public async Task StartAsync(IDialogContext context)
{
var message = context.Activity as IMessageActivity;
var query = DirectoryQuery.Parse(message.Text);
await context.PostAsync($"Searching for {query.SearchKey}...");
try
{
//await SearchEmployee(context, query);
context.Wait(MessageReceivedAsync);
}
catch (FormCanceledException ex)
{
await context.PostAsync($"Oops! Something went wrong :-(");
}
}
RootDialog code -
public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
{
var message = await result;
try
{
if (message.Text != null)
{
await context.Forward(new DirectoryDialog(), ResumeAfterOptionDialog, message,CancellationToken.None);
}
}
catch (Exception ex)
{
await context.PostAsync($"Oops! Something went wrong");
}
finally{
context.Done(true);
}
}
private async Task ResumeAfterOptionDialog(IDialogContext context, IAwaitable<object> result)
{
context.Wait(MessageReceivedAsync);
}
Thank you Tanmoy and Nicolas for helping! :)
context.wait(MessageReceivedAsync);
at the end of MessageReceivedAsync(IDialogContext context, IAwaitable result) method of Root Dialog.
and
context.done(true);
at the end of StartAsync method of DirectoryDialog or within both try and catch block

Linq update Trouble

I want to update my Azure database using linq in my xamarin.forms project
below is the initalise and sync methods that connect to the database. These work successfully. My problem is that I want to update a record is the database. Any suggestions are welcome.
MobileServiceClient client = null;
IMobileServiceSyncTable<Shop> ShopTable2;
bool isInitialised;
public async Task Initialize()
{
if (isInitialised)
{
return;
}
this.client = new MobileServiceClient("link to database");
MobileServiceClient client = new MobileServiceClient("link to databse");
const string path = "user.db";
var store = new MobileServiceSQLiteStore(path);
store.DefineTable<Shop>();
await this.client.SyncContext.InitializeAsync(store, new MobileServiceSyncHandler());
ShopTable2= this.client.GetSyncTable<Shop>();
isInitialised = true;
}
sync method
public async Task Sync()
{
try
{
await shopTable2.PullAsync("allusers3", shopTable2.CreateQuery());
await client.SyncContext.PushAsync();
}
catch (Exception ex)
{
Debug.WriteLine("Unable to sync " + ex);
}
}
where I want to update the records here:
public async void BuyProducts(string Pname)
{
string productname = Pname;
await Initialize();
await SyncBookings();
List<Shop_TBL> item = await BookingsTable2
.Where(todoItem => todoItem.ProductName == productname)
.ToListAsync();
}
Assuming you are using Entity Framework as your ORM:
Select the entity you want to update.
var book = db.Books.First(b => b.Id == _id);
Change the property:
book.Name = "Something else";
Save the changes:
await db.SaveChangesAsync();
or
db.SaveChanges();
That's how you do an update.

Azure Notification Hub and WP8 Intermitant notifications

This is a fairly long piece of code but I am getting nowhere with this and cannot see any issues, although I am new to using notification hubs. I am trying to register for targeted notifications (the logged on user) using the notification hub in Azure. After the registration, a test notification is sent.
The issue I am having is that sometimes the notification is sent to the device, and sometimes it is not. It mostly isn't but occasionally when I step through the code on the server, i will get the notification on the emulator come through. Once when I deployed the app to my phone the notification came though on the emulator! I cannot discover a pattern.
My Controller class looks like this;
private NotificationHelper hub;
public RegisterController()
{
hub = NotificationHelper.Instance;
}
public async Task<RegistrationDescription> Post([FromBody]JObject registrationCall)
{
var obj = await hub.Post(registrationCall);
return obj;
}
And the helper class (which is used elsewhere so is not directly in the controller) looks like this;
public static NotificationHelper Instance = new NotificationHelper();
public NotificationHubClient Hub { get; set; }
// Create the client in the constructor.
public NotificationHelper()
{
var cn = "<my-cn>";
Hub = NotificationHubClient.CreateClientFromConnectionString(cn, "<my-hub>");
}
public async Task<RegistrationDescription> Post([FromBody] JObject registrationCall)
{
// Get the registration info that we need from the request.
var platform = registrationCall["platform"].ToString();
var installationId = registrationCall["instId"].ToString();
var channelUri = registrationCall["channelUri"] != null
? registrationCall["channelUri"].ToString()
: null;
var deviceToken = registrationCall["deviceToken"] != null
? registrationCall["deviceToken"].ToString()
: null;
var userName = HttpContext.Current.User.Identity.Name;
// Get registrations for the current installation ID.
var regsForInstId = await Hub.GetRegistrationsByTagAsync(installationId, 100);
var updated = false;
var firstRegistration = true;
RegistrationDescription registration = null;
// Check for existing registrations.
foreach (var registrationDescription in regsForInstId)
{
if (firstRegistration)
{
// Update the tags.
registrationDescription.Tags = new HashSet<string>() {installationId, userName};
// We need to handle each platform separately.
switch (platform)
{
case "windows":
var winReg = registrationDescription as MpnsRegistrationDescription;
winReg.ChannelUri = new Uri(channelUri);
registration = await Hub.UpdateRegistrationAsync(winReg);
break;
case "ios":
var iosReg = registrationDescription as AppleRegistrationDescription;
iosReg.DeviceToken = deviceToken;
registration = await Hub.UpdateRegistrationAsync(iosReg);
break;
}
updated = true;
firstRegistration = false;
}
else
{
// We shouldn't have any extra registrations; delete if we do.
await Hub.DeleteRegistrationAsync(registrationDescription);
}
}
// Create a new registration.
if (!updated)
{
switch (platform)
{
case "windows":
registration = await Hub.CreateMpnsNativeRegistrationAsync(channelUri,
new string[] {installationId, userName});
break;
case "ios":
registration = await Hub.CreateAppleNativeRegistrationAsync(deviceToken,
new string[] {installationId, userName});
break;
}
}
// Send out a test notification.
await SendNotification(string.Format("Test notification for {0}", userName), userName);
return registration;
And finally, my SendNotification method is here;
internal async Task SendNotification(string notificationText, string tag)
{
try
{
var toast = PrepareToastPayload("<my-hub>", notificationText);
// Send a notification to the logged-in user on both platforms.
await NotificationHelper.Instance.Hub.SendMpnsNativeNotificationAsync(toast, tag);
//await hubClient.SendAppleNativeNotificationAsync(alert, tag);
}
catch (ArgumentException ex)
{
// This is expected when an APNS registration doesn't exist.
Console.WriteLine(ex.Message);
}
}
I suspect the issue is in my phone client code, which is here and SubscribeToService is called immediately after WebAPI login;
public void SubscribeToService()
{
_channel = HttpNotificationChannel.Find("mychannel");
if (_channel == null)
{
_channel = new HttpNotificationChannel("mychannel");
_channel.Open();
_channel.BindToShellToast();
}
_channel.ChannelUriUpdated += async (o, args) =>
{
var hub = new NotificationHub("<my-hub>", "<my-cn>");
await hub.RegisterNativeAsync(args.ChannelUri.ToString());
await RegisterForMessageNotificationsAsync();
};
}
public async Task RegisterForMessageNotificationsAsync()
{
using (var client = GetNewHttpClient(true))
{
// Get the info that we need to request registration.
var installationId = LocalStorageManager.GetInstallationId(); // a new Guid
var registration = new Dictionary<string, string>()
{
{"platform", "windows"},
{"instId", installationId},
{"channelUri", _channel.ChannelUri.ToString()}
};
var request = new HttpRequestMessage(HttpMethod.Post, new Uri(ApiUrl + "api/Register/RegisterForNotifications"));
request.Content = new StringContent(JsonConvert.SerializeObject(registration), Encoding.UTF8, "application/json");
string message;
try
{
HttpResponseMessage response = await client.SendAsync(request);
message = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
message = ex.Message;
}
_registrationId = message;
}
}
Any help would be greatly appriciated as I have been stuck on this now for days! I know this is a lot of code to paste up here but it is all relevant.
Thanks,
EDIT: The SubscribeToService() method is called when the user logs in and authenticates with the WebAPI. The method is here;
public async Task<User> SendSubmitLogonAsync(LogonObject lo)
{
_logonObject = lo;
using (var client = GetNewHttpClient(false))
{
var logonString = String.Format("grant_type=password&username={0}&password={1}", lo.username, lo.password);
var sc = new StringContent(logonString, Encoding.UTF8);
var response = await client.PostAsync("Token", sc);
if (response.IsSuccessStatusCode)
{
_logonResponse = await response.Content.ReadAsAsync<TokenResponseModel>();
var userInfo = await GetUserInfoAsync();
if (_channel == null)
SubscribeToService();
else
await RegisterForMessageNotificationsAsync();
return userInfo;
}
// ...
}
}
I have solved the issue. There are tons of fairly poorly organised howto's for azure notification hubs and only one of them has this note toward the bottom;
NOTE:
You will not receive the notification when you are still in the app.
To receive a toast notification while the app is active, you must
handle the ShellToastNotificationReceived event.
This is why I was experiencing intermittent results, as i assumed you would still get a notification if you were in the app. And this little note is pretty well hidden.
Have you used proper tag / tag expressions while register/send the message. Also, Where are you storing the id back from the notification hub. It should be used when you update the channel uri (it will expire).
I would suggest to start from scratch.
Ref: http://msdn.microsoft.com/en-us/library/dn530749.aspx

Resources