A site devoted to discussing techniques that promote quality and ethical practices in software development.

Wednesday, July 15, 2015

A tale of two share registries

Every year around this time, the end of the financial year, I, like others, have to prepare share holding statements of my share portfolio for my accountants and this exercise takes me into close contact with the share registries managing the shares in the listed companies.

There are several registries in Australia and some companies use one while the others use a different one. It is not uncommon for a share holder having to deal with multiple registries.

The two largest ones are the ComputerShare and Link Market Services. Both have the facilities to generate holding statement document but they are vastly different in their implementation and this blog post documents my experience showing how one can be so badly designed to meet user's requirement while other is a joy to use.

Both systems offer several log in facilities to access the holding or holdings. Both allow a user to become a registered user and in so doing can let the user to define the collection of shares of interest. They also offer a user a single holding access to just one share's detail using the share identification number called the SRN and other details.

For people with a large share portfolio it is much more convenient to become a registered user. However as to be revealed, it is not always the case when dealing with ComputerShare.

ComputerShare has longer history than Link Market Services but the latter has a far user-friendly user interface that the former.

ComputerShare once had a very functional, though less colourful, system and had served it well. In that system, one could expand the particular share holding and could then enquire the holding at a particular date right there. Several years' ago, ComputerShare decided the functional system needed freshen up and decided to splatter the web site with eye-candy features and introduced an amateurish help system that is actually an insult to the intelligent of its users. More on this later on.

The eye-candy effect caused minimal changes to how holding details are shown to the user and the shares in the portfolio are listed alphabetically, just like the less colourful previous system. As a comparison to Link Market Services the eye-candy effect has not improved the usability one bit as compared to Link Market Service, speaking from someone with a long history of using both.

However, the most radical change in ComputerShare is in the way of generating holding statement  at a particular date. It is not about relocating the access of a feature from one user-interface to another location that is so unusable but the implementation behind that makes this so frustrating to use.

The 'Export Balance Letter' has the following user-interface design:

to let the user to generate the balance statement. For some strange or mismanagement reason, the designer of this piece of user-interface changes the terminology from 'holding' to 'account' in the 'Select Account'. In the opening statement of this user-interface, the designer is still referring them as holdings. The rest of the web site all uses holding to refer to a particular share holding. 'Select Account' should be corrected to 'Select holding' for consistence.

It is not the eye-candy stuff that makes this piece of user-interface totally unhelpful and unusable. It is what lies behind the combo box for the list of holdings (I will refrain from calling them accounts because they are not) that are irritating (and dare I say any users bar the designer).

This piece of implementation is a prime candidate for the book "Why software sucks". If you drop that combo down, any sane person would expect ComputerShare designer to show the share holdings in alphabetical sort order, just like in the Portfolio page.

But surprisingly or rather shockingly, the order seems to be rather random without seeing the code. In my access, the list box in the combo box shows the companies in the list starting with A, C, W, W, A, C, A, P, A, .... S, L. What kind of sort order is that? I managed to talk with someone from ComputerShare about what kind of collating sequence they are using to generate this. The answer, from someone without much conviction, suggested that it might be the order I acquired the share. Even if that is the case, what good does that sort sequence do to the users?

Having worked with many developers in my life I have never seen something as bizarre as this. It is a sloppy piece of work and how hard it is to add an ORDER BY clause on ASXCode column in your SQL statement?

Needless to say the person I talked with from ComputerShare is rather defensive (a trait I have commonly found in some development companies) giving me all other irrelevant excuses like the software has to work in different countries. I am not inexperience in I18n.

