Tuesday, February 24, 2009

Nullsoft Scriptable Install System (NSIS)

I have been using Visual Studio’s ‘Setup Project’ template for creating Windows installers to install my applications on a Windows computer. It’s pretty straight forward and easy, but gets a bit complicated when we need to do something more advanced. I knew there were things like InstallShield but they cost money.

Recently I was introduced to a new tool named as Nullsoft Scriptable Install System (NSIS). It’s completely free, and is a professional open source system to create Windows installers. It is driven by scripts (using a custom language) and offers a myriad of built-in features and functions covering all the basic installer necessities, from layout of install wizard dialogs, to manipulating files and registry keys.

Installing NSIS is very easy. Go to its home page at http://nsis.sourceforge.net and download the latest version. I used 2.43.

There are two types of installers that can be created using NSIS. The simple one is based on zip file. You package all your files into a single zip file and then feed it to the NSIS (Main Menu > Compiler > Installer based on ZIP file).

Zip2Exe It will generate a setup exe which the end user can execute to copy your files into a specified directory.

Zip2ExeSetup

The next option is the more powerful and flexible one. You create a NSIS script file (which is just a text file with extension as .nsi) with all the details of the installer like how many navigation pages it should have, what files need to be copied, and what values to be added to registry, etc. All these are specified through NSIS's own script language which is fairly easy to learn.

Once the script is ready and all the required files mentioned in the script are placed at the proper folders, you can right click on the script file and choose 'Compile NSIS Script' option. NSIS will then compile this script and will create a single setup exe file.

Now let us see the internals of such a script file. In this example, I am creating a Windows installer for my free software tool SQL Analyzer.

[Remember to get a fine text editing tool such as Notepad++ which has line number support and syntax highlighting for NSIS].

Initially I am defining some constants using the !define keyword. These are some string constants that will be used later on.

!define PRODUCT_NAME "SQL Analyzer"
!define PRODUCT_VERSION_MAJOR 7
!define PRODUCT_VERSION_MINOR 0
!define PRODUCT_DISPLAY_VERSION "7.0"
!define PRODUCT_PUBLISHER "Coolwayfarer"
!define PRODUCT_WEB_SITE "http://www.codeplex.com/sqlanalyzer"
!define PRODUCT_UNINST_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}" ; 
!define PRODUCT_UNINST_ROOT_KEY "HKLM"
!define PRODUCT_INSTALL_DIR "$PROGRAMFILES\SQL Analyzer"

Anything that comes after a $ sign is a predefined constant or variable. For example $PROGRAMFILES will translate into the user’s program files folder (typically C:\Program Files\).

Next we need to specify what compression technique we are using and what kind of user interface is required for the installer.

SetCompressor /SOLID lzma
!include "MUI2.nsh"

Here I am using the lzma. Don’t worry about that, it gives maximum compression. I also include a header file (you don’t need to get a copy of that file to include it) for the settings for Modern UI 2 (MUI2) which is the latest version of a user interface in a wizard style.

Next, the settings for the installer interface are specified.

!define MUI_ABORTWARNING
!define MUI_ICON "resources\sqlanalyzer.ico"
!define MUI_UNICON "resources\sqlanalyzer.ico"
!define MUI_HEADERIMAGE
!define MUI_HEADERIMAGE_BITMAP "resources\sqlanalyzerheader.bmp"
!define MUI_HEADERIMAGE_RIGHT
!define MUI_HEADER_TRANSPARENT_TEXT
!define MUI_WELCOMEFINISHPAGE_BITMAP "resources\sqlanalyzerwelcome.bmp"
!define MUI_WELCOMEFINISHPAGE_BITMAP_NOSTRETCH

As you can see, things like MUI_ICON are predefined properties/settings. Here I have specified an icon for the installer and two images, one for the header and another one for the welcome page. Note that the files are put in a relative path to the script file.

Now the different wizard pages in the installer are specified.

; Welcome page
!insertmacro MUI_PAGE_WELCOME

; License page
!define MUI_LICENSEPAGE_CHECKBOX
!insertmacro MUI_PAGE_LICENSE "resources\license.txt"

; Instfiles page
!insertmacro MUI_PAGE_INSTFILES

; Finish page
!define MUI_FINISHPAGE_SHOWREADME "$INSTDIR\README.txt"
!define MUI_FINISHPAGE_NOREBOOTSUPPORT
!insertmacro MUI_PAGE_FINISH

; Uninstaller pages
!insertmacro MUI_UNPAGE_INSTFILES

; Language files
!insertmacro MUI_LANGUAGE "English"

Anything that starts with a semicolon is a comment. So I have pages like Welcome page, license page, etc. defined here. Note that in the finish page, I have an option specified to show readme file and it points to the file README.txt in the installed location ($INSTALLDIR). We will see in a moment that as part of our installation, we are copying this file as well.

Now we specify some basic settings for the installer itself.

Name "${PRODUCT_NAME}"
OutFile "${PRODUCT_NAME} Setup.exe"
InstallDir "${PRODUCT_INSTALL_DIR}"
ShowInstDetails show
ShowUnInstDetails show
BrandingText "${PRODUCT_PUBLISHER}"
RequestExecutionLevel admin

We are making use of the constants we defined earlier here to specify things like the installer file (OutFile: which will be now ‘SQL Analyzer Setup.exe’).

Now the settings are complete and we need to define the actions during the installation. This is done by defining a section with some name.

Section "MainSection" MainSection
;Action goes here...
SectionEnd

Within this section, first we need to set the out path (which is the installation directory) and then copy all the required files to this path.

SetOutPath "$INSTDIR"
SetOverwrite ifnewer

;Copy files
File "/oname=sqlanalyzer.ico" "resources\sqlanalyzer.ico" ;Binary of the application.
File "/oname=SQLAnalyzer.exe" "files\SQLAnalyzer.exe" ;Binary of the application.
File "/oname=sqlanalyzer.gif" "files\sqlanalyzer.gif" ;A sample screen shot.
File "/oname=README.txt" "files\README.txt" ;Readme file.
File "/oname=RICHTX32.OCX" "files\RICHTX32.OCX" ;Required OCX control: Rich Text Box.
File "/oname=COMDLG32.OCX" "files\COMDLG32.OCX" ;Required OCX control: Common Dialog. 
File "/oname=MSFLXGRD.OCX" "files\MSFLXGRD.OCX" ;Required OCX control: Flex Grid.

Next, I am registering the dependent OCX controls and creating Start Menu shortcuts.

;Register the OCX controls.
Exec 'regsvr32 "$INSTDIR\RICHTX32.OCX" /S'
Exec 'regsvr32 "$INSTDIR\COMDLG32.OCX" /S'
Exec 'regsvr32 "$INSTDIR\MSFLXGRD.OCX" /S'

;Create Start Menu folders and shortcuts.
CreateDirectory "$STARTMENU\Programs\${PRODUCT_NAME}"
CreateShortCut "$STARTMENU\Programs\${PRODUCT_NAME}\${PRODUCT_NAME}.lnk" "$INSTDIR\SQLAnalyzer.exe"
CreateShortCut "$STARTMENU\Programs\${PRODUCT_NAME}\README.lnk" "$INSTDIR\README.txt"
CreateShortCut "$STARTMENU\Programs\${PRODUCT_NAME}\Sample.lnk" "$INSTDIR\sqlanalyzer.gif"
CreateShortCut "$STARTMENU\Programs\${PRODUCT_NAME}\Uninstall.lnk" "$INSTDIR\Uninstall.exe"

;Create uninstaller
WriteUninstaller "$INSTDIR\Uninstall.exe"

Any external tool can be used using the Exec keyword. If you need to run your own custom tool as part of installation, first copy that tool and then use this command. NSIS can create an uninstaller automatically using the keyword WriteUninstaller.

If we need this product to appear on Windows installed programs list (Add/Remove Programs), then we need to write a registry entry as below.

WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "DisplayName" "${PRODUCT_NAME}"
WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "UninstallString" "$INSTDIR\Uninstall.exe"
WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "DisplayIcon" "$INSTDIR\sqlanalyzer.ico"
WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "DisplayVersion" "${PRODUCT_DISPLAY_VERSION}"
WriteRegDWORD ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "VersionMajor" "${PRODUCT_VERSION_MAJOR}"
WriteRegDWORD ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "VersionMinor" "${PRODUCT_VERSION_MINOR}"
WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "URLInfoAbout" "${PRODUCT_WEB_SITE}"
WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "Publisher" "${PRODUCT_PUBLISHER}"

We are almost done and only thing left now is to instruct NSIS on what to do while the uninstaller is executed. Well, we need to remove whatever files we have copied, directories and shortcuts we have created, and registry entries we have made. This is specified in a section named Uninstall as below.

Section "Uninstall"
;Unregister the OCX controls.
Exec 'regsvr32 -u "$INSTDIR\RICHTX32.OCX" /S'
Exec 'regsvr32 -u "$INSTDIR\COMDLG32.OCX" /S'
Exec 'regsvr32 -u "$INSTDIR\MSFLXGRD.OCX" /S'

;Delete all the files
Delete "$INSTDIR\sqlanalyzer.ico"
Delete "$INSTDIR\SQLAnalyzer.exe"
Delete "$INSTDIR\sqlanalyzer.gif"
Delete "$INSTDIR\README.txt"
Delete "$INSTDIR\RICHTX32.OCX"
Delete "$INSTDIR\COMDLG32.OCX"
Delete "$INSTDIR\MSFLXGRD.OCX"
Delete "$INSTDIR\Uninstall.exe"

;Remove the installation folder.
RMDir "$INSTDIR"

;Remove the Shortcuts
Delete "$STARTMENU\Programs\${PRODUCT_NAME}\${PRODUCT_NAME}.lnk"
Delete "$STARTMENU\Programs\${PRODUCT_NAME}\README.lnk"
Delete "$STARTMENU\Programs\${PRODUCT_NAME}\Sample.lnk"
Delete "$STARTMENU\Programs\${PRODUCT_NAME}\Uninstall.lnk"
RMDir /r "$STARTMENU\Programs\${PRODUCT_NAME}"

;Remove the entry from 'installed programs list'
DeleteRegKey ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}"
SectionEnd

That’s it! Now make sure that the extension of this script file is .nsi (download the complete file from here). Right click on this file from Windows Explorer and you will see an option ‘Compile NSIS Script’ if you have successfully installed NSIS.

sa9If there is any error, the compiler will inform about it specifying the line number in the script. So it is easy to fix issues. If everything went fine, the installer exe will be created at the same location.

Now let us see how the installer interface looks like with the settings in the script file.

sa1This is the first welcome screen. The image on the left is the onwe we specified with ‘sqlanalyzerwelcome.bmp’.

sa2Here in the second page the license from a text file is displayed. The ‘Install’ button will be enabled only when  ‘I accept…’ checkbox is checked.

sa3 This screen shows the progress of the installation.

sa4 This is the final page with an option to show Readme file. After the installation, the Start Menu shortcuts are created as below.

sa5The product will also be listed under ‘Add/Remove Programs’

sa6Now on clicking the Uninstall button, the uninstaller will get executed and will remove all the changes we have done.

sa7

You can download all the files and the script as a zip from here or just try out the installer from here. Let me know if this article helped you and feel free to post any questions you may have. Remember to first check out the tutorial and documentation on NSIS site which is very detailed.

Thursday, November 27, 2008

Windows Live Writer Plugin Development

Windows Live Writer is a cute small free blog publishing desktop application. If you are tired of the browser based tools to post your blogs, you must try Writer where you can create rich content posts offline and then publish to your blog hosting server when you are online.
lwplugin0
Windows Live Writer can be easily installed by double clicking the downloaded WLinstaller.exe file. To The initial wizard during the startup will help to configure to an existing blog or to create a new blog. There are no other additional configurations or settings involved.
Plugins helps in extending the capabilities of Writer to insert, edit, and publish new types of content. It is very easy to develop a plugin if you are a .NET developer. For the plugin development no separate SDK is required as all the APIs comes with the installation and will be available in the installation folder typically at C:\Program Files\Windows Live\Writer.
lwplugin4
lwplugin1
lwplugin2
lwplugin3
There are two types of content source plugins a) Simple (inserts custom html) and b) Smart (inserts custom html with editing options).
Content created by both simple and smart content sources can originate from an Insert dialog box, a URL, or Live Clipboard data. Each content source plugin can support creating content from one or all of these contexts.
In this post, we will see how we can develop a Simple Content Source Plugin through Insert Dialog Box. You can use Visual Studio 2008 or 2005 or 2003.
  • Launch Visual Studio and start a new Class Library Project in C#.
  • Add a reference to the WindowsLive.Writer.Api assembly (located in the directory C:\Program Files\Windows Live\Writer).
  • Create a new class derived from ContentSource base class from this API.
  • Apply the WriterPluginAttribute to the new class that will define the plugin properties. (Use a new GUID to identify this plugin. If an image is specified in the attribute, add this image as an embedded resource to the project. The publisher URL and description will appear in the Plugins options in Writer).
  • Apply the InsertableContentSourceAttribute to the new class that will define the plugin content. This will appear as the menu name under Insert menu.
  • Override the CreateContent method and code the required functionality there.
  • Add a Post Build event to the project to copy plugin dll to the Writer plugins directory after it is built (XCOPY /D /Y /R "$(TargetPath)" "C:\Program Files\Windows Live\Writer\Plugins\").
  • Build the project and then run Windows Live Writer to test and debug. New plugin will appear under Insert menu.
The complete code snippet for a hello world plugin is given below:
using System.Windows.Forms;
using WindowsLive.Writer.Api;

namespace LiveWriterPlugin
{
[WriterPluginAttribute
("8CFEFA0C-6366-419f-9590-20A6590728DC",
"My Sample Plugin",
ImagePath = "mypluginimage.png",
PublisherUrl = "http://ctlabs.blogspot.com",
Description = "A sample plugin that can insert hellow world in your blog posts")]

[InsertableContentSourceAttribute("My Sample Plugin Content")]
public class MyPlugin: ContentSource
{
public override DialogResult CreateContent(IWin32Window dialogOwner, ref string newContent)
{
DialogResult result = MessageBox.Show("Do you want to insert this sample content?","My Plugin",MessageBoxButtons.OKCancel);

if (result == DialogResult.OK)
{
newContent = "Hello World from Plugin";
}

return result;
}
}
}

That's it. Look at the above images to see this plugin in action. Happy plugin development!

Thursday, November 06, 2008

Innovation Days Again At Kochi

It was just 5 months back we had an Innovation Days event at Kochi from Microsoft. Seeing the great response from the IT enthusiasts at Kochi, Microsoft has come back today with yet another session packed event. This time the location was at Taj Residency at Marine Drive.  Kochi techies showed their interest by turning up in large numbers, making it a house-full event.

The day started with a keynote address from Vikram Rajkondawar, Architect Advisor at Microsoft (India). He spoke in detail about the Software + Services mantra Microsoft is transitioning to, and clarified myths around Cloud computing and briefly explained Windows Azure and other latest technologies. There was a Live Mesh demo that showed connected devices (two laptops and a mobile) synchronizing files between them.

The session on SQL Server performance issues by Praveen was in-depth as he discussed internals of SQL Server and how a query is parsed, algebrized and optimized before execution. He did mention that from SQL Server 2005 onwards it doesn’t matter if you are using stored procedures or inline SQL queries as both gives similar results on a performance point of view.

Nahas Mohammed did a short session on Internet Explorer 8 and demonstrated its new features like Accelerators and Web Slices.

Chandrashekar’s session on .NET debugging tools helped in understanding some of those rarely used, but highly useful debugging tools like Fusion Log Viewer (fuslogvw.exe), NGen, SoS.dll, ILDAsm, ILAsm, and Managed Debugging Assistance (MDA).

Praveen concluded the event with a session on Rich Internet Applications (RIA) and spoke about ASP.NET MVC, AJAX, jQuery integration and Silverlight.

Between the technical tracks, there was a short session on Innovate On partnership program that Microsoft launched last time. A guy from TIE (The IndUs Entrepreneurs) spoke about their institution and inspired us to think on entrepreneurship.

There were lots of goodies (T-Shirts, books) given out besides a great lunch. I enjoyed the overall event and could meet many friends/ex-colleagues as well as some new people from the Kochi developer community. As I had registered for the Innovate On program last time, I received my first kit containing a T-Shirt, Technology Specialist certificates, and CDs containing technical resources.

Thursday, October 30, 2008

Multi-Touch Windows 7 Application

See this video of Multi-Touch Windows 7 Application developed by IdentityMine.



Read more about it here.

Latest from Microsoft

New technology/product release spree that Microsoft seems to be in lately has come to its high with the Professional Developers Conference (PDC) 2008 concluding today at Los Angeles, USA.

It's been not very long since Microsoft has released .NET 3.0/3.5 with completely new technologies like WPF, Silverlight, WCF, and so on. Recently they released the next versions of them (Silverlight 2, and .NET 3.5 SP1) and PDC saw the announcement of Silverlight 2 Tool Kit and WPF Tool Kit.

Other Products/Technologies that were previewed at PDC include Windows 7, Windows Azure, and Visual Studio 2010 / .NET 4.0.

Windows 7 (formerly codenamed Blackcomb and Vienna) is the next version of Microsoft Windows and the successor to Windows Vista. I tried out the developer preview version of Windows 7 Ultimate (Build 6801) and found it not much different from Windows Vista in look and feel. But under the hood, it includes a number of new features, such as advancements in touch, speech, and handwriting recognition, support for virtual hard disks, improved performance on multi-core processors, improved boot performance, and kernel improvements. Read more here.

Windows Azure is Microsoft's operating system for the cloud. The Azure Services Platform combines cloud-based developer capabilities with storage, computational and networking infrastructure services, all hosted on Microsoft's servers. Read more here.

The next version of Visual Studio is 2010 with .NET Framework 4.0. Read more here.

I wonder why Microsoft is still continuing the calendar year naming for the versions of Visual Studio while they discontinued it for Windows. Anyway, as developers in Microsoft technologies, there is no end to our continuous learning and re-learning cycles.