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”

});


Wednesday, June 22, 2022

Angular Ng Build out of memory issue

 If you come accross issue with Angular ng build in prod mode for out of memory issue, like below

Command: ng build --prod


Include command with "node --max_old_space_size=5120 ./node_modules/@angular/cli/bin/", you can increase the size however wanted. This will solve the issue, we can also update this size in environment variables of system. 

Command: node --max_old_space_size=5120 ./node_modules/@angular/cli/bin/ng build --prod



Monday, April 25, 2022

JSON Path to use in Angular Projects

How to use JSON Path to query any JSON object.

For example, consider below simple JSON, if you want to query JSON we can use simply query as this.obj.name or this.obj.id to access to the JSON

this.obj ={

   id: 1,

   "name": "balaji"

}

For array object we can use index, for ex: this.objData[0].id. For more JSON path to find we can refer https://jsonpathfinder.com/

this.objData = {

        data: [

  {

    "id": 1,

    "name": "Balajiprasad",

    "age": 18,

              "address": {

                      "state": "TN",

                       "country": "India"

                } 

 

  },

  {

    "id": 2,

    "name": "prasad",

    "age": 28,

     "address": {

                      "state": "Tx",

                       "country": "US"

                } 

  }

]}


In angular project, if we need to use JSON path dynamically then we can refer the jsonpath library Ref: https://www.npmjs.com/package/jsonpath

Steps to use,

1. Add "json-path" in package.json file under dependencies

    "dependencies": {

"jsonpath": "1.1.1"

}


2. Add reference of "json-path" directly in component. No need to specify in App.module

    import * as jp from 'jsonpath'

3. Use the JSON path in code , need to use $.. (double dots)

   let state = jp.query(this.objData, '$..data[0].address.state')

 



Tuesday, April 12, 2022

Excel - Find sum of all digits to single digit

In excel, use below formula to get sum of all digits into single digit  (For ex: 3268 -> Total 1). This is useful to findout vehicle number's total.

Formula: =IF(MOD(A1,9)=0,"9",MOD(A1,9))




Wednesday, December 15, 2021

AI Based PDF OCR using Microsoft Azure Form Recognizer

In real world, we will have many PDF files to read the content and prefill the forms in web application. To automatically read this PDF and predict the values, Microsoft offering cognitive service called Form Recognizer. Using this service, we can pass our PDF file and get the extracted OCR values as JSON back with bounding box coordinates. 

Ref: https://azure.microsoft.com/en-in/services/form-recognizer/#features

We can use some custom libraries to highlight the bounding box coordinates in UI over the image.  For this we can convert PDF into images and display it in UI as well.


For ex: 

https://www.w3schools.com/tags/tag_map.asp


Sample JSON extracted: Highlighted sample bounding box coordinates.

{"status":"succeeded","createdDateTime":"2021-02-23T05:09:00Z","lastUpdatedDateTime":"2021-02-23T05:09:11Z","analyzeResult":{"version":"2.1.0","readResults":[{"page":1,"angle":0,"width":1700,"height":2200,"unit":"pixel","lines":[{"text":"CONTOSO LTD.","boundingBox":[114,134,466,134,466,175,115,175],"words":[{"text":"CONTOSO","boundingBox":[115,135,333,134,333,176,115,176],"confidence":0.994},{"text":"LTD.","boundingBox":[357,134,465,134,465,176,358,176],"confidence":0.994}],"appearance":{"style":{"name":"other","confidence":0.878}}},{"text":"INVOICE","boundingBox":[1410,114,1601,115,1601,155,1410,155],"words":[{"text":"INVOICE","boundingBox":[1411,115,1593,115,1592,156,1411,155],"confidence":0.995}],"appearance":{"style":{"name":"other","confidence":0.878}}},.......}


Monday, September 13, 2021

Browser - Change Current Geo Location

In order to test different Geo Location in browser, we have option to change location in browser. Follow below steps,

Browsers used: Chrome, IE Edge

  1. Go to Developer Tools (Click F12)
  2. Click ... Settings Icon -> More Tools -> Sensors
  3. Now in Sensors Window, Change the location as needed. You can also manage for new locations.




Monday, August 24, 2020

SQL - Modify Array of JSON

 How to copy one array of JSON object into another array of JSON in SQL. Take this below sample copy array of empIds from one JSON into another JSON


DECLARE  @pArrayOfIntEmps nvarchar(max)='{ "empIds": [' + '1,2'+'] }'

--JSON_Query will return array value from json whereas JSON_VALUE return object value from json

--select JSON_QUERY(@pArrayOfIntEmps,'$.empIds') 

 

DECLARE @info NVARCHAR(max)='{"id":1,"abc":false,"empIds":[3,4] }'

SET @info=  JSON_MODIFY(ISNULL(@info,'{}'),'$.empIds,JSON_QUERY(@pArrayOfIntEmps,'$.empIds'))

select @info

 

--Output {"id":1,"abc":false,"empIds":[1,2] }, this empIds will be replaced by array of int

Thursday, May 14, 2020

How to ignore property conditionally during JSON serialization

Consider i have class Employer, i want serialize this class to json string and need ignore some properties conditionally. For ex: in my example, i want to include address1 and address2 only if it has valid values


  public class Employer
    {
 public int id { get; set; }

        public string name { get; set; }
       
 public string ssn { get; set; }

        public string address1 { get; set; }

        public string address2 { getset; }
   }



Declare some values


Employer employer = new Employer(){ … address1 = "some value", address2 = null };


Now serialize it for json string


var jsonstring = JsonConvert.SerializeObject(employer,
                       Newtonsoft.Json.Formatting.None,
                       new JsonSerializerSettings
                       {
                           
                       });

Here you will get all the properties.

Now lets see how to ignore the properties conditionally, you can choose either one of these options.

Option 1: Use ShouldSerialize property inside class itself like below. But you need add individual shouldSerialize property for each class property.

  public class Employer
    {
 public int id { get; set; }

        public string name { get; set; }
       
 public string ssn { get; set; }

        public string address1 { get; set; }

        public string address2 { get; set; }

        public bool ShouldSerializeaddress1()
        {
            // don't serialize if it is null or empty or add any your custom conditions
            return !string.IsNullOrEmpty(address1);
        }
        public bool ShouldSerializeaddress2()
        {
            // don't serialize if it is null or empty or add any your custom conditions
            return !string.IsNullOrEmpty(address2);
        }

   }


Option 2: Instead creating multiple ShouldSerialize property inside class, we can create ContractResolver and add it in Json serialization as below,

Create Resolver Class,

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Linq;
using System.Reflection;
...

  public class EmployerShouldSerializeContractResolver : DefaultContractResolver
    {
        public new static readonly EmployerShouldSerializeContractResolver Instance = new EmployerShouldSerializeContractResolver();

        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            JsonProperty property = base.CreateProperty(member, memberSerialization);

            if (property.DeclaringType == typeof(Employer))
            {
                property.ShouldSerialize =
                    instance =>
                    {
                        //ignore default values
                        return instance.GetType().GetProperty(member.Name).GetValue(instance, null) != property.DefaultValue;
                    };
            }

            return property;
        }

    }


Include it in JSON serialization,

var jsonstring = JsonConvert.SerializeObject(employer,
                       Newtonsoft.Json.Formatting.None,
                       new JsonSerializerSettings
                       {
                           ContractResolver = new EmployerShouldSerializeContractResolver()
                       });


Friday, April 24, 2020

Angular CLI - Custom Date validator

Angular supports of custom validators. Here i have created custom validator to validate date for template drive forms.

Directive: date-validator.directive.ts


import { AbstractControl, ValidatorFn, FormControl } from '@angular/forms';
import * as moment from 'moment';
import { NG_VALIDATORS, Validator } from '@angular/forms';
import { Directive } from '@angular/core';

// validation function
function validateDateFactory(): ValidatorFn {
  return (c: AbstractControl) => {

    let isValid = moment(c.value, 'M/D/YYYY', true).isValid();

    if (isValid) {
      return null;
    } else {
      return {
        validDate: {
          valid: false
        }
      };
    }
  }
}

@Directive({
  selector: '[validDate][ngModel]',
  providers: [
    { provide: NG_VALIDATORS, useExisting: ValidDateValidator, multi: true }
  ]
})
export class ValidDateValidator implements Validator {
  validator: ValidatorFn;

  constructor() {
    this.validator = validateDateFactory();
  }

  validate(c: FormControl) {
    return this.validator(c);
  }

}


Html:
<input type="text" [(ngModel)]="someDateModal" validDate />