If the caller wanted to solicit user feedback to help them with their design, he had used the wrong tactic. No where in my Facebook (borrowing someone's access) message did I say anything about having the ability to download them to a spreadsheet. And yet, this person kept drumming into me of the ability to download into spreadsheet and that features might take some time. I told him all I wanted was for ComputerShare to list the holdings in the list box in alphabetical order - a much easier undertaking that will bring huge benefit. He certainly has failed the user-requirement solicitation process.

Now let's consider how Link Market Service handles this that makes ComputerShare looking like an amateur. Link does not use the algorithmic way of pulling in the share holding relevant for the registered user. Link allows user to pull in holdings of totally different owners as long as one has the SRN and it also allows user to group these holdings, a useful feature not available in ComputerShare.

Hence in Link, one can have BHP, for example, owned by Albert, Mary, Jack and Tom, each with distinct SRN of course.

In Link, the balance statement is located in the 'Balance History' page which contains a similar user-inferface

Once again it is not what hits your eyes that matter but it is in the implementation of that list box in the combo box for the holdings. Link sorts the holdings alphabetically and a sort order I challenge ComputerShare to show me that is less useful.

Rather than to torture myself with the ComputerShare's illogical sort order when I came to compiling the end of the year holding statement for shares managed by ComputerShare, I did not use my registered log in detail. Instead I used the single holding access which seems irrational. Even with having to provide log in details and entering the CAPTCHA for each holding, it is still the quickest and less stressful way to get the job done. This is still might quicker than to navigate through poorly arranged list of holding in ComputerShare.

Not contented with driving their users crazy with their idiotic design, they try to pretend to provide some 'human' assistance; they introduced the 'Ask Penny' which must be built with a penny as it lacks any form of intelligence or  knowledge. If you can't provide an AI assistance, perhaps a general helpdesk e-mail facility is more useful and more capable of giving that human touch. Their 'Contact us' facility is equally useless because it is share-centric.

In sharp contrast, it is a joy to use Link to compile that end of the year holding statements. Thanks for a job well done.

Tuesday, June 23, 2015

Rare to see an anti-virus/malware protector not having automatic updates

It is extremely rare to find an anti-virus/malware protector not having an automatic update facility to its engine and database. Windows Defender running in Windows 8.x is one such rare species.

This happens if the user chooses the option in Windows Update not to use automatic updates, a choice giving the user better control which upgrades should be applied.

In that case, Microsoft acknowledges that it is a design decision that the user is not given the normal Windows Update notification, except in the log in screen. While I accept, only reluctantly, that there is a shred of logic in this, albeit very draconian one, why does that affect the important updates to a protection software which depends on timely update of its database/engine?

I have used a variety of AV and this has to be the first one that fails to update automatically or tell me an update pending when I choose not to use automatic Windows update option. Most of them has automatic update by default and is not under the influence of Windows Update.

This situation is a good example of Golden-Hamer anti-pattern resulting in leaving its Windows user vulnerable to attacks. So if you want more controls on your Windows' updates, don't use Windows Defender. Furthermore, another case of don't believe everything you read (on Microsoft product) and here is one taken from the Windows Defender's Update page for Win8.1:

It only updates automatically if Windows update is set to automatic. That "Did you know" message needs to be clearly qualified to avoid misunderstanding.

Windows has all sorts of detections and options, surely in the Windows update control panel applet Microsoft can add a check box there to let the user to choose if one wants to receive notification, including Windows Defender update notification. Or in Windows Defender to have a check box to remove automatic updates if the update notification is so distractive; it could and should update silently. Cutting that out altogether is just plainly a bad design decision. I suspect that is other sinister motive than what has been revealed.

I am wondering if this draconian approach will be addressed in the upcoming Windows 10?

If you persist to support Windows Defender with your choice of Windows updates option, the other option is to use a Task Scheduler to register the Defender updates periodically. It is a choice to ditch Windows Update or to use the Task Scheduler.

I will now experiment with some of the Windows Update Notification tools to address the Windows 8.x deficiency.



Thursday, May 14, 2015

My experience in using one2free prepaid Mobile Broadband SIM in Hong Kong

I am a regular visitor to Hong Kong and in every visit, I purchase a prepaid mobile broadband data SIM for my Huawei pocket modem to provide Internet service to me. I am no stranger to this kind of SIM as I have used in the past various types of 3HK Data SIM. So after reading so many glowing remarks about the one2free's prepaid mobile broadband SIM, I have decided to give it a test ride this time.

I did some preliminary investigation prior to the visit via their e-mail customer service which I may say is rather responsive by comparison. It would be nicer if they have 3HK's online chat service.

On the whole, I am rather pleased with the performance, the cost, the responsiveness of the customer service which I had to use quite a lot, as you will see, during my stay. Unfortunately, their responsiveness is tarnished somewhat by their answers which clearly indicate that they are let down by their organisation.

Now, with the good bits out of the way, let's go through the bad bits.

Foremost is their web site which is devoid of any useful and helpful information. It would be more helpful if their web site provides some form of instructions in using their services. Such as what happen if you buy the $100 starter kit, what rate will you be charged at. What about the steps to buy the 30-Day Pass with 3GB quota for someone what has not used your product before? What happen when one uses up the quota but still within the 30 days? Will the connection speed be shaped?

In my case, I want to use the 3GB 30-day pass, which according to the published information will cost me HK$148.00. To subscribe to that, one needs to load the prepaid SIM with at least (preferably more) that that amount. At the shop where I purchased the kit, they did not have $50 top up voucher instead they only had $100 voucher which means my SIM card is loaded with $200 and after paying for the 30-Day pass, it has a balance of $52.00.

No where in their web site explaining this and what happens to that balance. For those wanting to go down this path, here is the treatment of the balance.

The 30-Day pass expires after 30 days from the day of subscription. CSL will immediately deduced that amount from your card on subscription. Hence you must load your card up with sufficient amount before you can punch in the code to select the day pass. The amount remaining can be use for other purposes such as making calls or to contribute towards next day pass purchase. It does not expire until 6 months after the activation or from your last top up. In other words, your prepaid SIM card is valid for 6 months as long as there is sufficient fund to pay for the monthly government charges, which is HK$2.

Unless you do not have other SIM to make voice call, this SIM charges (HK$0.3/min) 3 times as much as other CSL SIM ($0.1/min).

The next area of great disappointment is how to monitor the data usage. Their web site for the prepaid starter kit contains wrong and misleading information.

While that site is for the Prepaid Mobile Broadband SIM, the login button is not intended for Prepaid mobile and I only found this out after the event.

This web site expects the user to possess certain degree of psychic to realise that. I was misled by this page and unsuccessfully to get a password or to reset it by following the online link. Out of desperation, I inserted the data SIM into a mobile phone and used the *777 code to successfully reset the 6-digit password for my SIM. The system acknowledges the request and echoes back the password (very security conscious).

Next, armed with my SIM's mobile number and the password, I pressed the login button on that web page. Rather than telling me that my SIM cannot use 'My Account' to manage my usage, it throws a Java Exception message:
type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

java.lang.IllegalStateException
 org.apache.coyote.tomcat5.CoyoteResponseFacade.sendRedirect(CoyoteResponseFacade.java:418)
 LoginRedirect.doPost(Unknown Source)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:767)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:860)
 sun.reflect.GeneratedMethodAccessor57.invoke(Unknown Source)
 sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 java.lang.reflect.Method.invoke(Method.java:585)
 org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:249)
 java.security.AccessController.doPrivileged(Native Method)
 javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
 org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:282)
 org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:165)

