Wednesday, December 6, 2023

Html - Render Html Dynamically into Frame without Hosting and Communicate from Parent

 In case we want to render Html dynamically into website as frame without hosting the Html into another website, we can use of this code Blob with createObjectURL to render dynamically,


Create Parent Website as below:

<html>

<head>

<script>

// This function will update the iframe src with the HTML code from the textarea

function renderHTML() {

   // Get the textarea element by its id

  var textarea = document.getElementById("html-code");

  // Get the iframe element by its id

  var iframe = document.getElementById("html-frame");

  // Create a blob object from the textarea value

  var blob = new Blob([textarea.value], {type: "text/html"});

  // Create a URL object from the blob object

  var url = URL.createObjectURL(blob);

  // Set the iframe src to the URL object

  iframe.src = url;

}

 

function postIframe(){

 var iframe = document.getElementById("html-frame");

 iframe.contentWindow.postMessage("Hi, Message From Parent Website", '*');

}

  </script>

</head>

<body>

  <h1>HTML Editor</h1>

  <p>Enter some HTML code in the textarea below and click the button to render it in the iframe.</p>

<textarea id="html-code" rows="10" cols="50">

        <h2>Hello World</h2>

        <p>This is a simple HTML document.</p>

</textarea>


<br>

<button onclick="renderHTML()">Render HTML</button>

<br>

<iframe id="html-frame" width="500" height="300"></iframe>

<br />

<button onclick="postIframe()">Post Iframe</button>

</body>

</html>


In case we want to communicate with iFrame, we can use of postMessage, for that we can add the following code into Html of iFrame

iFrame Html Content as below:


<!DOCTYPE html>

<html>

<head>

  <title>Page Title</title>

</head>

<body>

  <h1>This is a Heading</h1>

  <p>This is a paragraph.</p>

  <script type="text/javaScript">

     function addListener() {

       window.addEventListener('message', event => {

        // IMPORTANT: check the origin of the data!

        //if (event.origin === 'https://your-parent-site-url') {

        // The data was sent from your site.

        // Data sent with postMessage is stored in event.data:

        alert(event.data);

        //} else {

        // The data was NOT sent from your site!

        // Be careful! Do not use it. This else branch is

        // here just for clarity, you usually shouldn't need it.

        return;

        //}

      });

     }

    addListener();

   </script>

<div> Footer Content</div>

</body>

</html>

Friday, July 21, 2023

How to get previous page details in page change event on embedded PowerBI report

In Power Bi, there is challenge to get page details when changing the pages. In Angular/JavaScript, powerBI client provides event handling to manage this. For this page changes, we have "pageChanged" event. Below sample code will help us to get events on page changes, so that you can capture bookmark if needed on previous page names etc.,


Sample Code: 

import { service, factories } from "powerbi-client";
const powerBI= new service.Service(factories.hpmFactory, factories.wpmpFactory, factories.routerFactory);

....

let currentSelectedPage = any = null;
let pbiElement = document.getElementById(“yourdivid”);
let pbiconfig = : any = {
    type: 'report',
    hostName: "https://app.powerbi.com/",
    accessToken: "",
    embedUrl: "",
    id: "",
    settings: {
      filterPaneEnabled: false,
      navContentPaneEnabled: false
    }
  }

this.report =  powerBI.embed(pbiElement, pbiconfig);

this.report.on('pageChanged', (event) => {
      
     console.log('Page changed Old:', event.detail.oldPage);
    
    //If event.detail.oldPage is not working then go with custom logic 
    //if (this.currentSelectedPage)
    //console.log('Page changed Old:', this.currentSelectedPage.displayName);  
    //set changed page into existing variables
    //this.currentSelectedPage = event.detail.newPage;

      console.log('Page changed New:', this.currentSelectedPage.displayName);
});

Thursday, March 9, 2023

Regex - To find word startswith __ and endswith __ but does not contain __

 Regex to match words start with double underscore (__) and endswith double underscore (__), but should not contains double underscore (__)


Pattern: /\_\_[^_\n]{1}.*?([^_\n]+)\_\_/g


This will match __somekey__ ,  __some_key__,  but not __some__key__, insted it will match __some__


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";

}