Monday, June 19, 2017

VBScript: Execute Script Using Command Prompt | Execute Script Using Batch File Processing

VBScript: Execute Script Using Command Prompt | Execute Script Using Batch File Processing. It's easy to execute a VBScript file using Windows command prompt. First need to create ".vbs" file. Now create a file named "MyScript.bat" with following code and double click the bat file to execute VBScript.


@ECHO OFF
mode 200,50

cscript.exe MyScript.vbs

pause

exit;








Sunday, June 18, 2017

Laravel 5.X Forward To URL | Redirect To Route | Forward Request | Mock Request | Mock HTTP Request | Dynamic HTTP Request | Laravel Dispatch Request

Laravel 5.X Forward To URL | Redirect To Route | Forward Request | Mock Request | Mock HTTP Request | Dynamic HTTP Request.

It's easy to forward a request using Laravel Route. Forwarding do for you is URL will not change but response will change. The way it is working is that it will mock a request using Request::create(...) and dispatch using current Router.

<?php
namespace App\Http\Controllers;

use Illuminate\Routing\Router;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request as HttpRequest;

class MyController extends Controller {
    public function __construct(HttpRequest $httpRequest, Router $router) {
        $this->middleware('auth', ['except' => ['action1', 'action2']]);

        $this->httpRequest = $httpRequest;
        $this->appRouter = $router;
    }

    //Route=my/need-forward (Create new request and dispatch)
    public function needForward() {
        //http://www.domain.com/my/need-forward
        $route_name = action("MyController@forwardHere");
        //http://www.domain.com/other-folder/my/need-forward
        $route_name = action("OtherFolder\\MyController@forwardHere");
        //http://www.domain.com/my/need-forward/100/Name%20Text?roll=303
        $route_name = action("MyController@forwardHere", ["id" => 100, "name" => "Name Text", "roll" => 303]);
        $request = HttpRequest::create($route_name, 'GET', array("param1" => "Param 1", "param2" => "Param 2"));
        return app()->handle($request);
    }

    //Route=my/need-forward (Forward same request to new route)
    public function needForward2() {
        $route_name = "my/forward-here";
        $request = HttpRequest::create($route_name);
        return  $this->appRouter->dispatch($request);
    }

    //Route=my/forward-here
    public function forwardHere() {
        echo "Browse [/my/need-forward] will send output of [/my/forward-here]";
    }
}


Saturday, June 17, 2017

MySQL Trigger | MySQL Before/After Insert Trigger | MySQL Before/After Update Trigger | MySQL Before/After Delete Trigger

MySQL Trigger | MySQL Before/After Insert Trigger | MySQL Before/After Update Trigger | MySQL Before/After Delete Trigger:


DROP TRIGGER IF EXISTS `example_table_before_insert`;
DELIMITER $$
CREATE TRIGGER `example_table_before_insert`
BEFORE INSERT ON `example_table` FOR EACH ROW BEGIN
  DECLARE ready INT DEFAULT 0;
  DECLARE rnd_str TEXT;
  IF NEW.CODE IS NULL OR CHAR_LENGTH(NEW.CODE) = 0 THEN
    WHILE NOT ready DO
      SET rnd_str := UPPER(SUBSTR(MD5(CONCAT(rand(), now())), 1, 5));
      IF NOT exists(SELECT * FROM example_table WHERE CODE = rnd_str) THEN
        SET NEW.CODE = rnd_str;
        SET ready := 1;
      END IF;
    END WHILE;
  END IF;
END
$$
DELIMITER ;

DROP TRIGGER IF EXISTS `example_table_before_update`;
DELIMITER $$
CREATE TRIGGER `example_table_before_update`
BEFORE UPDATE ON `example_table` FOR EACH ROW BEGIN
  DECLARE ready INT DEFAULT 0;
  DECLARE rnd_str TEXT;
  IF NEW.CODE IS NULL OR CHAR_LENGTH(NEW.CODE) = 0 THEN
    WHILE NOT ready DO
      SET rnd_str := UPPER(SUBSTR(MD5(CONCAT(rand(), now())), 1, 5));
      IF NOT exists(SELECT * FROM example_table WHERE CODE = rnd_str) THEN
        SET NEW.CODE = rnd_str;
        SET ready := 1;
      END IF;
    END WHILE;
  END IF;
  SET NEW.updated_at = now();
END
$$
DELIMITER ;

DROP TRIGGER IF EXISTS `example_table_after_delete`;
DELIMITER $$
CREATE TRIGGER `example_table_after_delete`
AFTER DELETE ON `example_table` FOR EACH ROW BEGIN
  DELETE FROM example_table_associations WHERE example_id=OLD.id;
END
$$
DELIMITER ;



Friday, June 16, 2017

How to Handle Laravel 5.X Exceptions

In Laravel 5.2, all errors and exceptions, both custom and default, are handled by the Handler class in app/Exceptions/Handler.php with the help of two methods ##report & ##render.

The ##report method enables you to log raised exceptions or parse them to error logging engines. 

The ##render method return with an error message as well as response code raised by any exception. It generates a HTTP response from the exception and sends it back to the browser.

We can also override the default behavior of error handling with our own custom exception handler if we need.