note The full stack trace of the root cause is available in the Sun-Java-System/Application-Server logs.

Nice? Have they ever tested their program? Why doesn't the web page inform their user that the login page is not for Prepaid user? Surely, they have all the information to tell if the caller's SIM is a prepaid or not.

I raised this issue with the online support as well as visiting one of their customer service centres and was then told that that login button on the web page and "My Account" facility are not for Prepaid users. Surely their web designer can put that few words into their page to warn their user and even better, their program tests and traps that kind of exception and to inform their users in a more meaningful manner. It is not a big ask isn't it. More disturbingly, if that facility is not for prepaid user, why does *777 allows a number belonging to a prepaid SIM to reset password? So amateurish!

So after the visit, I discovered that as a NextG-Prepaid user, I should use this URL http://www.one2free.com/nextg-prepaid while connecting to the CSL using the one2free SIM. Using this URL, I have managed for the next 3 days to make a daily enquiry of my usage.


On the 4th day, when I used that URL, I was confronted with this web page:

Notice that the left hand pane tells me that this is a "My Account" facility, the very facility that I was told that it was not for me.

Not deterred and with a sense of adventure, I pressed the login link which sent me to https://prepaid.hkcsl.com/login with the following login page

The login page asks for the mobile number of the SIM and a password, which I duly use the one that I used the *777 code to reset. The system accepts my inputs and provides me access to my SIM's data. The data usage can be retrieved by pressing the "Promotional Bonus Details" link.


Notice this is a different web page as compared to the previous one via the NextG-Prepaid link.

I sought the customer service for an explanation of how I could access "My Account" when they told me that it is not for me to no avail. We ended up going around and around in circle. The customer service refuses to acknowledge that the URL https://prepaid.hkcsl.com/login is right for me despite being pointed out that the URL containing the word 'prepaid' to indicate that it is for prepaid users.

Even more interestingly is that I can access my prepaid SIM card detail using this URL without having to use a connection provided by CSL SIM while I need to use the one2free SIM in order to use the http://www.one2free.com/nextg-prepaid regardless successful or not. As an experiment, I have just connected to this https://prepaid.hkcsl.com/login some thousands miles away from Hong Kong.

After discovering that I can use this URL to monitor my data usage, I continue to use it ignoring any contradictory comments from the customer service. Incidentally this URL is not disclosed on any of the CSL web pages. It seems that there is a communication problem within the CSL on this issue.

Whatever it is, it is CSL's problem and they need to deal with it. I have supplied all the information, such as SIM card number, mobile number, and modem model. They need to improve their web site to make it more useful and helpful. Don't just throw figures and data on it. Test it with someone who is not a user of your system or product.

Teach your front line support personnel to slow down and take time to explain the various facets of your products. I know you know your products very well but your potential customers DON'T.

Test your web site with any non-sensible data and don't let your Java exception message leak out to the users. That is not an acceptable way to tell your user that they have entered something wrong.

To date, I still have not been offered a logical explanation why the link http://www.one2free.com/nextg-prepaid, I was instructed by the customer service to use, failed after 3 days. And that why I should not use https://prepaid.hkcsl.com/login which works but the customer service next acknowledges that I should use that.

Thankfully, I have a wonderful Internet service and despite all the above mentioned issues, it is still cheaper than 3HK's offering and I still will recommend it to other travelers. Just be prepared for some rough edges.

Saturday, March 28, 2015

Installation recommendation for PDFCreator 2.1.0

For those intend on installing PDF 2.1.0, you are recommended
  1. to download it, 
  2. turn off your network connectivity, 
  3. before running the installation package. 

This is because the installation script produces very much the same undesirable behaviour. Turning off the network connective during installation prevents it from calling home to download other crapware.

If you are running AVG 2015, it will pick up the presence of OpenCandy, "Adware AdLoad.OpenCandy", since it is a crapware, it is best to let AVG's residence shield to toss it away - no loss at all.

Below is the brief outline of what happen to the installation process with no network connectivity (assuming no AV to intercept the presence of OpenCandy crapware).

In fairness, I do not believe PDFCreator intends on planting OpenCandy into your machine. Detail probing of the installation process seems to indicate that some programming error is responsible for the left over of "OpenCandy's recommendation engine p101, version 2.0.0.156" (OCSetupHlp.dll) in the temporary directory. The presence of this file can cause your AV to report the presence of OpenCandy threat during routine scanning.

PDFCreator installation script also generates a copy of the set up log in "c:\Program Files\PDFCreator\SetupLog.txt". There also seems to be a programming error that left the temporary copy (original copy) of this file of the format "Setup Log yyyy-mm-dd #xxx.txt" in your temporary directory.

When one initiates the set up program, it creates two temporary directories of the format is-XXXXX.tmp. One is to hold the actual installation program PDFCreator-2_1_0-Setup.tmp and the other is to hold various files that it needs during the installation program. You can find the list in the Set up log. One of them is the "OpenCandy recommendation engine p101" OCSetupHlp.dll version 2.0.0.156.

At the early stage of installation process, this DLL is not used, see comment below, and if you hate OpenCandy, delete it now and in fact that is what AVG did when it picks up the presence of OpenCandy and that you instruct it to remove the threat.

After you have selected the options to install, the program will run smoothly to completion. In my execution (not installing "PDF Architect") I never allow the last dialog box to launch PDFCreator.

