Saturday 11 June 2022

Laravel Trottle AddHeaders Error

Laravel Trottle AddHeaders Error

We sometimes face this error when new install Laravel and run composer udpate

 Type error: Argument 1 passed to Illuminate\\Routing\\Middleware\\ThrottleRequests::addHeaders()

must be an instance of Symfony\\Component\\HttpFoundation\\Response, null given


Solution:

For me, the issue is resolved by correcting database credentials in the .env file. Hope the same will work for

you as well.

Saturday 12 June 2021

Test Web Apps on all browsers online

Test Web Apps on different browsers online


Browserstack is the best solution to test website UI/UX on different browsers simulators at single place online.



browserstack

Click here for more info:




I used this https://www.browserstack.com/ for my apps to test UI/UX and performance of my apps. We can get following browsers at one place:
  1. Google Chrome - All Versions
  2. IE - All Versions 
  3. Safari - All Versions
  4. Android - All Versions
  5. IOS - All devices, All Versions
  6. Opera browsers


Tuesday 8 June 2021

Microsoft Graph API PHP

Microsoft Graph API PHP Tutorials

I am sharing some basic sample PHP code for Microsoft Graph API. May this will  helpful for someone.

For full reference, go to GIT URL:

PHP Framework Laravel Sample Code GIT URL:





















To start, you should have Outlook/Hotmail or any Microsoft Account.

First required to register App on Azure Active Directory. You can create App on Azure even if you have School or Organization account.

Graph API will generate Microsoft Authentication URL, where user will redirect and after successful login he will redirect back callback URL. Callback URL need to define in Azure App.

User can get Calendar events based on dates provided. User can create events on their Calendar.

Sharing Create Calendar Event using Microsoft Graph API.

<?php
// POST /me/events
$events_response = $graph->createRequest('POST', '/me/events')
    ->attachBody($newEvent)
    ->setReturnType(Model\Event::class)
    ->execute();


Get Calendar Events using Microsoft Graph API

<?php

$userEventsArr = $graph->createRequest('GET', $getEventsUrl)
// Add the user's timezone to the Prefer header
    ->addHeaders(array(
        'Prefer' => 'outlook.timezone="' . $userTimezone . '"',
    ))
    ->setReturnType(Model\Event::class)
    ->execute();

Sunday 6 June 2021

Calculate Number of Days PHP

Calculate Number of Working Days Between Two Days in PHP

I am sharing my PHP code to get difference between two dates.

$workingDays = 0;

$startTimestamp = strtotime('2021-06-03');
$endTimestamp = strtotime('2022-07-09');
for ($i = $startTimestamp; $i <= $endTimestamp; $i = $i + (60 * 60 * 24)) {
    if (date("N", $i) <= 5) $workingDays = $workingDays + 1;
}

echo "no. of days: " . $workingDays;

Save code in nofdays.php.

Run program in terminal. Output will be:

$ php nofdays.php

no. of days: 287




Tuesday 11 May 2021

Digital E-sign Tool

Digital E-sign Tool

I have developed Digital E-Signature Tool to digital sign any PDF file. It's a developed in HTML5, JQuery technology and JSPDF library. JS Signature Pad library is also used. PHP script is also added to save the file on server. May be its helpful for someone.

Digital E-Sign Tool Img1


User can drag signature at any place on the PDF document. User can upload signature as well.




Digital E-Sign Tool -2



Digital E-sign - 3



Digital E-Sign - 4



    
Digital E-Sign Tool



Full code can be found at below Bitbucket URL:



First we load any PDF.  Then user click Add signature button. User can upload signature file as well. Once user draw or upload his signature, it will show in drag area on right side. User can drag that signature anywhere on the PDF file. Once user click Acceptance checkbox, as most of the sites ask for acceptance of policy or any agreement. Submit button becomes available. User can save signature file, email that or upload on server, developer has to write that script as per his requirements.




Friday 12 March 2021

PDF file generation from HTML file in Python

PDF Generation from HTML File in Python






I am sharing my script to generate PDF file from HTML file in Python using PDFKit module.

Install Python PDF-Kit

$ pip install pdfkit

