Friday, January 13, 2023

How to cancel any running task by wait for sometime in C#

 Problem Statement: In some real time scenario, you may need to cancel some long running tasks in certain time interval and then proceed. 

Here in below example, i am calling some infinite time method and am not sure when it will be completed. So i am making 30 seconds maximum to wait and cancelling it. 

RunSomeTestJob();

 

string RunSomeTestJob()

{

    string result = "";

 

    //loop your logic

 

    try

    {

        Console.WriteLine("Running Job Started " + DateTime.Now.ToString());

        // Create CancellationTokenSource.

        var source = new CancellationTokenSource();

        // ... Get Token from source.

        var token = source.Token;

 

        var someTask = Task.Run(() =>

        {

            result = infinteJobWork(token);

 

        }, token);

 

        someTask.Wait(30 * 1000);

       //someTask.Dispose();

        source.Cancel();

 

    }

    catch (Exception ex)

    {

        //suppress error and proceed

        //log somewhere

    }

    Console.Write("Running Job Completed " + result + DateTime.Now.ToString());

 

    Console.Read();

 

    //proceed with next steps

 

    return result;

 

}

 

string infinteJobWork(CancellationToken token)

{

    //Short running Job - Fixed timing

    //for (int i = 0; i < 3; i++)

    {

        //Long running Job - Indefinite time

        while (true)

        {

            //TODO: make some api call or some work to external api

            Console.WriteLine("Running Job : " + DateTime.Now.ToString());

            Thread.Sleep(5 * 1000);

 

            // See if we are canceled from our CancellationTokenSource.

            if (token.IsCancellationRequested)

            {

                Console.WriteLine("Job cancelled");

                return "Job cancelled";

            }

        }

    }

    //return "Job done";

}

 


Wednesday, July 6, 2022

Export Website as PDF - Using Headless browser

 There are many way we can download website html in C# and export it as PDF or however we wanted. But most of these ways not having option to render complete JavaSript and render the page fully.


Option 1: 

Simply use WebClient and export website into html then to PDF

using (WebClient client = new WebClient())

    {

        byte[] websiteData = client.DownloadData("somewebsiteurl");

        File.WriteAllBytes(“savepath”, websiteData);

        //do further steps to convert html to pdf

    }


Option 2: 

Use Headless browser with Puppetter to export as PDF from URL, here you can add more wait handlers to render the JavaScript

Ref: 

https://developer.chrome.com/docs/puppeteer/

https://www.puppeteersharp.com/  


Using JS: 

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com');
  await page.screenshot({ path: 'example.png' });

  await browser.close();
})();


Using C#: 


using var browserFetcher = new BrowserFetcher();

await browserFetcher.DownloadAsync();

await using var browser = await Puppeteer.LaunchAsync(

    new LaunchOptions { Headless = true });

await using var page = await browser.NewPageAsync();

await page.GoToAsync("http://www.google.com");

await page.ScreenshotAsync(outputFile);


Note: we can also use installed browsers for exporting website as below



Browser browser = await Puppeteer.LaunchAsync(new LaunchOptions

{

Headless = true,

Args = "{ "--disable-features=site-per-process", "--disable-web-security" }",

ExecutablePath = “any chromimum browser exe path”

});