Saturday, February 25, 2017

A simple guide to using Traits in Laravel 5

Its great if we can use trait in our application. Laravel has the ability to give us that freedom to use trait. Laravel is a strong php based framework today. At first we have to create a trait, but its nothing but a php class except we use here a keyword named 'trait' & surely this class has no constructor as it cannot be instantiated. So lets start with use of trait.

First we have to create a php file named "TestTrait.php" as follows:

namespace App\Trait;

trait TestTrait {
    public function someFunction() {
        
    }
}

I think you have already have good knowledge about namespace described in Laravel.

Now we have to use this trait in some Controller or Service etc...

Lets see an example of use of trait in Controller.

First we have to import "TestTrait" in our Controller as follows:

//First step is import
use App\Trait\TestTrait;
class TalentMapperController extends Controller
{
    //Second step is tell our Controller to use trait
    use TestTrait;
    
    public function __construct() {
        //Third & final step is apply functions from here
        super::someFunction();
    }
}

Friday, February 24, 2017

Http Redirect Using Laravel

Laravel is a strong php based framework today. It is very important forward to another url or redirect as http function. There are several ways describes in Laravel. The best way is redirect using Controller & Action. Using Controller Action is easy to redirect to another url:

return redirect()->action(
    'SomeController@action', ['id' => 1, 'status' => 'active']
);


Or you also can do the following:

return redirect("/afterRedirect/param1?x=1&y=2");

Get Current URL Using Laravel

Laravel is a strong php based framework today. We frequently coding on this platform. And who coded its important for him to know / get current working url sometimes. Its easy to get current url inside an Controller/Service class. Just need to use Request attribute to get desired output at Laravel. 

First need to import Request class to Controller/Service class:
use Illuminate\Http\Request;

And then need to pass Request as parameter as follows:
public function someAction(Request $request)

And finally use following method to get current full url:
$request->fullUrl();

You have different options when you use Laravel Request class as follows:

Get the request method
$request->method();

Get the root URL for the application
$request->root();

Get the URL (no query string) for the request
$request->url();

Get the full URL for the request
$request->fullUrl();

Get the current path info for the request
$request->path();

Determine if the request is the result of an AJAX call
$request->ajax(); 


There is another way around to get URL from Laravel Controller
At first you have to import following component:
use Illuminate\Routing\UrlGenerator;

Then need to initialize it on construct on controller as follows:
private $UrlGenerator;
public function __construct(UrlGenerator $UrlGenerator)
{
    $this->UrlGenerator = $UrlGenerator;
}

And then use below line of code get Laravel base URL:
$urlGenerator->to("/");

You can get all available method details of UrlGenerator from below link:
https://laravel.com/api/5.0/Illuminate/Routing/UrlGenerator.html
  

Tuesday, February 21, 2017

Create Thubmnail / Image From Each Page of a PDF Using Java

It is very important to make some thumbnails from pdf in our application. Using java it is now very easy to do this task. You have to open your pdf using java program then you can set which page (0...n) you want to make to thumbnail. Then you can save that as image to your server or desktop machine.

To complete this task you need to download PDFRenderer-0.9.1.jar.

You can download whole package from here.

Sample java code:

package com.pkm;

import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created by pritom on 26/12/2016.
 */
public class ThumbnailFromPdf {
    public static void main(String[] args) throws Exception {
        File file = new File("src/com/pkm/PDF.pdf");
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
        FileChannel fileChannel = randomAccessFile.getChannel();
        ByteBuffer byteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
        PDFFile pdfFile = new PDFFile(byteBuffer);
        PDFPage pdfPage = pdfFile.getPage(0);
        Rectangle rectangle = new Rectangle(0, 0, (int) pdfPage.getBBox().getWidth(), (int) pdfPage.getBBox().getHeight());
        Image image = pdfPage.getImage(rectangle.width, rectangle.height, rectangle, null, true, true);
        ImageIO.write((RenderedImage) image, "png", new File("src/com/pkm/PDF.png"));
    }
}

Sample output would be like something depends on your pdf file:


 

Saturday, February 18, 2017

VBScript Take Input From User

VBScript is a scripting language to manage computer developed by Microsoft. Below is a code snippet to take user input:

Wscript.StdOut.Write "Enter Some Input: "
Source = Wscript.StdIn.ReadLine

VBScript Create Rar File With Password Protection Using WinRar.exe

VBScript is a scripting language to manage computer developed by Microsoft. Sometimes we need to create .rar file using WirRar.exe and use VBScript. Below is a code snippet to create rar file using both VBScript & WinRar.exe. There is a extension you can use password to protect your rar file. -p"PASSWORD" will create a rar file with password or if you use only -p as arguments then a prompt will appear to take password from user as input. -r use to create recursive all folders and files withing the root folder. -hs argument for include all hidden files.

Dim ObjShell, FSO
Set ObjShell = WScript.CreateObject("WScript.Shell")
Set FSO = CreateObject("Scripting.FileSystemObject")

Wscript.StdOut.Write "Enter Source: "
Source = Wscript.StdIn.ReadLine

Wscript.StdOut.Write "Enter Destination: "
Destination = Wscript.StdIn.ReadLine

Wscript.StdOut.Write "Delete Source: "
DeleteSource = Wscript.StdIn.ReadLine

ObjShell.Run """C:\Program Files\WinRAR\WinRar.exe"" a -x -IBCK -ep1 -r -hs -p """ & Destination & """ """ & Source & """ ", 0, True
Set ObjShell = Nothing

Sub CheckRarCreated
    If (FSO.FileExists(Destination)) Then
       WScript.Echo Destination & " Created"
       If StrComp(DeleteSource, "True", 1) = 0 And FSO.FolderExists(Source) Then
          FSO.DeleteFolder Source
       End If
    Else
       WScript.Echo Destination & " Not Created"
    End If
End Sub
CheckRarCreated

Saturday, February 11, 2017

VBScript Open Another Program And Wait Until Closed

VBScript is a scripting language to manage computer developed by Microsoft. Below is a code snippet to open an external program suppose named "firefox.exe" and wait until firefox closed. Script will not be execute further statements until firefox closed. 

Dim objShell

ShowOption = 1
WaitUntilClose = True

Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run """C:\Program Files\Mozilla Firefox\firefox.exe""", ShowOption, WaitUntilClose
Set objShell = Nothing

'ShowOption
'0 Hide the window (and activate another window.)
'1 Activate and display the window. (restore size and position) Specify this flag when displaying a window for the first time. 
'2 Activate & minimize. 
'3 Activate & maximize. 
'4 Restore. The active window remains active. 
'5 Activate & Restore. 
'6 Minimize & activate the next top-level window in the Z order. 
'7 Minimize. The active window remains active. 
'8 Display the window in its current state. The active window remains active. 
'9 Restore & Activate. Specify this flag when restoring a minimized window. 
'10 Sets the show-state based on the state of the program that started the application.

VBScript Lunch Program Using Shell Execute

VBScript is a scripting language to manage computer developed by Microsoft. Below is a code snippet to open an external program using Shell Application.

Dim objShell

Program_Name = "Notepad.exe"
Arguments = "" 'Optional
Directory = "" 'Optional
Operation = "open" 'open,edit,find,print,properties
Show_Option = 1 

Set objShell = CreateObject("Shell.Application")
objShell.ShellExecute Program_Name, Arguments, Directory, Operation, Show_Option

Set objShell = Nothing

'0 = Open the application with a hidden window.
'1 = Open the application with a normal window. If the window is minimized or maximized, the system restores it to its original size and position.
'2 = Open the application with a minimized window.
'3 = Open the application with a maximized window.
'4 = Open the application with its window at its most recent size and position. The active window remains active.
'5 = Open the application with its window at its current size and position.
'7 = Open the application with a minimized window. The active window remains active.
'10 = Open the application with its window in the default state specified by the application.

VBScript Launch programs whose path contains spaces

Dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run("""C:\Program Files\Mozilla Firefox\firefox.exe""")
Set objShell = Nothing

Pass old input/ get old input from view after Form Request validation in laravel

Sometimes we need to get old values in form to show them when error back to the same form, It is now well organized in Laravel. Consider the following situations:

1. Suppose you submitted a form with some values.
2. Found some errors and send back to the form again from Laravel controller to show the form again.
3. You have to show the values when he was here few moments ago (before submit the form)

$username = Request::old('username');

or in view:

{{ old('username') }}

Laravel join or left join queries AS different name

There are many situations where you need to join same table, but must have different names (you can define this as alias). Below is a simple code snippet to show how you can join same table with different name.

$limit = 10;
$page = 1;
$groups = DB::table('person')
       ->leftJoin('users as for_user', function ($join) {
           $join->on('for_user.id', '=', 'person.for_id')->where("for_user.id", "=", 10);
       })
       ->join('users as by_user', function ($join) {
           $join->on('by_user.id', '=', 'person.by_id');
       })
       ->where('person.status', '=', 1)
       ->select('person.id', 'person.first_name', 'by_user.first_name')
       ->limit($limit)->offset($page * $limit)
       ->get();

jQuery extend prototype

It is important that you can extent jQuery to improve your work environment. Below is a code snippet to do this as simple:

If you write your code in some-file.js then follow below:


(function () {
    $.prototype.hi = function () {
        this.html("Prototype invoked...")
        return this
    }
})()

Else if you write your code in <script> tag then follow below:


$.prototype.hi = function () {
    this.html("Prototype invoked...")
    return this
}

Example of usage:


$(".class").hi()

How to get the query executed in Laravel

As a developer you must face some situation where you have to need the sql executed. In Laravel you can see your sql query generated each step. Below is a simple code snippet to output the sql query generated by Laravel query generator. Also you have the parameters there used in Laravel query.

DB::enableQueryLog();
$total = DB::table('user')
       ->where('group_id', '=', 1)
       ->where('status', '=', 1)
       ->count();
$queries = DB::getQueryLog();
$last_query = end($queries);
echo "<pre>"; print_r($last_query); echo "</pre>";


Output following:




Array
(
    [query] => select count(*) as aggregate from `user` where `group_id` = ? and `status` = ?
    [bindings] => Array
        (
            [0] => 64
            [1] => 1
        )

    [time] => 0
)

How to get the current URL inside @if statement (blade) in Laravel

It is sometimes you need to control your view page(.blade.php) based on url visited by user. You can check if user visited by a Controller or Controller+Action both. It can be now done by Laravel very easily. Below is code snippet to do the tricks.

@if (Request::is('controller/*'))
    <!-- code block here -->
@endif

@if (Request::is('controller/action'))
    <!-- code block here -->
@endif

Laravel adnance query builder using and or conditions

It is very important to make query dynamically based on what parameters we received. Best way to do this using Laravel is use query as a function. Background color yellow show how it works.


DB::table('users')
        ->where('name', '=', 'John')
        ->where(function($query) use($params) {
            $query->where('votes', '>', 100);
            $query->orWhere('title', '<>', 'Admin');
        })->get();

The query above will produce the following SQL:

select * from users where name = 'John' 
and (votes > 100 or title <> 'Admin') 

Or you can do below:

$where = [
    ['name', '=', "Some name"],
    ["OR" => function($q) {
        $q->where("type", "=", "EMPLOYEE");
        $q->orWhere("type", "=", "SUPERVISOR");
    }]
];


$list = DB::table('employees')->where($where)->get();

Laravel where in example query | Laravel query builder | Query Builder Component

In laravel it is need to do create criteria to search in database where in some id list or others. Below shows how can we use where in Laravel. 

DB::table('table')->whereIn('id', array(1, 2, 3))->get();

All query builder options available in below link:

Laravel Query Builder

Raw Queries in Laravel | Get Sql Query And Bindings From Laravel Eloquent Query Builder | Execute Raw Query With Parameters

Laravel has a strong query builder to build queries. It is as much powerful as we need. But sometimes we need to execute raw sql using Laravel. Below is a code snippet to execute raw sql queries using Laravel. The below code will return some results.


$results = DB::select( DB::raw("SELECT * FROM table_name WHERE field_id = :field_id"),
array(
    'field_id' => 5,
));

If you dont need to return results and only need to do some statement level queries then do the following:

DB::statement("UPDATE USER SET STATUS='ACTIVE' WHERE ID=1;");


You can get Raw SQL and Bindings from Laravel eloquent query builder:

$query = DB::table("my_table")->where("id", $id);
echo $query->toSql();
print_r($query->getBindings());


Laravel group concat operation

It is important to get some concat value. You can use GROUP_CONCAT in Laravel easily. Below is a code snippet to do the trick:


$result = DB::table('table_name')
       ->select(DB::raw('group_concat(field_name) as field_name_alias'))
       ->where('condition_field', '=', $condition_value )
       ->first();

Simple Laravel Layouts using Blade

The most part of Laravel is usage of layout. It helps you to design a better application. You can create a layout and use that for view pages. Below is a good & simple example how you can create and use layouts.

At first create file named "test.blade.php" under "resources/views/layouts" folder with following contents:


<!DOCTYPE html>
<html>
    <head>
        <title>Title - @yield('title')</title>      
    </head>

    <body>
        <section>
            @yield('content')                
        </section>
        <section>
            @yield('pageScript')
        </section>
    </body>
</html>

The use of the layout file would be as like (from any resources blade file):


@extends('layouts.test') //This line will include layout file

@section('title', 'Title of the page') //Set title of the page

@section('content') //Start content of the page
Html content goes here
@stop //End content of the page

@section('pageScript') //Start javascript of the page
<script src="{{ asset('/js/some-js-file.js') }}"></script>

<script>
$(document).ready(function () {
    
});
</script>
@stop //End javascript of the page

Laravel throw/return custom exception/response

In Laravel it is very simple to handle exception and return custom error codes to view. Below is a example how you can return custom http header code.


<?php
namespace App\Http\Controllers;

use Request;

class TestController extends Controller { 
   public function test_function(Request $request) {
       return response("content", 430)->header('Content-Type', "text/html");
   }
}
?>

Friday, February 10, 2017

VBScript Empty Recycle Bin

VBScript is a scripting language to manage computer developed by Microsoft. Now it is easy to empty your recycle bin easily. Below is a code snippet that describe how recycle bin be empty.

Const RECYCLE_BIN = &Ha&

Set FSO = CreateObject("Scripting.FileSystemObject")
Set ObjShell = CreateObject("Shell.Application")
Set ObjFolder = ObjShell.Namespace(RECYCLE_BIN)
Set ObjFolderItem = ObjFolder.Self
Wscript.Echo ObjFolderItem.Path

Set colItems = ObjFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
    If (objItem.Type = "File folder") Then
        FSO.DeleteFolder(objItem.Path)
    Else
        FSO.DeleteFile(objItem.Path)
    End If
Next

VBScript Delete All Files And SubFolders

VBScript is a scripting language to manage computer developed by Microsoft. It is important that we have power to do something using some script written by me. Below is a code snippet that delete all files & subfolders & files of subfolders easily.

Set FSO = CreateObject("Scripting.FileSystemObject")
Set Folder = FSO.GetFolder("C:\tmp\xxx")

'Delete all files in root folder
for each File in Folder.Files
    On Error Resume Next
    name = File.name
    File.Delete True
    If Err Then
        WScript.Echo "Error deleting:" & Name & " - " & Err.Description
    Else
        WScript.Echo "Deleted:" & Name
    End If
    On Error GoTo 0
Next

'Delete all subfolders and files
For Each File In Folder.SubFolders
    On Error Resume Next
    name = File.name
    File.Delete True
    If Err Then
        WScript.Echo "Error deleting:" & Name & " - " & Err.Description
    Else
        WScript.Echo "Deleted:" & Name
    End If
    On Error GoTo 0
Next

Tuesday, February 7, 2017

Resize command prompt through commands

mode con: cols=130 lines=40
OR

mode 130,40

VBScript Show Details Of a File, Copy, Delete And Move

set FSO = CreateObject("Scripting.FileSystemObject")

'Display detailed information about this file
set FileObject = FSO.GetFile("C:\tmp\heidisql.exe")

Wscript.Echo "Path = " & FileObject.Path
Wscript.Echo "Name = " & FileObject.Name
Wscript.Echo "Short Name = " & FileObject.ShortName
Wscript.Echo "Short Path = " & FileObject.ShortPath
Wscript.Echo "Drive = " & FileObject.Drive
Wscript.Echo "Size = " & FileObject.Size
Wscript.Echo "Attributes = " & FileObject.Attributes
Wscript.Echo "Parent Folder = " & FileObject.ParentFolder
Wscript.Echo "Date Created = " & FileObject.DateCreated
Wscript.Echo "Last Modified = " & FileObject.DateLastModified
Wscript.Echo "Last Accessed = " & FileObject.DateLastAccessed
'FileObject.Copy "heidisql_.exe", True 'True=Overwrite
'FileObject.Delete True 'True=Delete the read-only file
FileObject.Move "heidisql_moved.exe"

VBScript Open URL in Default Browser

Option Explicit

Dim WscriptSchell
Set WscriptSchell = CreateObject("WScript.Shell")

WscriptSchell.Run "https://google.com", 9

VBScript List And Details Of Local Drives

set FSO = CreateObject("Scripting.FileSystemObject")

'Display all drives and their properties
set ds = FSO.Drives
WScript.Echo "List of drives:"
for each d in ds
    WScript.Echo ""
    WScript.Echo "Drive Letter = " & d.DriveLetter
    WScript.Echo "Type = " & d.DriveType
    WScript.Echo "Ready = " & d.IsReady
    WScript.Echo "Path = " & d.Path
    WScript.Echo "Share Name = " & d.ShareName
    if d.IsReady then
        Details = "File System = " & d.FileSystem _
            & ", Serial = " & d.SerialNumber _
            & ", Volume = " & d.VolumeName _
            & ", Size = " & d.TotalSize _
            & ", Free = " & d.FreeSpace
        WScript.Echo Details
    end if
next

VBScript Execute Ping

Dim oShell, oExec, sLine
Set oShell = CreateObject("WScript.Shell")
Set oExec = oShell.Exec("ping google.com")

'Reading the output of the shell command thread
Do While Not oExec.StdOut.AtEndOfStream
    sLine = oExec.StdOut.ReadLine
    WScript.StdOut.WriteLine "Output: " & sLine
    WScript.Sleep 10
Loop

'Waiting for the shell command thread to end
'In case the output ends before the command
Do While oExec.Status = 0
    WScript.Sleep 100
Loop

VBScript Append text to text file if it already exists

Option Explicit

Const ForReading = 1, ForAppending = 8

Dim InputFileName, OutputFileName, FileSystemObject, InputFile, OutputFile

Set FileSystemObject = CreateObject("Scripting.FileSystemObject")
InputFileName  = "C:\tmp\input.txt"
OutputFileName = "C:\tmp\output.txt"

PreCheck

Set InputFile = FileSystemObject.OpenTextFile(InputFileName, ForReading)
Set OutputFile = FileSystemObject.OpenTextFile(OutputFileName, ForAppending, True)

OutputFile.WriteLine ""
Do While Not InputFile.AtEndOfStream 
    OutputFile.WriteLine InputFile.ReadLine
Loop

InputFile.Close
OutputFile.Close

Sub Echo(Str)
    Wscript.Echo Str
End Sub

Sub PreCheck()
    If Not FileSystemObject.FileExists(OutputFileName) Then
        Echo "Output File Not Found"
        WScript.Quit
    End If

    If Not FileSystemObject.FileExists(InputFileName) Then
        Echo "Input File Not Found"
        WScript.Quit
    End If

    If FileSystemObject.GetFile(InputFileName).Size < 1 Then
        Echo "Input File Has No Content"
        WScript.Quit
    End If
End Sub

Saturday, February 4, 2017

Windows CMD, Clear All Browsers Cache & Everything

::@ECHO OFF
::cscript.exe "Test.vbs"
::pause
::exit;

@echo off

rem IE
taskkill /F /IM iexplore.exe
start "" "C:\Windows\System32\rundll32.exe" InetCpl.cpl,ClearMyTracksByProcess 255

:: Parse the Local AppData sub path
call :Expand xAppData "%%LocalAppData:%UserProfile%=%%"

set "xFirefox=\mozilla\firefox\profiles"
set "xChrome=\google\chrome\user data"
set "xOpera1=\Local\Opera\Opera"
set "xOpera2=\Roaming\Opera\Opera"

:: Start at the User directory
pushd "%UserProfile%\.."

taskkill /F /IM firefox.exe
taskkill /F /IM chrome.exe
taskkill /F /IM opera.exe

:: Loop through the Users
for /D %%D in (*) do if exist "%%~fD%xAppData%" (
    rem Check for Firefox
    if exist "%%~fD%xAppData%%xFirefox%" (
        rd /s /q "%%~fD%xAppData%%xFirefox%"
    )

    rem Check for Chrome
    if exist "%%~fD%xAppData%%xChrome%" (
        rd /s /q "%%~fD%xAppData%%xChrome%"
    )
 
 rem Check for Opera
    if exist "%%~fD%xAppData%%xOpera1%" (
        rd /s /q "%%~fD%xAppData%%xOpera1%"
    )
 if exist "%%~fD%xAppData%%xOpera2%" (
        rd /s /q "%%~fD%xAppData%%xOpera2%"
    )
)
popd
goto End


::::::::::::::::::::::::::::::
:Expand <Variable> <Value>
if not "%~1"=="" set "%~1=%~2"
goto :eof


:End
endlocal

VBScript Clear Google Chrome Cache, History & Everything

Option Explicit
Dim FileSystemObject, RootFolder, UserName, File
Set FileSystemObject = CreateObject("Scripting.FileSystemObject")

UserName = CreateObject("WScript.Network").UserName
RootFolder = "C:\Users\" & UserName & "\AppData\Local\Google\Chrome\User Data\"
 
ProcessTerminate "chrome.exe"
DeleteFileFromFolder RootFolder

Sub DeleteFileFromFolder(Path)
    For Each File In FileSystemObject.GetFolder(Path).Files
        DeleteAllow File
    Next
    For Each File In FileSystemObject.GetFolder(Path).SubFolders
        DeleteFileFromFolder File.Path
    Next
End Sub

Sub DeleteAllow(File)
    'Bookmarks remain same
    If NOT(StrComp(Left(File.Name, 9), "Bookmarks", vbTextCompare)) = 0 Then
        Wscript.Echo File.Path + " Deleted"    
        On Error Resume Next
        FileSystemObject.DeleteFile File.Path, True
    End If
End Sub

Sub ProcessTerminate(Process)
    Const StrComputer = "." 
    Dim WshShell, ObjWMIService, ProcessList, ObjProcess
    Set WshShell = CreateObject("WScript.Shell")
    Set ObjWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & StrComputer & "\root\cimv2")

    Set ProcessList = ObjWMIService.ExecQuery("SELECT * FROM Win32_Process WHERE Name = '" & Process & "'")
    For Each ObjProcess in ProcessList 
        On Error Resume Next
        ObjProcess.Terminate
        Wscript.Echo "Process Terminated, ProcessId=" & ObjProcess.ProcessId & " (" & ObjProcess.Name & ")" 
    Next
End Sub

Friday, February 3, 2017

VBScript MySql connection

You have to install mysql odbc connector first.

Dim Connection, ConnectString

ConnectString = "Driver={MySQL ODBC 3.51 Driver};Server=localhost;PORT=3306;Database=database;User=root;Password="

Set Connection = CreateObject("ADODB.Connection")

Connection.Open ConnectString

Sql = "SELECT id,created_at FROM table ORDER BY id DESC LIMIT 0, 10"
Set Result = Connection.Execute(Sql)

Do Until Result.EOF
    Wscript.Echo "Id=" + CStr(Result(0)) + ",Create_Date=" & FormatDateTime(Result(1), 1)
    Result.MoveNext
Loop

Connection.Close

Install and Create MySQL ODBC Connector on Windows 7

MySQL ODBC Connector help you to connect to MySQL via different applications. It supports Windows, Linux, Mac & Unix Platforms. You can more details from here. Please follow the following steps to download and install MySQL ODBC Connector to your machine.


  • Download and install from here or from here
  • Double click on the file "mysql-connector-odbc-3.51.30-winx64.msi" that you just downloaded to run the setup process.
  • Click Next and accept the license agreement.
  • Select Custom to see what we will have after the installation

VBScript Get a List of the ODBC Drivers

Const HKEY_LOCAL_MACHINE = &H80000002
StrComputer = "."
Set ObjRegistry = GetObject("winmgmts:\\" & StrComputer & "\root\default:StdRegProv")
StrKeyPath = "SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers"
ObjRegistry.EnumValues HKEY_LOCAL_MACHINE, StrKeyPath, arrValueNames, arrValueTypes

For i = 0 to UBound(arrValueNames)
    StrValueName = arrValueNames(i)
    ObjRegistry.GetStringValue HKEY_LOCAL_MACHINE,StrKeyPath,StrValueName,StrValue
    Wscript.Echo StrValueName + " - " + StrValue
Next

Windows - How to terminate process using VBScript

Sub ProcessTerminate(Process)
    Const StrComputer = "." 
    Set WshShell = CreateObject("WScript.Shell")
    Set ObjWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & StrComputer & "\root\cimv2")

    Set ProcessList = objWMIService.ExecQuery("SELECT * FROM Win32_Process WHERE Name = '" & Process & "'")
    For Each ObjProcess in ProcessList 
        On Error Resume Next
        ObjProcess.Terminate
        Wscript.Echo "Process Terminated, ProcessId=" & ObjProcess.ProcessId & " (" & ObjProcess.Name & ")" 
    Next
End Sub

ProcessTerminate "chrome.exe"

VBScript Get List Of Running Processes And Executable Path

Dim Service, Process
 
Set Service = GetObject ("winmgmts:")
 
For each Process in Service.InstancesOf ("Win32_Process")
 Wscript.Echo Process.Name & ": " & Process.ExecutablePath
Next

VBScript - How to make program wait until process has finished

const DontWaitUntilFinished = false, ShowWindow = 1, DontShowWindow = 0, WaitUntilFinished = true
set WScript_Shell = WScript.CreateObject("WScript.Shell")
command1 = "C:\xampp\apache_stop.bat"
command2 = "C:\xampp\apache_start.bat"
Wscript.Echo "Apache Server Stopping"
WScript_Shell.Run command1, DontShowWindow, WaitUntilFinished
Wscript.Echo "Apache Server Stopped"
Wscript.Echo "Apache Server Starting"
WScript_Shell.Run command2, DontShowWindow, DontWaitUntilFinished
Wscript.Echo "Apache Server Started"

Thursday, February 2, 2017

VBScript: How to Automatically Restart MySQL Server


Set WshShell = CreateObject("WScript.Shell" ) 
'Just Start Apache Server & MySQL Server
WshShell.Run """C:\xampp\apache\bin\httpd.exe""", 0, false
WshShell.Run """C:\xampp\mysql\bin\mysqld.exe"" --defaults-file=C:\xampp\mysql\bin\my.ini --standalone --console", 0, false
'Stop & Start MySQL Server
WshShell.Run """C:\xampp\mysql_stop.bat""", 0, false
WshShell.Run """C:\xampp\mysql_start.bat"" --defaults-file=C:\xampp\mysql\bin\my.ini --standalone --console", 0, false
Set WshShell = Nothing

Wednesday, February 1, 2017

How can I delete only PDF File from a folder using VBS

Option Explicit
Dim FileSystemObject, RootFolder, SubFolder, File
On Error Resume Next
 Set FileSystemObject = CreateObject("Scripting.FileSystemObject")
 RootFolder = "C:\Users\PRITOM\Downloads"
 
 For Each File In FileSystemObject.GetFolder(RootFolder).Files
  If StrComp(Right(File.Path, 4), ".pdf", vbTextCompare) = 0 Then
   Wscript.Echo File.Path + " Deleted"
   FileSystemObject.DeleteFile File.Path, True
  End If
 Next
 
 For Each SubFolder In FileSystemObject.GetFolder(RootFolder).SubFolders
 Do
  If StrComp(SubFolder.Name, "management", vbTextCompare) = 0 Then
   Exit Do
  End If
  For Each File In FileSystemObject.GetFolder(SubFolder.Path).Files
   If StrComp(Right(File.Path, 4), ".pdf", vbTextCompare) = 0 Then
    Wscript.Echo File.Path + " Deleted"
    FileSystemObject.DeleteFile File.Path, True
   End If
  Next
 Loop Until True
 Next
On Error Goto 0