Create an alias in Windows

May 20th, 2011 | by | technology

May
20

Recently, I wanted to create shortcuts for git commands. I can have written aliases inside the git config file, but then also, I had to type git explicitly. So, I just searched the internet and came across this link: http://superuser.com/questions/49170/create-an-alias-in-windows-xp.

And I just wrote few quick aliases using the doskey in a file called ‘a.cmd‘. Now I just type ‘a‘ and press TAB and ENTER in the command prompt and set aliases quickly. I don’t want it to be automatic, so I just manually run the a.cmd whenever needed. Here is how my a.cmd looks like initially:

doskey st=git status
doskey log=git log
doskey +=git add $1
doskey co=git commit
doskey ..=cd ..
doskey bin=cd "D:\Project\Release\"
doskey src=cd "D:\Project\"

No Comments »

Show line numbers in vi or vim

May 11th, 2010 | by | technology

May
11

Displaying line numbers while editing a file can be handy. Using line numbers you can directly jump to a particular line. You can set the line numbers in vi using the following commands:

:set number

If you want to turn off the line numbers in vi, use the following command:

:set nonumber

You can also insert the following text into the .vimrc file, and can switch on or off the line numbers, by pressing the F6 and F7 keys respectively.

vi ~/.vimrc
nnoremap <silent> <F6> :set number<CR>
nnoremap <silent> <F7> :set nonumber<CR>

You can also find lots of vimrc recipes at: http://stackoverflow.com/questions/164847

No Comments »

Move cursor by display lines when wrapping in vi

May 11th, 2010 | by | technology

May
11

You can move your cursor by display lines when wrapping in vi, instead of jumping to the next line. This can be really helpful, when you have long wrapped lines, and you want to move in between them.

Just edit the .vimrc file.

vi ~/.vimrc

and insert the following text into that:

nnoremap <up> gk
nnoremap <down> gj
inoremap <up> <C-o>gk
inoremap <down> <C-o>gj

No Comments »

File Checksum Integrity Verifier utility

May 8th, 2010 | by | technology

May
08

Many times we face situations where a bug is not reproducible on a particular version in our environment, but the customer or supports says, that its reproducible at their ends, but they can’t share that environment due to security concerns.

Most of the times it can be some configuration issue or some patch applied in the customer environment. We can easily verify that the files in the customer environment is the same as the one that we uses to reproduce the issue, instead of asking customer to zip their environment and send to us, using the file hashes/checksums.

The File Checksum Integrity Verifier (FCIV) is a command-prompt utility that computes and verifies cryptographic hash values of files. FCIV can compute MD5 or SHA-1 cryptographic hash values. These values can be displayed on the screen or saved in an XML file database for later use and verification.

FCIV command is easy to use and can recursively compute the checksums of all the files in a folder and you can also specify file type filter.

fciv.exe c:\mydir -r -wp -sha1 -type *.dll -xml db.xml

More information and download links is available in the Microsoft support article at: http://support.microsoft.com/kb/841290

If you are looking for some graphical tool, then HashMyFiles is a good freeware tool for this purpose. HashMyFiles is small utility that allows you to calculate the MD5 and SHA1 hashes of one or more files in your system. You can easily copy the MD5/SHA1 hashes list into the clipboard, or save them into text/html/xml file. HashMyFiles can also be launched from the context menu of Windows Explorer, and display the MD5/SHA1 hashes of the selected file or folder.

HashMyFiles

No Comments »

Using FTP Batch Scripts on Windows

May 8th, 2010 | by | technology

May
08

The Microsoft KB article 96269 shows you how to use the ftp program that comes with all versions of windows to automate file transfer. You can use the -s option for passing FTP script to the program.

ftp -s:script.txt

The contents of script.txt might look like this:

open ftp.myserver.com
yourUserName
yourPassword
bin
cd /files
dele file.zip
put file.zip
bye

However, if the FTP host implements automatic login, this command will not work. To turn off automatic login, use the -n switch in the command line.

No Comments »

Shell script to download file using ftp

April 13th, 2010 | by | technology

Apr
13

#!/bin/sh

# ftpget - given an ftp: style URL, unwrap it, and try to obtain the file using ftp.

if [ $# -ne 2 ] && [ $# -ne 3 ]; then
  echo "Usage: $0 ftp://... username [password]" >&2
  exit 1
fi

# Typical URL: ftp://ftp.ncftp.com/2.7.1/ncftpd-2.7.1.tar.gz

if [ "$(echo $1 | cut -c1-6)" != "ftp://" ] ; then
  echo "$0: Malformed url. I need it to start with ftp://" >&2;
  exit 1
fi

server="$(echo $1 | cut -d/ -f3)"
filename="/$(echo $1 | cut -d/ -f4-)"
basefile="$(basename $filename)"
username="$(echo $2)"
password=""
if [ $# -eq 3 ] ; then
  password="$(echo $3)"
fi

#rm $basefile
echo ${0}: Downloading $basefile from server $server

ftp -n << EOF
open $server
user $username $password
bin
get $filename $basefile
quit
EOF

if [ $? -eq 0 ] ; then
  #chmod +x $basefile
  ls -l $basefile
fi

exit 0

No Comments »

How to search duplicate files within two directories?

November 17th, 2009 | by | technology

Nov
17

#!/usr/bin/perl
use strict;
use warnings;

# findDupeFiles:
# This script attempts to identify which files might be duplicates.
# It searches specified directories for files with a given suffix
# and reports on files that have the same MD5 digest.
# The suffix or suffixes to be searched for are specified by the first
# command-line argument - each suffix separated from the next by a vertical bar.
# The subsequent command-line arguments specify the directories to be searched.
# If no directories are specified on the command-line,
# it searches the current directory.
# Files whose names start with "._" are ignored.
#
# Cameron Hayne (macdev@hayne.net)  January 2006
#
#
# Examples of use:
# ----------------
# findDupeFiles '.aif|.aiff' AAA BBB CCC
# would look for duplicates among all the files with ".aif" or ".aiff" suffixes
# under the directories AAA, BBB, and CCC
#
# findDupeFiles '.aif|.aiff'
# would look for duplicates among all the files with ".aif" or ".aiff" suffixes
# under the current directory
#
# findDupeFiles '' AAA BBB CCC
# would look for duplicates among all the files (no matter what suffix)
# under the directories AAA, BBB, and CCC
#
# findDupeFiles
# would look for duplicates among all the files (no matter what suffix)
# under the current directory
# -----------------------------------------------------------------------------

use File::Find;
use File::stat;
use Digest::MD5;

my $matchSomeSuffix; # reference to a subroutine for matching suffixes
if (defined($ARGV[0]))
{
  # the list of desired suffixes is supplied in $ARGV[0]
  # separated by vertical bars - e.g. ".mp3|.aiff"
  # Note that if $ARGV[0] is '', then all files will be looked at

  my @suffixes = split(/\|/, $ARGV[0]);
  if (scalar(@suffixes) > 0)
  {
    # create an efficient matching subroutine using the Friedl technique
    my $matchExpr = join('||', map {"m/\$suffixes[$_]\$/io"} 0..$#suffixes);

    $matchSomeSuffix = eval "sub {$matchExpr}";
  }
  shift @ARGV;
}

# if no dirs supplied as command-line args, we search the current directory
my @searchDirs = @ARGV ? @ARGV : ".";

# verify that these are in fact directories
foreach my $dir (@searchDirs)
{
  die "\"$dir\" is not a directory\n" unless -d "$dir";
}

my %filesByMd5; # global variable holding hash of arrays of dupes

# calcMd5: returns the MD5 digest of the given file
sub calcMd5($)
{
  my ($filename) = @_;

  if (-d $filename)
  {
    # doing MD5 on a directory is not supported
    return "unsupported"; # we need to return something
  }

  $filename =~ s#^(\s)#./$1#; # protect against leading whitespace
  open(FILE, "< $filename\0")
     or die "Unable to open file \"$filename\": $!\n";
  binmode(FILE); # just in case we're on Windows!
  my $md5 = Digest::MD5->new->addfile(*FILE)->hexdigest;
  close(FILE);
  return $md5;
}

# checkFile: invoked from the 'find' routine on each file or directory in turn
sub checkFile()
{
  return unless -f $_; # only interested in files, not directories

  my $filename = $_;
  my $dirname = $File::Find::dir;

  return if $filename =~ /^\._/; # ignore files whose names start with "._"

  if (defined($matchSomeSuffix))
  {
    return unless &$matchSomeSuffix;
  }

  my $statInfo = stat($filename)
        or warn "Can't stat file \"$dirname/$filename\": $!\n" and return;
  my $size = $statInfo->size;
  my $md5 = calcMd5($filename);

  my $fileInfo = {
    'dirname'  => $dirname,
    'filename' => $filename,
    'size'   => $size,
    'md5'    => $md5,
    };

  push(@{$filesByMd5{$md5}}, $fileInfo);
}

MAIN:
{
  # traverse the directories and build up lists of dupes in %filesByMd5
  find(\&checkFile, @searchDirs);

  # for each set of dupes, print the full path to the files
  my $numDupes = 0;
  my $numDupeBytes = 0;
  foreach my $key (keys %filesByMd5)
  {
    my @dupList = @{$filesByMd5{$key}};
    my $numCopies = scalar(@dupList);
    next unless $numCopies > 1;

    my $size = -1;
    foreach my $fileInfo (@dupList)
    {
      my $dirname = $fileInfo->{dirname};
      my $filename = $fileInfo->{filename};
      if ($size == -1)
      {
        $size = $fileInfo->{size};
      }
      elsif ($size != $fileInfo->{size}) # sanity check
      {
        print "File sizes don't match!\n";
        print "previous: $size current: $fileInfo->{size}\n";
      }

      print "rm $dirname/$filename\n";
    }
    #print "----------\n";

    $numDupes += ($numCopies - 1);
    $numDupeBytes += ($size * ($numCopies - 1));
  }

  my $numDupeMegabytes = sprintf("%.1f", $numDupeBytes / (1024 * 1024));
  #print "Number of duplicate files: $numDupes\n";
  #print "Megabytes duplicated: $numDupeMegabytes\n";
}

I used it to match the test cases output to a predefined set and find out which cased failed. I modified the script to remove the “—–” lines after every match and prepends rm to all file names, so that I can direct the output to a .bat file and remove the common files.

Usage:

perl findDupeFiles.pl '.aif|.aiff' AAA BBB CCC > rm.bat

No Comments »

How to add “Command Prompt Here” to Nautilus/Gnome?

November 6th, 2009 | by | technology

Nov
06

Command Prompt Here: Windows developers are familiar with the tiny utility “Command Prompt Here” which allows them to open the command prompt from the windows explorer, with the working directory set to the current directory selected in the windows explorer. This PowerToy adds an “Open Command Window Here” context menu option on file system folders, giving you a quick way to open a command window (cmd.exe) pointing at the selected folder.

Open Gnome-Terminal Here

Linux and Gnome are open source software which allows great deal of options for users, to control and customize it as per their needs. Nautilus is the default file manager for Gnome, and it allows easy customization of the user interface.

Open Gnome-Terminal Here will adds an “Open Gnome-Terminal Here” context menu option on file system folders, giving you a quick way to open a gnome-terminal pointing at the selected folder. It will open gnome-terminal with the working directory set to the current directory selected in nautilus.

Installation

You need to install the Nautilus actions. Nautilus actions is an extension for Nautilus, the gnome file manager. It allow to configure program to be launch on files selected into Nautilus interface. Each time you right-click on one or several selected files in nautilus, nautilus-actions will look at its configured actions to see if a program has been setup for this selection. If it is the case, it will add an item in the menu that allow you to execute the program on the selected files.

sudo apt-get install nautilus-actions

You can also install the Nautilus actions using the Synaptic Package Manager.

Adding a new Item

Run the Nautilus actions from the System » Preferences » Nautilus Actions Configuration and add a new action item to the Nautilus context menu.

Nautilus Actions

Set the Label as: “Open Gnome-Terminal Here” for the Nautilus menu item, also give the Path as: “gnome-terminal” and Parameters as: “–working-directory=%d/%f“. The parameters for the gnome-terminal can be check in the man pages for the gnome-terminal. %d is the base directory and %f is the folder name of the selected folder in the Nautilus file manager.

Adding a new Nautilus Actions Item

Nautilus actions has a lot of parameter condition legends, so that you have fine control over the Nautilus context menu customization.

Nautilus Actions Parameters Legend

In the Conditions tab, for the “Appear if selection contains“, select the “Only folders” checkbox.

Nautilus Actions Appearance Conditions

The result

Now navigate to some folder in the Nautilus file manager and Right click on any folder, or in the free space in the Nautilus file manager, and you will see the new menu item: “Open Gnome-Terminal Here“. When you choose that menu item, the gnome-terminal will be launched with the working directory set to the current selected folder in the Nautilus file manager.

Nautilus Actions Context Menu Item

Alternatives

The same functionality can be achieved using nautilus-open-terminal package:

sudo apt-get install nautilus-open-terminal

References

No Comments »

Run Commands Effectively in Linux

November 6th, 2009 | by | technology

Nov
06

There are various ways to launch applications and run commands in Linux. Which method is best is a matter of personal taste and individual productivity needs. Here I will discuss some of the best methods available in Linux to do the common quotidian tasks easier and faster.

Command Prompt

The basic method of running commands is through the gnome-terminal, i.e. the command prompt in the Windows language. To run gnome-terminal, just press ALT+F2, type “gnome-terminal” and press the enter key.

gnome-terminal

Similarly, you can run other applications, like “gnome-system-monitor” the task manager equivalent of windows, “gnome-control-center” the control panel equivalent of windows, by using the Run Application dialog box. In the terminal window, you can run any command, redirect the output to a file, run commands from command history, etc.

n>&m – Swap Standard Output and Standard Error

You can redirect the output of a console application to any file descriptor like:

command > output.txt

This will create a new file and send the output to that file.
If you want to append the output to an existing file, like your logs file:

command >> logs.txt

By default the output (cout) goes to the file and the error (cerr) goes to the screen, by using this way.
But there may be situation where you want to run your program automatically and logs all standard error to a file and discard the standard output, means send the error to a file and normal output to the screen. In the Bourne shell you can do that using redirection.

command 2> errorlogs.txt

File descriptors 0 means standard input, 1 means standard output and 2 means standard error. There are other file descriptors from 3 to 9 used as temporary descriptors.
When using pipes, you need different way, as pipes doesn’t have names. You can say point 2 to where 1 is pointing, like:

command 2>&1 |

This means send the standard error to where the standard output is going.
To swap the standard output and the standard error you need to say:

command 3>&2 2>&1 1>&3 |

Think this as swapping a and b using temporary temp:

temp = b;
b = a;
a = temp;

Command History

Command Description
history List the last 16 commands
history -c Clears the commands history
fc -l 20 30 List commands 20 through 30
fc -l -5 List the last five commands
fc -l cat List the last command beginning with cat
fc -ln 5 > doit Save command 5 to file doit
fc -e vi 5 20 Edit commands 5 through 20 using vi
fc -e emacs Edit previous command using Emacs
!! Reexecute previous command
!cat Reexecute last cat command
!cat foo-file Reexecute last command, adding foo-file to the end of the argument list
!N Reexecute Command number N in history list.
!-N Reexecute Nth command back from current command.
!$ Last argument of previous command.

Command Alias

You can also define command short aliases by adding the alias in the ~/.bashrc file.

gedit ~/.bashrc

and add a line as:

alias ll='ls -l'
alias sysmon='gnome-system-monitor'
alias ins='sudo apt-get install'

You can also run the alias command in the terminal window to create an alias for that session only:

alias h='history'
unalias h

You can also use variables in the aliases like:

alias cdo="cd \"\$OLDPWD\""

Note: it is important, that there are ONLY double quotes in the expression above, no single quotes like in the other examples!

Global Hotkeys

You can also create hotkeys for the most commonly used programs by following the steps:

  • Launch gconf-editor by typing in a terminal: gconf-editor.
  • In gconf-editor choose apps » metacity » global_keybindings.
  • In global_keybindings assign keyboard shortcuts.

    Assign keys for global keybindings

  • Select keybinding_commands (right below global_keybindings in the metacity menu).
  • In keybinding_commands assign the custom commands you would like to launch with the keyboard shortcuts you created in step three.

    Assign application to global keybindings

Gnome-do

You can use gnome-do, this is similar to QuickSilver (Mac) or Launcy/wxQuickRun (Windows). Install the program and the plugins using the Synaptic Package Manager.

gnome-do

Just launch the program, and press “Win/Command key + Space Bar” and type your commands. Use the arrows keys for selecting various items, and the tab key to move to a different pane. You can also download additional plugins from the gnome-do repository and copy them to “~/.local/share/gnome-do/plugins“.

Dock Window

Ever like the cool Mac GUI effects and the docking window to launch your favorite application without searching through the maze of menus. Well now we have lots of docking managers for Linux also namely: Avant Window Navigator, Cairo Dock, wbar, etc.

Avant Window Navigator

wbar

You can also imitate OSX GUI in your Linux desktop, by changing the Gnome themes.

Gnome Desktop

SUSE Linux Favorite Application

SUSE Linux Enterprise Desktop 10 uses a desktop menu to help you launch applications. This menu has three sections: Favorite Applications, Recently Used Applications, and Recent Documents. You can add or remove any application to your favorite application section. This allows easy access to the commonly used application.

SUSE Linux Favorite Application

References

No Comments »

Detect & Install .NET 3.5 Framework using Inno Setup.

November 6th, 2009 | by | technology

Nov
06

In this article, we would see how to detect whether the .NET Framework is present or not, and how to install the .NET Framework automatically from the internet (Microsoft Website), if its already not present. The installation won’t continue, until the .NET Framework is installed. This article is basically a modification of the script at http://www.blackhillsoftware.com/blog/2006/06/26/using-innosetup-with-the-dotnet-framework/ and uses information from the Microsoft .NET Framework 3.5 Deployment Guide for Application Developers, to detect the .NET Framework 3.5 version.

Below is the INNO Setup script to detect and install the .NET 3.5 Framework. If you want some other version of .NET Framework, to be detected and installed automatically, just change the registry values to search and the dotnetRedistURL value to download that .NET Framework. To know about the exact registry values and keys to be used for detection of a particular version of .NET, you can read the article: Using managed code to detect what .NET Framework versions and service packs are installed.

 

Framework Version Registry Key
.NET Framework v1.1 HKLM\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322\Install
.NET Framework v2.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\Install
.NET Framework v3.5 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Install

All of these values are a DWord value, so if it is present and set to 1, then that version of the Framework is installed.

 

Framework Version Download URL
.NET Framework v1.1 http://download.microsoft.com/download/a/a/c/aac39226-8825-44ce-90e3-bf8203e74006/dotnetfx.exe
.NET Framework v2.0 http://download.microsoft.com/download/5/6/7/567758a3-759e-473e-bf8f-52154438565a/dotnetfx.exe
.NET Framework v3.5 http://download.microsoft.com/download/7/0/3/703455ee-a747-4cc8-bd3e-98a615c3aedb/dotNetFx35setup.exe

Please note that these are temporary download URL and subject to change by Microsoft, also these download are for normal Windows 32 bit architecture.

[_ISTool]
EnableISX=true

[Files]
Source: C:\Program Files\ISTool\isxdl.dll; Flags: dontcopy

[Code]
var
 dotnetRedistPath: string;
 downloadNeeded: boolean;
 dotNetNeeded: boolean;
 memoDependenciesNeeded: string;

procedure isxdl_AddFile(URL, Filename: PChar);
external 'isxdl_AddFile@files:isxdl.dll stdcall';
function isxdl_DownloadFiles(hWnd: Integer): Integer;
external 'isxdl_DownloadFiles@files:isxdl.dll stdcall';
function isxdl_SetOption(Option, Value: PChar): Integer;
external 'isxdl_SetOption@files:isxdl.dll stdcall';

const
  dotnetRedistURL = 'http://download.microsoft.com/download/7/0/3/703455ee-a747-4cc8-bd3e-98a615c3aedb/dotNetFx35setup.exe';

function InitializeSetup(): Boolean;
var
  IsInstalled: Cardinal;
begin
  Result := true;
  dotNetNeeded := true;

  // Check for required netfx installation
  if(Is64BitInstallMode()) then begin
   if (RegValueExists(HKLM, 'SOFTWARE\Wow6432Node\Microsoft\NET Framework Setup\NDP\v3.5', 'Install')) then begin
    RegQueryDWordValue(HKLM, 'SOFTWARE\Wow6432Node\Microsoft\NET Framework Setup\NDP\v3.5', 'Install', IsInstalled);
    if(IsInstalled = 1) then begin
     dotNetNeeded := false;
     downloadNeeded := false;
    end;
   end;
  end
  else begin
   if (RegValueExists(HKLM, 'SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5', 'Install')) then begin
    RegQueryDWordValue(HKLM, 'SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5', 'Install', IsInstalled);
    if(IsInstalled = 1) then begin
     dotNetNeeded := false;
     downloadNeeded := false;
    end;
   end;
  end;

  if(dotNetNeeded) then begin
   if (not IsAdminLoggedOn()) then begin
    MsgBox('My Application needs the Microsoft .NET 3.5 Framework to be installed by an Administrator.', mbError, MB_OK);
    Result := false;
   end
   else begin
    dotnetRedistPath := ExpandConstant('{src}\dotnetfx.exe');
    if not FileExists(dotnetRedistPath) then begin
     dotnetRedistPath := ExpandConstant('{tmp}\dotnetfx.exe');
     if not FileExists(dotnetRedistPath) then begin
      isxdl_AddFile(dotnetRedistURL, dotnetRedistPath);
      downloadNeeded := true;
     end;
    end;
   end;
  end;
end;

function NextButtonClick(CurPage: Integer): Boolean;
var
  hWnd: Integer;
  ResultCode: Integer;
begin
  Result := true;

  if CurPage = wpReady then begin
  hWnd := StrToInt(ExpandConstant('{wizardhwnd}'));

  // don't try to init isxdl if it's not needed because it will error on < ie 3
  if (downloadNeeded) then begin
   isxdl_SetOption('label', 'Downloading Microsoft .NET 3.5 Framework');
   isxdl_SetOption('description', 'My Application needs to install the Microsoft .NET 3.5 Framework. Please wait while setup is downloading extra files to your computer.');
   if isxdl_DownloadFiles(hWnd) = 0 then Result := false;
   end;
   if (Result = true) and (dotNetNeeded = true) then begin
    if Exec(ExpandConstant(dotnetRedistPath), '/q /norestart', '', SW_SHOW, ewWaitUntilTerminated, ResultCode) then begin
     // handle success if necessary; ResultCode contains the exit code
     if not (ResultCode = 0) then begin
      Result := false;
     end;
    end
    else begin
     // handle failure if necessary; ResultCode contains the error code
     Result := false;
    end;
   end;
  end;
end;

No Comments »