Category: nice to know

  • Codepages

    Recently, I encountered the issue of codepages again. The problem was that the name of a Turkish city (İstanbul) was not represented correctly. Again a codepage issue. The character İ was not part of the application.

    How did these codepages come around?

    In the early days of Windows 95, we had ASCII. This had 127 different characters that were represented with 7 bit. For some network reason an additional bit was necessary which led to the situation that 8 bits (a full byte) was necessary to represent an ASCII character. The set of ASCII characters contains the normal a,b, c etc, both in lower case and upper case. This is added with numerics (0,1,2,3, ..) and signs like the question mark, comma, dot etc. We miss in the ASCII the language specific characters like È, ç characters.
    To cover for the Western European languages an additional series of 128 characters was created. The original ASCII plus the West European special characters ( È, ç) could be represented in 8 bits. Hence one byte was sufficient to display all characters in the Western European languages. This list is indicated by extended ASCII, Codepage 1252 or ISO -8859-1 or Latin1. Roughly these codepages allow us to represent West European texts like French, English, Spanish, German and Dutch.

    However if one would like to write İstanbul, one encounters the limitations of these codepages. Hence other codepages are created to represent Baltic, Turkish or Czech. In most cases the alphabets that are derived from Latin contain the original ASCII list plus a series of characters (İ, Ď ) that are specific to these languages. The idea is that one byte represents one character.
    Likewise, other languages like Russian, Hebrew and Arabic have created a list of characters whereby one byte is used to represent a character.

    However, one might run into problems if an attribute should contain both Turkish and French names. What codepage to use? To solve this a new codepage is created: the unicode. Here, roughly two bytes are used which allows to store a nearly infinite set of characters. Standard characters are represented with one byte; more exotic characters use 2, 3 or 4 characters. One might even store Japanese, Korean in unicode.

    Unicode certainly has the future. As we speak, one sees many migration documents where a ASCII codepage is migrated to unicode. I am also informed that more and more dbms recommend unicode as their default codepage.

  • PIN code

    A few days ago, I got the suggestion to protect a transaction with a PIN number. But how does that mechanism work? It looks as if this mechanism is used to describe several situations. One situation (the simplest) looks a bit like a password. On the client side, a user enters a PIN code. This PIN code is translated into another value that is sent to the server. For the moment, one may think of a multiplication of the PIN code by the daynumber. This product is sent to the server. The server undertakes a similar process. It multiplies a stored PIN code with the daynumber. If this result equals the number that is received, the entered PIN code is assumed to be entered by the authorised user. After such verification the user may proceed to the required transaction.
    Whenever the network traffic is monitored, the monitor only reveals the calculated code. Suppose the PINcode is multiplied by the daynumber, someone sees a number like 337518. If someone monitors the network with the idea to hack the protected site, such information is worthless. The hacker doesn’t know the algoritm (multiplicating the pincode by the daynumber), he can’t know what PIN code to file out. He might try to use the number 337518 as an attempted PINcode but his attempt will be rejected. From the traffic, he doesn’t get the PINcode that he needs to use.

  • Strange characters

    In some cases, you get unexpected weird results being returned from your database like: Testù�Summary. This may be expected as one inserted TestùęSummary. Apparently symbols like ę were not recognised and were subsequently translated into �.
    A likely reason is that the so-called codepage is wrong. Characters like ę are not included in the common characterset and an extended characterset (like unicode) must be used.
    Fortunately, most DBMS support the unicode. As an example, we take an example from Teradata. Look as this code:

    CREATE SET  TABLE SAN_D_FAAPOC_01.TestUnicode ,NO FALLBACK ,
    NO BEFORE JOURNAL,
    NO AFTER JOURNAL,
    CHECKSUM = DEFAULT,
    DEFAULT MERGEBLOCKRATIO
    (
    Ident VARCHAR(255) CHARACTER SET LATIN NOT CASESPECIFIC NOT NULL,
    Serial INTEGER,
    Node VARCHAR(64) CHARACTER SET UNICODE NOT CASESPECIFIC)
    PRIMARY INDEX (Serial);
    
    insert into SAN_D_FAAPOC_01.TestUnicode(ident,node,serial)
    values('TestùęSummary','TestùęSummary',1235);
    
    SELECT	Ident, Serial, Node
    FROM	SAN_D_FAAPOC_01.TestUnicode;
    

    The results are:

    	Ident	Serial	Node
    1	Testù�Summary	1,235	TestùęSummary
    
    

    The nice thing about Teradata is that columns can be defined as unicode-columns. Hence nothing extra needs to be done to store such unicode characters.
    A similar situation exists with MySQL. Also in that DBMS, we may store data in columns that are defined as being unicode. As an example, one may use this code snippet:

    CREATE TABLE t1
    (
        col0 CHAR(10),
        col1 CHAR(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci
    );
    
    insert into t1 values('TestùęSumm','TestùęSumm');
    

    Also here, we have an illustration of the purpose on Unicode. It is an extension of the standard ASCII characterset to include all characters from all living languages. I understand that even Gothic and Music characters are included in unicode. A subset of unicode is the ASCII set. On top of that characters are included that are not within the ASCII dataset.
    I understand we have different version of unicode. One such version is UTF-8. This version uses one byte to store the common latin characters such as ‘A’, ‘B’,’1′ etc. For the more exotic characters, more byte are used. An example is recently introduced “€” that takes 3 bytes. Other characters use 4 bytes.
    On average a western text is stored quite efficiently in UTF-8. As most characters only use 1 byte, we end up with a file size (in terms of bytes) that equals the number of characters.
    Another implementation is UTF-16 that uses 2 bytes per character. In that case, the file size, in terms of bytes, is double that of the number of characters. A western text, written in UTF-16 is then double as big as it would have been in UTF – 8.
    As an example, I include two texts, one written in ASCII and one in UTF-8:
    utf

  • Starting vbscript

    I recently came across vbscript. I was a bit curious to see how this works. As a first step, I created a small batch file (“tom.bat”) that invokes a vbscript. This script reads as:

    cscript C:\Users\TOM.VAN-MAANEN\tom.vbs "KINLW7D6LPVM1"
    exit %ERRORLEVEL%
    

    This script shows how such vbscripts can be invoked. One may start a script from the command line with the command “cscript”. This command is followd by a scriptname and a parameter. The script is ” C:\Users\TOM.VAN-MAANEN\tom.vbs” and the parameter is “KINLW7D6LPVM1”. The script returns a runcode that can be displayed with exit %ERRORLEVEL%. As an example, I also provide the script:

    On Error Resume Next
    Const CONVERSION_FACTOR = 1024
    Const ONE_SEC = 1000
    If WScript.Arguments.Count = 0 Then
     Wscript.Echo "Usage: tom.vbs server1 [server2] [server3] ..."
     WScript.Quit
    End If
    For Each Computer In WScript.Arguments
      Set objWMIService = GetObject("winmgmts://" & Computer)
      Set colLogicalDisk = objWMIService.InstancesOf("Win32_LogicalDisk")
      wscript.Echo colLogicalDisk.Count & " drives found on " & Computer 
      For i = 1 to 1
        For Each objLogicalDisk In colLogicalDisk
        wscript.Echo "There are " & int((objLogicalDisk.FreeSpace / (CONVERSION_FACTOR * CONVERSION_FACTOR * CONVERSION_FACTOR))) & _ 
        " Gigabytes on "  & " " & objLogicalDisk.DeviceID
        Next
        Wscript.Sleep ONE_SEC
      Next
    Next
    

    What does this script do? This script checks the disk space on each drive on the computer “KINLW7D6LPVM1”. It uses existing objects that are available in a windows environment with the WMI service. A class within this object provides information on the drives. It provides information on the number of drives and the free space that is available. The information is gathered and exported in a loop that displays the information on each of the drives. I also created a loop to allow for a regular check on available diskspace. Within this loop a delay is included.

    Another nice example is this vbs programme:

    
    Const cAppend = 8
    
    
    paramStr = Wscript.Arguments.Item(0)
    
    
    if (paramStr = "ONZIN") then
    	paramFile = "C:\Users\TOM.VAN-MAANEN\test_list_parm.txt" '''''''''''''''BW parameter txt file for LASTSHIP DATE and others which run once a day
    	InboundFolder = "C:\Users\TOM.VAN-MAANEN\"  '''''''''''''''BW TD folder path 
    	logfile = "C:\Users\TOM.VAN-MAANEN\test_list_log.txt" 
    end if
    
    
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objLogFile = objFSO.OpenTextFile(logfile, cAppend, True) 'open the text file for appending
    
    
    if (trim(paramStr) = "") then
      objLogFile.WriteLine paramStr & " file checking aborted, error in input parameter value"
      set objFSO = nothing
      WScript.Quit(1)  ''''FAILURE
    end if
    
    IF objFSO.FileExists(paramFile) Then 
    
      Set fileList = objFSO.OpenTextFile(paramFile, 1) 'open the text file for reading only
      i = 0
    
    '''' ------------------- Missing file listing ----------------
      Do While Not fileList.AtEndOfStream 'loop until the end of the file
       	strfilename = ""
    	strfilename = fileList.ReadLine 
    		
        If (Not strfilename = "") then ''''check filename is not empty
    	If NOT (objFSO.FileExists(InboundFolder & strfilename))  then ''''check file exists in inbound folder
      		if (i =0) then 
    		objLogFile.WriteLine "-------------------------------**** Missing file list *****----------------------------------"
    		end if
    
    		i = i + 1
    
    		objLogFile.WriteLine cstr(i) & ". " & strfilename
        	End If
    
        End If	    
      Loop '''' end loop for missing files 
      fileList.Close
     
    
      If (i > 0) then '''' atleast some missing files, terminate
    		objLogFile.WriteLine " "
     		objLogFile.WriteLine "========================================================="	  
       		objLogFile.WriteLine "File list not complete in Landed folder for " & paramStr & " at " & Now
    	  	objLogFile.WriteLine "========================================================="
      		fileList.Close 
      		objLogFile.Close
    		set objFSO = nothing
     		WScript.Quit(1) ''''FAILURE
      End If
    
      objLogFile.WriteLine " "
      objLogFile.WriteLine "========================================================="
      objLogFile.WriteLine "===== " & paramStr & " File checking process COMPLETED SUCCESSFULLY====" & Now
      objLogFile.WriteLine "========================================================="
    
      fileList.Close
      objLogFile.Close
      set objFSO = nothing
      WScript.Quit(0) '''''SUCCESS
    
    ELSE
      objLogFile.WriteLine paramStr & " file checking Process terminated, parameter file is missing in scripts folder for " & paramStr
      objLogFile.WriteLine "========================================================="
    
      objLogFile.Close
      set objFSO = nothing
      WScript.Quit(1) ''''FAILURE
    END IF
    

    This script can be started with: cscript C:\Users\TOM.VAN-MAANEN\test_list_scr.vbs “ONZIN”. The idea in this script in that file is read that contains a list of file names. For each file name, it is checked as to whether such a file exits in a given directory. If that is not the case, such file name is added to an array. In a subsequent step, the list with file names that do appear in a given location are written to a file.

  • Security certificates

    I got interested in security certificates. What are these? How does it work? It is possible to use it on your own website? Those were my questions.
    The principle is somewhat confusing, but is works. The idea is that a security certificate exists of two elements. One element is a so-called private key. This private key rests with the webserver and it is used to decrypt a message that is sent to the server. Likewise, it encrypts the message that is sent by the server. The private key is also used to generate a public key. This public key is sent to any browser. The browser is then able to do the opposite; it is able to encrypt a message sent to the server and decrypt the message received. The result is that encrypted traffic can be exchanged between browser and webserver.
    In a sequence, one gets:
    [1]: the browsers requests a secure page via https://…
    [2]: the webserver sends the public key to the browser with the signed certificate
    [3]: the browser checks the certificate. If the certificate cannot be correctly identified, the browser issues a warning. If one creates the certificates yourself, you get such a warning.
    [4]: the browser uses the public key to encrypt the url that is asked
    [5]: the webserver uses the private key to decrypt the url.
    [6]: the webserver encrypts the page that is sent to the browser
    [7]: the browser decrypts the page that is recieved.

    One may buy a set of certificates, but is more fun to create a set of certificates oneself.
    To do so, one needs an opensource software programme “openssl”. It is available for free. But I must admit, I had to search for it. It was not really easy to find. Maybe, it help in you know the exact name; in my case it was openssl-0.9.8h-1-setup.exe.
    The programme is meant to be used in Linux. There are windows versions, but then one should then set a parameter: set OPENSSL_CONF=C:\Program Files\GnuWin32\share\openssl.cnf, in my case. It depends of course on where the config file resides.
    The creation of the the private file is then done with a series of commands:

    openssl genrsa -des3 -out tom.key 2048 #generate private key
    openssl req -new -key tom.key -out tom.csr #generates signing request
    copy tom.key tom.key.orig
    openssl rsa -in tom.key.orig -out tom.key #write rsa key, private signed key
    

    Subsequently, the public key is generated with:

    openssl x509 -req -days 365 -in tom.csr -signkey tom.key -out tom.crt #delivers public signed key
    

    But, how do we apply these certificates to the webserver. Somehow, we must tell the webserver that such certificates exist. I now use nginx as webserver and this is how my config file looks like:

    worker_processes  1;
    events {
              worker_connections  1024;
           }
    http {
        include       mime.types;
        server {
                listen       80;
                server_name 192.168.5.14;
                return https://$server_name$request_uri;
               }
        # HTTPS server
        #
        #
        server {
            listen       443 ssl;
            server_name  192.168.5.14;
    
            ssl_certificate      tom.crt;
            ssl_certificate_key  tom.key;
    
    
            location / {
                root   html;
                index  index.html index.htm;
                error_page 404 /404.html;
                       }
                location ~ .php$ {
                                   root           html;
                                   fastcgi_pass   127.0.0.1:9000;
                                   fastcgi_index  index.php;
                                   fastcgi_param  SCRIPT_FILENAME c:/nginx/html/$fastcgi_script_name;
                                   include        fastcgi_params;
                                 }
              }
    
         }
    

    I would say that this config file looks rather straightforward. In the first part, any request is translated into an https request. In the second part, you see that the certificates are shown to the server.

  • XML records in Oracle tables

    It is possible to store XML records in an Oracle table. This is one (of the many) way to retrieve XML information from an Oracle environment. It is actually quite simple. An Oracle table may contain columns that allows us to store XML records. An example is:

      CREATE TABLE "OE"."TPERSON_DATA" 
       (	"PERSON_ID" NUMBER(3,0), 
    	"PERSON_DATA" "XMLTYPE"
       )

    We see that the attribute “Person_Data” in table tPERSON_DATA may contain XML records.
    This table can be loaded with standard insert statements like:

    insertXML

    We have an XML record having “book” in the root. One branch is “title”, another is “price”. Likewise, we also see an author branch and a year branch. This can be queried with SQL statements that have an inline XMLQUERY expression.

    The full statement is:

    SELECT person_id, XMLQuery ('for $i in /book
                                 where $i/price > 30
                                 return $i/title'
                      passing by value person_data
                      RETURNING CONTENT) XMLData
    FROM oe.tperson_data;

    The SQL statement is Select person_id etc, where the XMLQUERY expression is:

    for $i in /book
    where $i/price > 30
    return $i/title'
    passing by value person_data
    RETURNING CONTENT

    This XMLQuery is composed of 3 sections. One section is the apostrophe constrained line that retrieves a part of the XML records. This is an XQuery expression. The second part reads like “passing by value person_data” where person_data is the name of the attribute in which the XML record is stored. The final third part is RETURNING CONTENT which are key words.
    The apostrophe constrained line can be understood as “for $i in /book” where $i contains the content of the XML record and /book is the root on the XML record. The second line “where $i/price “refers to one branch that acts as a selection. The third line “return $i/title” refers to another branch that is returned to the query.

    This explains the outcome where we will see:

    insertXML2

    The outcome is “Learning XML” that is retrieved from the XML record with book as root and that complies to the restriction that the price is larger than 30.

    Another expression is:

     SELECT EXTRACT(person_data, '/book/title') as "Titel" 
     FROM oe.tperson_data w;

    that also provides us with the title:

    insertXML3

  • Product Types

    I recently encountered a nice model on product types that I would like to share.
    A product type can be understood as an concept of a product, much like the descriptions you might see in a catalogue. Examples like a Peugeot 206 Gentry which is a concept of a car. It is not equivalent to actual cars – it only describes a type of a car of which a lot of actual cars may exist.

    Then the model:

    productType

     

    In the left upper corner, we see the entity “Product Type”. This entity may contain a description such as the Peugeot 206 Gentry. Other examples may be the hard disk WD3000EXDB which stands for a type hard disk.

    As we may have hundreds, may be thousands of product type, we may classify these product type into several classes. We may have the class “cars” and a class “hard disks”.

    Each of these classes may have (overlapping) sets of attributes that describe the product types. The product type class “hard disk” may have attributes like price, storage amount, delivery term etc. Likewise a product type class may have attributes like price, number of seats. The attributes are listed in an entity “Product Type Attributes”. As we may have overlapping sets, an associative entity is added.

    The “Product Type Attributes” and “Product Type” both identify the values. We then know the Peugeot 206 Gentry costs 20000 euro, whereas the WD3000EXDB costs 200 euros.

     

     

  • XML and XSLT

    Several possibilities exist to read XML files. One such possibility is to have it read via XSLT. This procedure is composed of three elements:

    • The XML file that is to be read;
    • A XSLT file that provides us with instructions on how to handle the XML file.
    • An engine that translates the XML file via the instructions as given in the XSLT file into something that is readable.

    XMLXSLT

     

    An example may clarify this. Suppose, we have a XML file that starts with these lines:
    XML

     

    For a full XML file see here. Within this XML file, it is indicated that an XSLT file “cdcatalog.xsl” is to used as a file that contains instructions on how to read this XML file. In this case, the set of instructions looks like: XSLT.
    If the XML file is then accessed with a programme that contains an engine to apply the instructions as contained in the XSLT, we get the desired result. Every modern web browser contains such engine. Hence if the web browser is used to read the XML file, we already have the desired result. This is how I could see the XML file when I read this with my webbrowser:

     

    HTML

  • Some Javascript to read XML

    javascript1
    I know that lots and lots of possibilities exist whereby an XML file can be read. One set of possibilities is to use a Javascript. One then stores a script on the webserver that is processed by the web-browser. Upon processing, the XML file in read and can be stored in another format. A quick query provided me with three such scripts where an XML file is read and subsequently presented in an HTML file.
    Below, I have included a link where three scripts are executed.

    click here

    If the reader would like to see the scripts, he could look at the source that can be read from the web browser itself. After all, the script must be read by the web browser as to execute it in the browser.
    It is also nice to see that the scripts are interpreted differently by different web browser. The Internet Explorer will give another result as, say, the Chrome browser. This shows that the scripts are interpreted by the web browser and we have the consequences of different web browser and ensuing different results.

  • Send an attachment via email

    It is possible to use telnet to send an email. This is even quite straightforward.
    The idea is to start a telnet session with: telnet mail.wxs.nl 25 (or something alike that contains an email server to which one has connection.

    One could then enter to indicate the sender and receiver of an email:

    helo mail.wxs.nl
    mail from: tom.vanmaanen@wxs.nl
    rcpt to: tom.vanmaanen@wxs.nl
    
    

    The actual content of the email is then provided by:

    data
    Subject: Onzin van Tom
    MIME-Version: 1.0 
    Content-Type: multipart/mixed; 
     boundary= "KkK170891tpbkKk__FV_KKKkkkjjwq" 
    
    --KkK170891tpbkKk__FV_KKKkkkjjwq 
    Content-Type: text/plain; charset=US-ASCII 
    
    Dit is mijn boodschap
    
    

    One finishes with an empty line and a dot:

    
    .
    

    All commands and the actual text is sent in plain text. It is human readable.
    This makes it understandable that an attachment which is in binary format must be translated into plain text before it can be sent. Let us take as example an Access file (a.mdb), that must be translated into plain text. This will look like:

    --KkK170891tpbkKk__FV_KKKkkkjjwq 
    MIME-Version: 1.0
    Content-Description: "Base64 encode of a.mdb by Wincode 2.7.3"
    Content-Type: application/msaccess; name="a.mdb"
    Content-Transfer-Encoding: Base64
    Content-Disposition: attachment; filename="a.mdb"
    
    AAEAAFN0YW5kYXJkIEpldCBEQgABAAAAtW4DYmAJwlXpqWdyQD8AnH6fkP+FmjHFebrtMLzfzJ1j2eTDn0b7irxOmGXsN0PanPrYwCjmDSiKYEoKezbr7N+xaWoTQ9ExsTMq/3lbjCt8KqPgfJkIH5j9DJFyW7X9g2ZflfjQiSSFZ8YfJ0TS7s9l7f8Hx0aheBYM7ektYtRUBgAANC4wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    
    ...
    
    --KkK170891tpbkKk__FV_KKKkkkjjwq-- 
    
    

    A full example can be found here: ExampleEmail.

    One may question how the encoding can be accomplished. To do so, I found a set of useful websites (like http://www.opinionatedgeek.com/dotnet/tools/base64encode/ ) in which you may upload the binary file and one may get it encoded back. This can then be included in the mail session.