Investigation using ProcMon on the interaction of the PDFCreator setup program with OpenCandy records the following observations:
  1. Towards the end of the installation phrase, the installation script launches RunDll32.exe to invoke OCSetupHlp.dll with the entry point using exported function 16 and the optional parameter seems to indicate an intention to perform IPC with the parent process. The purpose of this is still a mystery.
  2. The installation script's clean up process then deletes the files such as InstallCheck.exe, etc in the temporary directory
  3. It fails to delete OCSetupHlp.dll because RunDll32.exe is still running using it. The installation program attempts to delete this file 31 times before giving up.
  4. Once all the files are 'deleted', including the failed one, it tries to delete the directory but fails.
  5. At the end it simply ignores those failures and completes the installation.
The presence of the installation program trying numerous attempt to delete OpenCandy crapware only to be faulted by their programming error and the lack of sign of it trying to plant this engine elsewhere suggest to me that PDFCreator does not have any intention of using OpenCandy in the execution of the program.

You cannot delete OCSetupHlp.dll at the completion of the installation program until you have terminated the RunDll32.exe process holding this DLL. The best way to find the process holding onto this DLL is to run ProcExp and then search for the OCSetupHlp.dll. Alternately, log off and log back on and you can delete this file. It is highly recommended that you delete OCSetupHlp.dll to avoid your AV finding it in routine scanning.

Once RunDll32.exe is terminated you can delete OCSetupHlp.dll and to satisfy your concern, run your AV scanner over your system or use something like MalwareBytes.

Thursday, January 8, 2015

A solution to my problem of unduly long time to connect to the WiFi network when waking Windows up from sleep

I have encountered a problem that has also been reported by many Netizens that they have experienced an annoyingly (some called it obscenely) long time to connect to their WiFi network when their Windows is woken from sleep. My laptop is running Windows 7 with all drivers up to date.

In my case, all WiFi connections are flagged 'Automatically Connect' and that the WiFi adapter did not have the "Allow the computer to turn off to save power" in the power management section selected.

When I wake my laptop up from sleep, the machine responses very swiftly and my desktop is restored. However, it frequently fails to automatically connected to the strongest signal WiFi nor initiates any attempt to connect; I have to manually press the connect button.

I have tested my machine with two distinctively different Wireless networks - different modems/routers and networking technologies and I have observed the same problem. Hence it is clearly the problem is in my laptop.

Prior to last month, my laptop's WiFi adapter connects to the network the moment I sign in after waking my machine up (< 10 seconds). Then suddenly the about mentioned problem occurs.

After some soul searching and searching the Internet, I have managed to rid this problem restoring it to its former glory. I am not suggestion nor recommending my way of solving my problem as a solution to deal with all long connection problems but you many review the materials to see if it can apply to your situation. It does not involve some drastic proposal found on the Net. IPv6 has nothing to do with this sluggish behaviour.

So what is the possible cause then? After some soul searching of what I did to my machine, I vaguely remember one evening I was investigating the Virtual WiFi Router that turns your laptop's WiFi Adapter into a wireless access point and that to understand the underlying mechanism, I was using the command line technique. In that experiment, I vaguely remember that I did not complete the whole process as I do not have a real need of it and that I might even have gotten the command sequence out of whack.

That experiment caused the "Microsoft Virtual WiFi Miniport Adapter" to appear in my Device Manager, albeit with a yellow triangle with an exclamation mark in it.

This gives me a clue that it might (just a might) be the cause of my problem - I therefore may have to disable or remove the miniport. So after some research, I have found the following instructions to disable the "Microsoft Virtual WiFi Miniport Adapter" and here are the steps (must be executed in a command prompt with Administrative rights):

1) To stop the hosted network
netsh wlan stop hostednetwork

2) To disable the WiFi Virtual Adapter
netsh wlan set hostednetwork mode=disallow

I throw in a Windows restart just for the safe measure. After that the long process connecting to the WiFi network is gone and the machine is restored to its former behaviour on waking from sleep; no longer do I need to manually click on a Wireless network to connect to it.

You can find more information on the netsh command to deal with the wireless hosted network on the Microsoft's site here.

Once I have executed the above mentioned commands, the "Microsoft Virtual WiFi miniport adapter" disappears from the Device Manager.

If you have used or experimenting with the Microsoft's virtual wifi hotspot (or router), a good sign is the presence of this adapter in the Device Manager, give this a try and see if it helps.


Friday, December 19, 2014

Experience in installing PDFCreator 2.0.x

I have been a long term, though slow to update, user of PDFCreator and recently I have decided to upgrade it to 2.0.0 from 1.7.3.

The installation experience left me with a sense of unease as it triggers the resident shield of my AVG 2015 flagging some files as being a Malware/Trojan/Adware. I will come back to this.

As a result of this alarm, I revisited my trust old friend CutePDF Writer, which has fewer feature than PDFCreator. The installation of CutePDF Writer 3.0 went without tripping my AVG but one has to be on the wit about its attempt to slip in some PUP and toolbars. It is nice to see the installation script offering a feature to skip all the PUP.

Since PDFCreator's installation script trips my AVG, I have decided to investigate this further in a controlled environment. First of all, I went to PDF Forge site to obtain the MD5 of the installation package to make sure I was not using a tainted package.

My investigation used 2.0.1, the latest release to determine what's going on. I use two installation scenarios - with network access and without network access and they have different behavior causing AVG to report different alerts. My experiments with installing PDFCreator do not install Image2PDF and PDFArchitect.

With network access

When the installation package, PDFCreator-2_0_1.exe (MD5:1464dab853dfac75097e6f81fa060c9a), is invoked, the first thing it does is to spawn a process called DownloadUpdateInfo.exe and this runs its twin DownloadUpdateInfo.tmp for a brief moment and then closed down.

After soliciting inputs from the user, it then invokes CBStub.exe which controls the invocation of the process InstallManager.exe. It is at this point that the resident shield of AVG 2015 alerts the user of the presence of a Malware ladden file. It alleges that it is infected with MalSign.Generic.5E6.

This file, together with its companion file, inetc.dll, which appears to be doing the HTML get, put, post, and head operations, are deposited in the %Temp%\. is a randomly generated temporary directory name. They disappear after successful installation and one needs some trickery to capture them.

According to VirusTotal, there are 10 out of 56 Anti-virus tools reporting this file as infected.

What this file does is to offer user a chance to install Ad-Aware Web Companion:
Strange, asking user to install an Ad-Aware component results in being classified as a Malware! What this does is to then invoke the Mntz_Installer.exe, which seems odd as most people on the Internet identifies this as the Opera Network Installer. Whatever this file is, it installs two services, namedly, LavasoftTcpService.exe and Lavasoft.SearchProtect.WinService.exe, which are part of the Web Companion software.


In all fairness, one can safely consider the alert from AVG for InstallManager.exe as a false-positive and can ignore it. If you are running AVG and feel uncomfortable when it raises the alert, it will not harm the operation of PDFCreator if you ask AVG to protect you. In this case, AVG will destroy InstallManager.exe and its subsequent operations.

Without network access

Often, it is advisable to install downloaded software with network disconnected to see if it calls home.

When the PDFCreator installation package is invoked with network disconnected, it does not invoke the DownloadUpdateInfo.exe.

Instead it extracted a bunch of files into a temporary directory %Temp%\ which happens to contain the OCSetupHlp.dll. The presence of this file triggers the AVG 2015's resident shield identifying it as an Adware AdLoad.OpenCandy.

According the VirusTotal, there are 12 out of 56 AV tools identifying it as infected with OpenCandy. Exactly what this being used is unsure but it does not appear to hamper the installation if one asks AVG to remove this offending DLL.

When installing without network access, the installation package will not prompt you about the installing the Ad-Aware Web Companion using the InstallManager.exe and hence it will not trip the AVG's resident shield.

If you examine this DLL's version information and its export functions, it is unambiguously associated with OpenCandy and hence it is fair to say that PDFCreator installation is tainted by OpenCandy but PDFCreator does not seem to have infected with OpenCandy after installation and during its operations.

In view of this, it is fair to say this is also a false-positive even though it is part of OpenCandy system.