Some Simple Examples:
import pdfkit

pdfkit.from_url('http://testpage.com', 'out.pdf')
pdfkit.from_file('test.html', 'out.pdf')
pdfkit.from_string('Hello!', 'out.pdf')

My Sample Script to generate PDF from HTML page.

 import os

import sys
from flask import Flask,request
import pdfkit
from flask import make_response
import logging.config
app = Flask(__name__)
from decouple import config

# Logger and handlers
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'console': {
            'format': '%(levelname)-1s%(asctime)s [%(name)-12s.%(funcName)s.%(lineno)s%(message)s',
        },
        'file': {
            'format': '%(levelname)-1s%(asctime)s [%(name)-12s.%(funcName)s.%(lineno)s%(message)s',
        },
    },
    'handlers': {
        'console': {
            'level': "DEBUG",
            'class': 'logging.StreamHandler',
            'formatter': 'console',
            'stream': sys.stdout
        },
        'file': {
            'level': "DEBUG",
            'class': 'logging.handlers.RotatingFileHandler',
            'formatter': 'file',
            'filename': 'htmltopdf.log',
        },
    },
    'loggers': {
        '': {
            'handlers': ['file'],
            'level': "DEBUG",
            'propagate': True
        },
    }
}

logging.config.dictConfig(LOGGING)
LOGGER = logging.getLogger(__name__)


@app.route("/")
# Function for html to pdf convertor
def function_html_to_pdf_convertor():
    try:
        logging.debug("calling func")
        html_file = request.args.get('f', default="", type=str)
        if html_file:
            html_file = '{}{}'.format(html_file,'.html')
            filepath = os.path.join(app.static_folder, html_file)
            filename = os.path.splitext(os.path.basename(filepath))[0]
            css = "static/style.css"
            options = {
                'page-size': 'Letter',
                'encoding': "UTF-8",
                'zoom': 1.80,
                'footer-center': 'Page [page]/[topage]',
                'footer-font-size': 8
            }
            if os.path.isfile(filepath):
                #pdf = pdfkit.from_file(filepath, css=css)
                pdf = pdfkit.from_file(filepath, False,options=options, css=css)
                response = make_response(pdf)
                response.headers.set('Content-Disposition', 'attachment', filename=filename + '.pdf')
                response.headers.set('Content-Type', 'application/pdf')
                return response
            else:
                logging.debug("File not found")
                return {
                    "status": 404,
                    "message": 'File not found'
        }
        logging.debug("'Please provide file'")
        return{
            "status": 400,
            "message": 'Please provide file'
        }

    except Exception as e:
        logging.debug("Bad request {}".format(e))
        return {
            "status": 400,
            "error": '{}'.format(e)
        }
# main function
if __name__ == "__main__":
    app.run()

Monday 8 February 2021

AWS Cognito SSO Integration with Python

AWS Cognito SSO Integration with Python

AWS SSO Cognito OAuth2.0 implementation as per below URL:

https://aws.amazon.com/blogs/mobile/understanding-amazon-cognito-user-pool-oauth-2-0-grants/

First we need to create code, get Client ID and Client Secret. Run below URL:

https://AUTH_DOMAIN/login?client_id=XXXXXXXXXX&response_type=code&scope=email+openid&redirect_uri=http://localhost/test/sso_check

Above URL will return to redirect url with code in query string.

Note: Code is valid for one time transaction only.

Get Access Token using the Code as per below description:



Make below request:





this will return below response:

{
    "id_token": "eyJraWQiOiJJNGs2UXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "access_token": "eyJraWQiOiJENllqdXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "refresh_token": "eyJjdHkiOiJKV1QiLCJlbmXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "expires_in": 3600,
    "token_type": "Bearer"
}


From above response we need to use id_token to get user information:

  • id_token – A valid user pool ID token. Note that an ID token is only provided if the openid scope was requested.
Below is the Python code Github URL to get user information by validating JWT token returned in id_token key.






Below is the response from above Python code:



Create .ICS file using PHP code

Recently worked on creating a .ics file in PHP after a very long time, code so thought to share with everybody. Please find below the comple...