Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

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);
});

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

}

 


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()
                       });


Monday, April 22, 2019

C# - Pdf rotate using iTextSharp

In C#, with opensource iTextSharp can be find in nuget package, we can easily rotate each pdf pages and save as new file, use below code

using iTextSharp.text;
using iTextSharp.text.pdf;

using System.IO;


namespace PdfRotate
{
    class Program
    {
        static void Main(string[] args)
        {
            //INFO: Change input and ouput path here
            string pdfFilePath = @"C:\Files\sample.pdf";
            string outputPath = @" C:\Files\sampleoutput.pdf ";

            //INFO: Change rotate degree here to 90, 180 etc
            RotatePages(pdfFilePath, outputPath, 180);           
        }

        private static void RotatePages(string pdfFilePath, string outputPath, int rotateDegree)
        {
            PdfReader reader = new PdfReader(pdfFilePath);
            int pagesCount = reader.NumberOfPages;

            for (int n = 1; n <= pagesCount; n++)
            {
                PdfDictionary page = reader.GetPageN(n);
                PdfNumber rotate = page.GetAsNumber(PdfName.ROTATE);
                int rotation =
                        rotate == null ? rotateDegree : (rotate.IntValue + rotateDegree) % 360;

                page.Put(PdfName.ROTATE, new PdfNumber(rotation));
            }

            PdfStamper stamper = new PdfStamper(reader, new FileStream(outputPath, FileMode.Create));
            stamper.Close();
            reader.Close();
        }
    }
}


C# - Pdf split using iTextSharp

In C#, with opensource iTextSharp can be find in nuget package, we can easily split pdf into mulitple files per page. use below code

using iTextSharp.text;
using iTextSharp.text.pdf;

using System.IO;

namespace PdfSplit
{
    class Program
    {

    
    static void Main(string[] args)
       {
            string pdfFilePath = @"C:\Files\sample.pdf";

            string outputPath = @"C:\Files\";

            SplitPages(pdfFilePath, outputPath);
             }

    private static void SplitPages(string pdfFilePath, string outputPath)
        {
           // Intialize a new PdfReader instance with the contents of the source Pdf file:
            PdfReader reader = new PdfReader(pdfFilePath);

            FileInfo file = new FileInfo(pdfFilePath);
            string pdfFileName = file.Name.Substring(0, file.Name.LastIndexOf(".")) + "-";

            Program obj = new Program();

            int pageNameSuffix = 0;
            for (int pageNumber = 1; pageNumber <= reader.NumberOfPages; pageNumber++)
            {
                pageNameSuffix++;
                string newPdfFileName = string.Format(pdfFileName + "{0}", pageNameSuffix);
                obj.SplitAndSaveInterval(pdfFilePath, outputPath, pageNumber, newPdfFileName);
            }
        }

   private void SplitAndSaveInterval(string pdfFilePath, string outputPath, int pagenumber, string pdfFileName)
        {
            using (PdfReader reader = new PdfReader(pdfFilePath))
            {
                Document document = new Document();
                PdfCopy copy = new PdfCopy(document, new FileStream(outputPath + "\\" + pdfFileName + ".pdf", FileMode.Create));
                document.Open();

                copy.AddPage(copy.GetImportedPage(reader, pagenumber));

                document.Close();
            }

        }
    }
 }