/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request $request
 * @param  \Exception $e
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $e)
{
    //$request->ajax() [[AJAX REQUEST CHECK]]
    if ($e instanceof MyException) {
        if ($request->ajax()) {
            return response()->json(['error' => 'Not Found'], 404);
        }
        return response()->view('errors.custom', [], 500);
    }
    if ($this->isHttpException($e)) {
        switch ($e->getStatusCode()) {
            case 404:
                return response()->view('errors.404', [], 500);
            case 500:
                return response()->view('errors.500', [], 500);
            default:
                return $this->renderHttpException($e);
        }
    } elseif ($e instanceof TokenMismatchException) {
        return redirect()->back()->withInput()->with('error', 'Your session has expired');
    } else {
        return response()->view('errors.500', [], 500);
    }
}

And finally you have to add a 404.blade.php && 500.blade.php file in resources/view/errors to represent our custom error page.


We can also generate a 404 as well as 500 error page response by calling the abort method which takes an optional response message.

abort(404, 'The resource you are looking for could not be found');


This will check for a related resources/view/errors/404.blade.php and serve a HTTP response with the 404 status code back to the browser. The same applies for 401 and 500 or for other error status codes.








Laravel 5.X: Access HTTP Session From Controller | Service

It's very important to have access to HTTP session in our Laravel Controller or Service class. Below is a code sample of session access in Controller class. Use of session in Service is similar.


<?php

namespace App\Http\Controllers;

use Symfony\Component\HttpFoundation\Session\Session;

class HomeController extends BaseController
{
    private $Session;
    public function __construct(Session $Session)
    {
        $this->Session = $Session;
    }

    public function setSessionValue()
    {
        $this->Session->set("some_name", "some_value_in_session");
        exit;
    }

    public function getSessionValue() {
        echo $this->Session->get("some_name");
        die();
    }










Laravel 5.X: Access HTTP Request From Controller | Service

It's very important to access HTTP Request from Laravel Controller or Service. Below is a code example showing how to access HTTP Request from Laravel Controller. Same for Service.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request as HttpRequest;
use Illuminate\Routing\Controller as BaseController;

class HomeController extends BaseController
{
    private $HttpRequest;
    public function __construct(HttpRequest $HttpRequest)
    {
        $this->HttpRequest = $HttpRequest;
    }

    public function checkHttpRequest() {
        echo $this->HttpRequest->get("id") . "<BR>";
        echo $this->HttpRequest->getBaseUrl() . "<BR>";
        echo $this->HttpRequest->getUri();
        die();
    }
}









Instagram: How to get images using Instagram API

You can develop a web-app to show Instagram images/photos from other users accounts using API call. Instagram API is the easiest so far to me. At first you have to visit https://www.instagram.com/developer/ to create a developer account and then an application for API communication as below steps:

The most important link is https://www.instagram.com/developer which describes API procedures.







You can create a Application and then you have client id and client secret as below screenshot.



Below is the full PHP code snippet to get images/photos from Instagram using API call:


<?php
session_start();

include_once "CurlExecutor.php";

define("CLIENT_ID", "d1aa0f7.............................");
define("CLIENT_SECRET", "e972a4a.........................");
define("REDIRECT_URI", "http://localhost/ci/InstagramAPI/");

if (isset($_SESSION["access_token"])) {
    getRecentPhotos();
}
elseif (isset($_GET["code"])) {
    getAccessToken();
}
else {
    authentication();
}

function getRecentPhotos() {
    $user_id = $_SESSION["user_id"];
    $url = "https://api.instagram.com/v1/users/$user_id/media/recent/";
    $url = $url . "?access_token=" . $_SESSION["access_token"];
    $url = $url . "&count=5";
    $response = CurlExecutor::execute($url);
    $response["response"] = json_decode($response["response"]);
    if ($response["code"] != 200) {
        die("ERROR");
    }
    foreach ($response["response"]->data as $o) {
        echo "<a target='_blank' href='" . $o->link . "'>";
        echo "<img src='" . $o->images->low_resolution->url . "'/>";
        echo "</a>";
    }
}

function getAccessToken() {
    $post = array(
        "client_id" => CLIENT_ID,
        "client_secret" => CLIENT_SECRET,
        "grant_type" => "authorization_code",
        "redirect_uri" => REDIRECT_URI,
        "code" => $_GET["code"]
    );
    $response = CurlExecutor::execute("https://api.instagram.com/oauth/access_token", "POST", $post);
    $response["response"] = json_decode($response["response"]);
    CurlExecutor::prettyPrint($response);
    if ($response["code"] != 200) {
        die("ERROR");
    }
    $_SESSION["access_token"] = $response["response"]->access_token;
    $_SESSION["user_id"] = $response["response"]->user->id;
    header("Refresh:0; url=" . REDIRECT_URI);
}

function authentication() {
    $auth_url = "https://api.instagram.com/oauth/authorize/?" .
        "client_id=" . CLIENT_ID .
        "&redirect_uri=" . REDIRECT_URI .
        "&response_type=code";
    header("Refresh:0; url=$auth_url");
    exit();
}
?>

Authorization screen is as below screenshots (User will authorize this application and then forwarded to redirect URI with a one time code, you can use that code to get access token, and then you can get users photos as well as users basic info using those access token):



And output is as below: