posts - 4, comments - 12, trackbacks - 0

My Links

News

Archives

Wednesday, November 02, 2011

Using iTextSharp to correctly display Hebrew / Arabic text (Right to Left) in a PDF Document

 

Introduction

iTextSharp is a useful library for creating PDF documents in .Net. However because of the right to left nature of Hebrew and Arabic texts, adding them to the document normally through iTextSharp renders them unreadable.
Lets take a look at how we can solve this problem.

Download iTextSharp here

Please read the comments to guide you through the code.

Code

using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Text.RegularExpressions;
using System.IO;
using System.Diagnostics;

public void WriteDocument()
{
  
//Declare a itextSharp document
    Document document = new Document(PageSize.A4);

    //Create our file stream and bind the writer to the document and the stream
    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(@"C:\Test.Pdf", FileMode.Create));

    //Open the document for writing
    document.Open();

   //Add a new page
    document.NewPage();

    //Reference a Unicode font to be sure that the symbols are present.
    BaseFont bfArialUniCode = BaseFont.CreateFont(@"C:\ARIALUNI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    //Create a font from the base font
    Font font = new Font(bfArialUniCode, 12);

    //Use a table so that we can set the text direction
    PdfPTable table = new PdfPTable(1);
    //Ensure that wrapping is on, otherwise Right to Left text will not display
    table.DefaultCell.NoWrap = false;

    //Create a regex expression to detect hebrew or arabic code points
    const string regex_match_arabic_hebrew = @"[\u0600-\u06FF,\u0590-\u05FF]+";
    if (Regex.IsMatch("מה קורה", regex_match_arabic_hebrew, RegexOptions.IgnoreCase))
    {
        table.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
    }

    //Create a cell and add text to it
    PdfPCell text = new PdfPCell(new Phrase("מה קורה", font));
    //Ensure that wrapping is on, otherwise Right to Left text will not display
    text.NoWrap = false;

    //Add the cell to the table
    table.AddCell(text);

    //Add the table to the document
    document.Add(table);

    //Close the document
    document.Close();

    //Launch the document if you have a file association set for PDF's
    Process AcrobatReader = new Process();
    AcrobatReader.StartInfo.FileName = @"C:\Test.Pdf";
    AcrobatReader.Start();

}

Conclusion

We used a regex expression to detect if the text was Hebrew or Arabic and then set the .RunDirection of the PdfpTable or PdfPCell accordingly.
Ensure that .NoWrap is set to false on the default cell of the table and any cells that you may create manually, if wrapping is turned off the right to left text will not be displayed.

Posted On Wednesday, November 02, 2011 4:10 AM | Feedback (5) |

Thursday, March 31, 2011

Configuring dotNetInstaller 2.0 to install custom prerequisites and then run a custom exe with elevated privileges.

Introduction

I recently came across a handy tool that can be used as a setup bootstrapper for windows. Its called dotNetInstaller and can be found at http://dotnetinstaller.codeplex.com/.

This tool allows the user to distribute a single compressed, executable packaged setup with all the pre-requisites. It is very customisable.

For the purposes of demonstration i will use the scenario that we encountered with our software distribution:
We have 4 pre-requisites that need to be checked and installed if the check fails. All pre-requisites must be installed before our final exe can be run.

Pre-requisites:

  1. Windows Installer 3.1
  2. Windows Imaging Component
  3. Microsoft .Net Framework 3.5 SP1
  4. Microsoft .Net Framework 4.

Steps Involved

  1. Download dotNetInstaller 2.0
  2. Create a new setup configuration
  3. Add all the necessary components, checks etc.
  4. Run a Custom Executable
  5. Build the bootstrapper.
  6. Test

1 Download dotNetInstaller 2.0

It can be downloaded at http://dotnetinstaller.codeplex.com/.
Note that at the time of this post 2.0 is in Beta testing, however it is available for download under the “Next Release” section near the bottom of the page.

2 Create a new setup configuration

  • Run the InstallerEditor.exe, located in the dotNetInstaller folder.
  • Create a new project from the File menu. File –> New.
  • Be sure to select the config file and edit the settings on the right hand side. Settings to note here would be the “log_enabled” which should be set to “True” to track the progress of your installer.
  • Add in a new setup configuration by right clicking on the “Config File” on the left hand side. Add –> Configurations –> Setup Configuration.

addconfig_thumb[4]

 

  • Select the “install”and edit the settings on the right hand side.
    • Change “APPLICATION_NAME” text to the name of your application
    • Under the “Runtime” section set the “administrator_required” to “True” (this will allow dotNetInstaller to elevate components if need be).

3 Add all the necessary components, checks etc..

  • To add a component, which would for example be a pre-requisite that needs to be installed, right click on the “install” setup configuration. Add –> Components –> Exe Component (you would choose the option that matches the type of component you want to install).
  • One Of our Components is “Windows Imaging Component”

addcomponent_thumb[2]

  • Once you have added a component select the component in the list and edit the settings on the right and side.
    • Add in names for “display_name” and “id”. (these can be the same)
    • Under the “Install” section fill in the path of the “executable”. for example "#APPPATH\presetup\wic_x86_enu.exe" /norestart /quiet
      • “#APPPATH” is the directory from which this bootstrapper will be run
      • “wic_x86_enu.exe” is the name of our Windows Imaging Component executable.
      • “/norestart /quiet” are the parameters that the executable will run with.
    • Under “Operating System” set the “os_filter_max” and “os_filter_min”
      • In our case windows imaging component will already be installed on Windows Vista and later. so we have :
        • “os_filter_max” as winServer2003Max
        • “os_filter_min” as win95
    • Set the reboot options under the “Runtime section” for this case I have set all the reboot options to “False” except for the last pre-requisite i have set the “must_reboot_required” to True. This will notify the user that they have to restart before the setup will continue.
    • Under “Return Codes”, if the pre-requisite would usually require the user to restart then put in the return code “3010” under the “returncodes_reboot” section. When the installation of this component ends, and would usually request a restart with that return code, it will now instead notify dotNetInstaller that the component was successfully installed.
  • Add in a check to the component. For many of the pre-requisite components we may want to check if they are already installed. dotNetInstaller offers many different types of checks. for the “Windows Imaging Component” we want to do a file check.
  • Right click on the “Windows Imaging Component”. Add –> Checks –> Installed Check File.
checkcomponent_thumb[3]
    • Click on the check and edit some of the properties.
      • “filename” should be where the file is located that you would like to check. in this instance “#SYSTEMPATH\WindowsCodecs.dll”
        • “#SYSTEMPATH” is the “Windows\System32” folder.
      • “comparison” allows you to specify the type of check you would like to do, “exists” or one of the version options. which would match against the “fileversion” field.
  • Once you have configured a component you can add multiple other components and checks.

4 Run a Custom Executable.

It is possible to run a custom executable / command as a component however after running the executable dotNetInstaller does not know how to evaluate that it was successfully run and execute the complete command. To circumvent this we can embed a file that will be extracted to a folder (random GUID) each time the installer runs.

  • Right click on the component for your custom executable / command. Add –> Embed –> Embedded File.

embedFile_thumb[5]

  • Set the “sourcefilepath” of your file to “#APPPATH\checkpoint.txt”. and make sure its located in the same directory as the “InstallerEditor.exe” when we create our bootstrapper
  • Once you have added an embedded file. Add in a check as we did with the “Windows Imaging Component” to check if the file exists. If this file exists then dotNetInstaller will know that your executable ran correctly.
  • Note that the path for the “filename” should be #CABPATH\checkpoint.txt (where checkpoint.txt is the name of our blank txt file that is used for checking purposes).
  • By default under the “install” –> “self-extracting CAB” – > “cab_path” will have the value of “#TEMPPATH\#GUID”. Note that this value is the value indicated by #CABPATH above.

5 Build the bootstrapper.

  • Before creating our bootstrapper executable, we should save this file as “Configuration.xml”
  • Because we want our bootstrapper to be able to resume after start-up we do not want it to run with elevated privileges by default otherwise UAC will block it from resuming on start-up.
  • By Default the executable will be compiled with a manifest that elevates the privileges to administrator. We will create and specify our own manifest.
    • Create a new .txt file and change the extension to “.manifest”. It should contain the following:
    • <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
      <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
        <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
          <security>
            <requestedPrivileges>
              <requestedExecutionLevel level="asInvoker" uiAccess="false" />
            </requestedPrivileges>
          </security>
        </trustInfo>
        <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
          <application>
            <!-- Windows Vista -->
            <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"/>
            <!-- Windows 7 -->
            <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>
          </application>
        </compatibility>
      </assembly>

    • Notice the line
    •    <requestedExecutionLevel level="asInvoker" uiAccess="false" />
      Here we see that the execution level has been set to “asInvoker” instead of “requireAdministrator”
  • Create an icon and a banner image (recommended size 110 X 208 px).
  • Go to File –> Create Exe you will see the following window.

createEXE_thumb[2]

  • Select the relevant files that you have created and click on “Make”

6 Test

Test your installation in a Clean Virtual Machine to ensure that you obtain the desired behaviour.

Posted On Thursday, March 31, 2011 12:03 AM | Feedback (5) |

Sunday, March 06, 2011

Dev4Dev’s March 2011 – User Interface Design

For all who attended my talk on User Interface Design. Here are the slides.

User Interface Design Slides

Posted On Sunday, March 06, 2011 8:08 PM | Feedback (0) |

Saturday, February 19, 2011

Automating the Backup of a SQL Server 2008 Express Database

Steps Involved:

1) Create a Database Backup Script.

2) Create a Scheduled Task To Run the Backup Script.

1 Create a Database Backup Script.

a) Download and install SQL Server Management Studio. This is a free tool available on the Microsoft website.

b) Once Management Studio is installed launch it and connect to the SQL server instance that contains the database that you want to back up.

c) Right click on the database and then in the menu choose Tasks -> Back up...

d) This will open up a window where you can choose your backup options, once you are happy with the options click on the "Script" button near the top and select the "Script Action to File" option.

e) Save the File.

2 Create a Schedule Task to Run the Backup Script

a) Open up Windows Task Scheduler.

b) Create a new Task using the wizard, when asked to select a program browse to C:\Program Files\Microsoft SQL Server\100\Tools\binn\SQLCMD.exe

c) There are 2 arguments that need to be set: -S \SERVER_INSTANCE_NAME  -i "PATH_OF_SQLBACKUP_SCRIPT"
where SERVER_INSTANCE_NAME  is the name of the instance of SQL server that contains your database e.g. (local) and PATH_OF_SQLBACKUP_SCRIPT is the path of your backup script e.g. "C:\Program Files\Microsoft SQL Server\DatastoreBackup.sql"

d) Adjust the task to run at the desired times and you are done.

Posted On Saturday, February 19, 2011 8:30 AM | Feedback (2) |

Powered by: