Monday, July 29, 2019

Angular CLI - Handle Error Globally

To handle error globally in Angular 7 Cli, follow below steps

Ref: https://angular.io/api/core/ErrorHandler

Steps:

- Create ErrorHanlder file as below


import { Injectable, ErrorHandler } from '@angular/core';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  constructor(private ngZone: NgZone) {
  }

  handleError(error) {
    this.ngZone.run(() => {
//use ngZone to attach context to Angular's zone
//custom logic to do anything, for ex: toastService can be injected and shown here
    });

    //log as error to console
    console.error(error);
  }
}



-  Inject GlobalErrorHandler into app.module.ts providers as below


import { NgModule, ErrorHandler } from '@angular/core';
import { GlobalErrorHandler } from './core/config/error.handler';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
  ],
  providers: [
    …,
    { provide: ErrorHandler, useClass: GlobalErrorHandler },
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }


-  Now throw error from anywhere, it will be catched in GlobalErrorHanlder

import { catchError, map } from 'rxjs/operators';

import { Observable, of, throwError } from 'rxjs';
….

getUser(): Observable<User> {
      return this.http.get(this.getUserUrl      )
        .pipe(
        map(response => { return <User>response; }),
        catchError((error, caught) => {
          //handled error globally
          return throwError(error);
        }));

    }

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

        }
    }
 }

Thursday, March 21, 2019

C# - Read file and save bytes into Text file


Read file and save bytes into Text file

System.IO.FileStream stream = System.IO.File.OpenRead(@"FileFullPathRead.pdf");
byte[] fileBytes = new byte[stream.Length];
stream.Read(fileBytes, 0, fileBytes.Length);
stream.Close();

string base64 = Convert.ToBase64String(fileBytes);
System.IO.File.WriteAllText(@"FileFullPathToSave.txt", base64);

Tuesday, February 26, 2019

Http TLS Support for Legacy framework

   Recently i faced issue to make http call to WebAPI which is supporting latest TLS12 or TLS11. But our client project framework uses .net 4.0 so it not support by default. To resolve this issue added below code (constructor of API or global level)


 //Setting supported security protocol

   System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | (SecurityProtocolType)((SslProtocols)0x00000C00) | (SecurityProtocolType)((SslProtocols)0x00000300);



Here 

(SecurityProtocolType)((SslProtocols)0x00000C00) is equivalent to Tls12
(SecurityProtocolType)((SslProtocols)0x00000300) is equivalent to Tls11



Ref: https://support.microsoft.com/en-us/help/3154520/support-for-tls-system-default-versions-included-in-the-net-framework