The experiments show that while PDFCreator installation package causes AVG to raise alarms during the installation, they are safe and one can safely ask AVG to protect yourself against these files without jeopardising the operations of PDFCreator. PDFCreator runtime does not cause any resident shield alarm.

Thursday, June 5, 2014

Handling Popup Menu (aka Context Menu) in a Gtk# TreeView widget

There are two ways to invoke the context menu, namely the familiar right mouse click and pressing Shift-F10.

To handle these two triggers requires some special treatments and this post is to illustrate how to accomplish them. The Internet and in fact the Mono forums contain materials showing how to handle the right mouse click and it is repeated here for completeness but seem to fail to discuss how to deal with Shift-F10.

To intercept the right mouse click

To intercept the right mouse click you need to provide a ButtonPress event handler to the TreeView's ButtonPress event and most importantly you need to tell the runtime to slot your handler before the default ButtonPress handler, or else you won't see the right mouse click.

Here is the code fragment to add a ButtonPress event handler, which you can also specify using the properties pad in MonoDevelopment IDE.

this.treeview1.PopupMenu += new global::Gtk.PopupMenuHandler (this.OnTreeview1PopupMenu)

When defining the handler, make sure you adore the handler with the Glib.ConnectBefore attribute as follows:

[ GLib.ConnectBefore ] // need this to allow program to intercept the key first.
protected void OnTreeview1ButtonPressEvent (object o, ButtonPressEventArgs args)
{
    if( args.Event.Button == 3 )    // Right button click
    {
        Debug.WriteLine( "Right mouse click detected" );
        ShowContextMenu("Right Click - ");
    }
}

To handle Shift-F10

It seems the treatment to invoke the context menu via the keystroke is not as popular as using the right mouse click and hence the forums have scant discussion on this. This may be due to poor documentation, in particular to the use of PopupMenuArgs, the event argument for the PopupMenuHandler delegate. In the absence of a recommended way from the Mono team to invoke the pop up, below offers a possible way to accomplish this.

When Shift-F10 is pressed on a TreeView, the runtime will invoke the TreeView.PopupMenu event handler if defined. This is different from other widget's way of handling context menu; Others have a PopulatePopupMenu event allowing the control's provider to construct the menu and the runtime will then render the menu.

Hooking the TreeView.PopupMenu event is easy but the same treatment used in invoking the user constructed pop up menu for right mouse click does not seem to work; in fact nothing is displayed. Hence it needs a slight departure from simply calling directly the Menu.Popup in the TreeView.PopupMenu event handler. You need to basically post yourself a message, using a Windows' parlance, and then you can invoke the popup. This can be accomplished by using the Application.Invoke method or its overloads.

Here is the code fragment to install an event handler for PopupMenu:

this.treeview1.ButtonPressEvent += new global::Gtk.ButtonPressEventHandler (this.OnTreeview1ButtonPressEvent);

Once again if you prefer, you can use the properties pad for the TreeView object in the MonoDevelop to specify this.

Below is the code fragment showing the way to use Application.Invoke() to show the context menu:

protected void OnTreeview1PopupMenu (object o, PopupMenuArgs args)
{
    Debug.WriteLine( "TreeView Popup Menu click" );
    // Post yourself a message to invoke the context menu.
    // Calling ShowContextMenu() directly from here does not
    // work.
    Application.Invoke( delegate 
        {
            Debug.WriteLine( "Delegate invoked" );
            ShowContextMenu("Shift-F10 - ");
        } );
}

For completeness, here is the implementation of very simple ShowContextMenu():

void ShowContextMenu (String prefix = "")
{
    Menu m = new Menu();
    MenuItem mi = new MenuItem( prefix + "Item 1" );
    mi.Activated += (object sender, EventArgs e) => 
    {
        String s = prefix + "Item 1 Clicked";
        Debug.WriteLine( s );
        ShowMsgBox( this, s ); 
    };
    m.Append(mi);
    
    mi = new MenuItem( prefix + "Item 2" );
    mi.Activated += (object sender, EventArgs e) => 
    {
        String s = prefix + "Item 2 Clicked";
        Debug.WriteLine( s );
        ShowMsgBox( this, s );
    };
    m.Append( mi ); 
 
    m.ShowAll();
    m.Popup();
}

Blog Archive