Silviu-Marius Ardelean's blog

a software engineer's web log

The First Hackathon Experience #HackTM2016

It have passed approximately two months from my first hackathon experience, the #HackTM2016 from Timisoara. This delay I’m publishing this article is mostly because of the release period to the job and other personal stuff I had to do.

This experience was a reminder of my high school programming competitions where I have attended with different applications written in the already ancient Turbo Pascal 7.0 or Borland C++ 3.1. At that moment, probably because of my high school informatics great teachers, the competition spirit between colleagues was so intense and we have competed each other in creating applications within the local competitions and in other cities from the country.

This year, the hackathon competition from Timisoara was between 20 – 22 May 2016 to the UPT Restaurant, Timisoara and from my point of view it was a great event. The event had categories such eHEALTH, Robots, Smart City, GameDev, IoT, Education, Fintech and Open but no Automotive category as I expected according to previous pitching sessions.

Before the effective event I have attended in two pitching sessions seeing different challenging proposals in few domains. The most appealing were some ideas of the ADAS team from Continental, a team I was apart between 2006-2008 (Siemens VDO department, video camera projects at that time).

Even if I had no team, because of curiosity, I bought the ticket and I went to the hackathon pitching session, trying to figure a team and to decide a project to deal with.

The Continental ADAS team came with hardware and software support how to hack their platform.

We were able to find a small team, first by two persons and later for a period five persons. Unfortunately those last three persons left us while realizing that the project is not what they have imagined initially, that other projects look more challenging or that their knowledge were not matching with what it was required for our project.
So, I installed on my laptop some software used internally by the ADAS team and we took a ride to record real traffic data. Once we had this data, the effective programming for grabbing it can be done in office conditions.

Driving to grab ADAS data

The idea

Having the radar and camera information, GPS data and vehicle dynamics, we were thinking is that in the near future, even before self-driving cars on the common roads, these information might be sent in cloud to be used by the traffic management solutions in order to be optimized the traffic. Even these days, in my city, Timisoara, such traffic management solution is implemented, but is not based on cars internal information. Maybe, this idea will not be applied.

What we have done – the effective experience

So, facing with this challenge, me and my teammate Nikola Kolevski, a Serbian nice guy, have started the work on Friday evening. We have met on that pitching meeting and we had a great cooperation. I was the back-end guy and he the man from the cloud. Because we “spoke” different languages, me C++ and he Python, we have decided to speak the REST way.

During our job we have improvised the “project management” with a Trello board. Of course, we used GitHub for source control.

What I effectively had to do it was to inject some code within a .DLL that was loaded into a Continental application and sent the ADAS information in cloud. Nicola was the guy that received and collected the data. Unfortunately, even if we tried few times, we found no front-end available teammate, just some with slices of time in terms of availability.

ADAS AE-RO HackTM concept

I decided to use the benefits of asynchronous programming and I used the Casablanca REST API. But because of the Continental’s Visual Studio 2012 project constraints (!!!), during the Friday evening I faced up with the challenge to find and adapt a Casablanca library older version to the project. The latest Casablanca’s versions are available for VS 2013 and VS 2015 only. Thanks to NuGet tool, I finally managed to get and use the 1.10 version.

On Saturday we managed the effective work, facing with some challenges related to the TCP/IP communication between our applications because of some Python server configuration, but finally our applications were able to talk each other via REST services, in the night and I have tweeted.

After a sleep break, next morning we did some last code adjustments and being time constrained we tried to improvised a frontend. Also, we had a second trip with the Continental’s Mercedes car to test what we did, using a 4G network.

As usual for a hackathon, everything was on the run with adrenaline, so quite nice! At the end of the hackathon we had to prepare for the hackathon jury’s visit and later for presentation because we have qualified in the first three teams in the Robots section. Yeah, we were included there because the Automotive category did not exist, but it was fine. 🙂

The truth is that the Continental was the only automotive represented company even if there are many such companies in Timisoara, but it seems they are not interest in such events.

Other interesting things from #HackTM2016

Attending to #HackTM2016 was a great experience, I have seen many interesting projects but from far the most exciting one was the Symme 3D Printer, a local start-up.

Conclusions

In a internet of things world our based idea might connect the cars ADAS information with intelligent management future systems to improve the traffic flow in big cities.

It is obvious but I want to underline: if you want to have success in hackathon, try having a core team before event. Otherwise, you might just have fun coding but not ending the prototype.  Strategies of being efficient would be a great asset.

Meeting new people and trying to do something from the scratch in a limited time is a very cool thing even if you don’t have time to write optimized and tested code. Also, you might learn a lot of new things.

Definitely, I will repeat this experience in the future!

Share

Finally, I got Windows 10

Finally, I got the Windows 10 for my laptop… Even if this task is trivial, it was a surprisingly experience this time. But let me tell you the story of Windows 10 installation on my Samsung RC 710 laptop.

Back in August I tweeted “That’s all I have within #Windows10 X64 Ent setup on Samsung RC710 with SSD”. By that, I meant that my setup process was stuck in the boot phase using the installation of this Windows brand new version. That was reproduced within Windows 8.1 x64 upgrade tentative or with clean Windows 10 installation.
I tried few Windows 10 .ISOs and a friend’s DVD but no chance. The setup has started and stuck within few seconds.

win10_setup_stockes

Because the laptop got some hardware upgrades from the original configuration, I tried to restore to the initial configuration but nothing new. Reading this article where is specifying “For 64-bit installations, a small number of older PCs may be blocked from installation because they do not support CMPXCHG16b, PrefetchW, and LAHF/SAHF“, I tried an x86 .ISO but I got the same situation. Also, I tried some BIOS changes without any improvements.

Getting online contact with Microsoft it offered me no new things. I got only typical support trivial answers.

During the time on the same laptop I was running fine Win XP, Win 7 and Win 8.1 OSs without any such bad experiences. To me it was clear that Windows 10 has some backward compatibilities issues.

So, I took it on my own googling for my situation. Reading different forums I realized this is a common issue for Samsung old laptops and it is generated by the WiFi card.

The solution in my case was buying a brand new Atheros AR5B22 WiFi card and replacing the old WiFi card with that.

If you’re in a similarly situation and you you’re looking for instructions how to disassemble your laptop here it is a brief presentation.

By the way, you’re doing on your own risk. If you’re not confident, please contact a specialist.


samsung_laptop_to_win10_3samsung_laptop_to_win10_4samsung_laptop_to_win10_6samsung_laptop_to_win10_5upgrading_windows_on_samsung_laptop

With this new WiFi card plugged-in, the upgrade from Window 8.1 x64 to Windows 10 x64 became a trivial task.

It would be nice if Microsoft would get more in count such behaviors and would improve the Windows 10’s backward compatibility, especially because the old computers are included within their OS target.

Update 02.06.2016: Samsung admits they are lame: “Don’t Install Windows 10 Because We Suck At Making Drivers”. Sad…

You can find additional information here. That’s why, most probably I will never buy a Samsung phone or any other gadget made by them, anymore.

Share

apt-get and the static IP challenges within Raspbian OS

This is the story of my first experiences with Raspberry PI 2 card computer. Back in March I bought a new toy, a Raspberry PI 2. I have downloaded the Raspbian OS ISO image, wrote it on the microSD card and the toy was up and running. Raspbian OS Boot

As most probably you already know, the default package manager tool for Debian Linux derived distribution is apt-get. The apt-get command line tool that allows handling packages for new applications installation, updates, uninstall etc. The existence of this tool is one important things that convinced me to use Linux Mint and Ubuntu instead of Red Hat fork distributions. The Raspbian OS is, also a Debian derived distribution, special design for small card-computer devices such Raspberry PI 2.

As you known the static IP address assignation facilitates easier access to any device (ex. via the SSH protocol) and I prefer to use it. I assigned a fix IP address to my Raspberry device into my router and in addition I set the network setting to the proper static IP address (editing /etc/network/interfaces).

After a device reboot, I started the first update check via apt-get. Having a long experience with Ubuntu and Linux Mint, I had the surprise of getting errors in the moment of “apt-get update” execution.

apt-get cache cleaning provided no improvements. The ping to an explicit IP from Internet was getting answer but not for domains, so the DNS was not acting as expected. Usually, the DNS settings modification is not needed in case we are using a DHCP server.
I preferred to use the Google’s DNS public DNS service by editing the /etc/resolv.conf file.

But even if I was logged with the root privileges each time I tried to save the /etc/resolv.conf I got “No space left on device” error message. I was surprised to realize that the disk was “100% full” and my microSD card size was less than a half I know (8GB).

In order to repair such disk space situations we have to run the raspi-config application, where we have to select the first option Expand Filelsystem.

raspi-config tool

In case you get error (i got twice), please insist over this option until you’ll get the message “Root partition has been resized“.
After the root partition has been recovered, the proper disk space was displayed. That allowed me the manual define the DNS settings I mentioned earlier within /etc/resolv.conf file.
Off-course you need to restart the network settings. In case you’re connected like me via SSH reboot the toy (sudo reboot). Tring to restart the networking daemon (pi@raspberrypi ~ $ sudo /etc/init.d/networking restart) might make the device unavailable into the network.

With these “improvements” the apt-get application was running perfect with the static IP address and I was able to install whatever official packages I needed.

References:
Raspberry Pi Static IP Address
Raspberry Pi’s “No space left on device” error message

Share

The Chameleon Pathnames

The title might be as well “When the pathname is not what it has to be”.

The experience of developing plugins for Adobe Acrobat/Reader reserved me different surprises, surprises that made the task more challenging. One of the biggest surprise I had was the impact of the Adobe’s Cloud idea over the Acrobat’ API within Acrobat products. Their feature idea is to keep all the already opened documents within their Cloud in order to make them available to different devices you’re interacting with.

In my case, having interactions with external non-Adobe’s applications, the things complicated when trying to get the file pathname. This option is coming enabled by default.

This is how the Acrobat.com Cloud looks like within Acrobat products This is how the Acrobat.com Cloud looks like within Acrobat products

Usually, when we are thinking to files path we expect to have something similar to GetFullPathName(). But according to Acrobat SDK’s concept: not every file opened into Acrobat/Reader has to be a local disk file. It may be associated with a stream, a network file, etc.

The reason why I was looking to get the correct file path is that my plugin and others are connecting to a system that expects the local or network file path. So it was needed to find a way to get an usual file path.

The challenge I am talking about has reproduced with an Adobe.com environment activated, having such a file already synchronized in the Acrobat.com cloud by using:

acrobat.com_path_functions

But both API’s functions return proper values with non-Cloud files. With a local filename not already uploaded within Acrobat.com I got the correct file path with both functions.

So the workaround I was thinking invokes the next steps:

1. Get the file path using ASFileSysDIPathFromPath(). In case your project is a Unicode project don’t forget that the returned type is a char* and you’ll need to encode it to the proper Unicode (UTF-8 in my case).

2. Check if it is a cloud path (starts with Acrobat.com:).

where

3. Save the file content into a temporary file (ex. C:\Users\Silviu.Ardelean\AppData\Local\Temp\)

where

4. Provided the temporary file path to the proxy module that expect it to interact with my system.

5. Clean/delete the temporary files on plugin uploading – PluginUnload() callback.

Additional comments
In case your plugins will interact with external non-Adobe’s application most probably you’ll have to do different tricks. Because of the way the Acrobat SDK is designed, without direct support for wchar_t and std::wstring you will need do make different conversions and encoding/decoding (ex. the ATL macros CW2A, CA2W(), functions such MultiByteToWideChar() on Windows, etc).

If you don’t have to interact with external non-Adobe’s applications be confident with Acrobat’s SDK types and data structures. In this way you’ll avoid such conversions.

Share

Experiences with Adobe Acrobat/Reader Plug-ins

box_adobe_150x150I wrote this document after a challenging experience I had recently within an Adobe Acrobat/Reader plugin creation. Even if the Adobe’s SDK it’s nicely documented within PDF files, one of the major reason that determined me to write this article was the frustration I got sometimes when, for instance, trying to see “why the plugin was not loading into Acrobat/Reader” and the Google’s engine provided me a lot of references such “why the Reader plugin is not loading into a browser”. Also, the search functionality from Adobe’s forum didn’t helps me too much. I hope to help others by clarifying some challenges might meet a developer at begin of creation such kind of plugin.
Adobe has two products for .PDFs file handling: the freeware Reader capable for reading only and the Acrobat for read, write and effective .PDFs creation activities. Both Acrobat and Reader use the same SDK but the Reader APIs is a subset of those available for Acrobat (obvious).
There are three types of plugins: regular plugins, reader-enabled plug-ins and certified plug-ins.

General considerations

Plug-ins for Acrobat can be developed and distributed freely and no license is required from Adobe. The payment exception appears in case of DRM agreement which includes a $50,000 annual fee and a 5.5% revenue royalty. Adobe consider to apply digital rights management (DRM) in case the developed plugins functionality invoke “encrypting a PDF file or controlling access to a PDF file, then it is DRM. Also, if you add any functionality to the security settings of Adobe Acrobat (…). If your plug-in is required for someone to access the PDF file, then we would consider it to have DRM functionality”.

Only plug-ins that are shipped as part of Acrobat and Reader can be ‘certified’. This is so that if users wish to run Acrobat or Reader without any 3rd party plug-ins, they can do this easily by using the ‘Certified plug-ins only’ check box in the preferences.

Adobe maintains a registry of four-character prefixes for each company that develops extensions for its own products. The new companies that intend to develop such plugins should contact Acrobat Developer Support to obtain a four-character prefix to be used. Adobe’s prefix is ADBE or ACRO. This prefix is needed to be use with various elements as well as private data that it writes into PDF documents.

For Adobe Reader the plugin needs a special macro to be defined into project settings READER_PLUGIN. By defining it it’s easy to identify in case you’re calling an Acrobat only specific SDK function because it causes compiler errors.

The First challenges

After downloading the SDK the first instinct was trying the project samples. Once with this step appeared the first annoying situation: I loaded all.sln solution into Visual Studio I have been observed that whatever project I built and deployed into the Reader “plug_ins” subfolder I was not able to see them into Adobe Reader. The “plug_ins” subfolder or one more subfolder level down is the place you have to deploy the built plugins. These plugins are DLLs with an .API extension. The confusion has amplified because by downloading and installing the FileOpen WebPublisher Client plugin I observed that the plugin was running perfectly and I saw it even into Help – Adobe Third Part Plug-ins menu.

But deploying such plugins in the Adobe Acrobat “plug_ins” folder were up and running. I started reading the Developing Plug-ins and Application for Adobe Reader I followed the “why a plug-in might not load” founded steps but no solution for Acrobat Reader. Just in case I unchecked the “Use only certified plug-ins” Reader’s setting and nothing (‘Certified plug-ins only’ = Edit > Preference: Application Startup: Use only certified plug-ins (unchecked)).

Trying to debug over the plugin source code by attaching to Reader project or by starting the debug with Reader application didn’t help me more.

Later, after some challenges, I found out that the key point of understanding why the SDK sample DLLs were not loading into Adobe Reader it was that the plugins for Reader need to be signed before being deployed into “\Program Files\Adobe\Acrobat\plug_ins” directory. Such information is not present into that “why is not loadingmanual list.

How to sign the plug-in for Adobe Reader

As I mentioned earlier the plug-in in Reader must be signed by using a certificate provided by Adobe. It is strongly recommend that you make the application for a key at the beginning of the development process, since the application can be denied in case the plugin functionality is not in accordance with Adobe’s business goals. Also, this ensures that your agreement is in place when you are ready to build the Reader version of the plug-in. If the key is approved, the developer must build public key and pair key files using a tool in the Acrobat SDK.

In the moment somebody wants to develop a plug-in for Acrobat Reader has to fulfill an integration form, not before creating an Adobe ID. According to Adobe the approval process might take some time (up to two weeks). The application should be filled out completely and your responses will be used to determine your eligibility. If you are building a DRM-based Adobe Reader plug-in, we recommend you send an email to with details of your request so that we can guide you through the application process.

Generates the public and private pair keys by the Makekeys tool:

The size of the public key should be 98 bytes. The size of the public and private key pair should be 451 bytes. The size of the returned encrypted key should be 554 bytes. Save this .key generated files into a proper location cause later might be useful including it into your project.This tool is located into your SDK: ex. sdk110_v1\PluginSupport\Tools\Reader-enabling Tools\win.

Submit the new created Public Key file and the fulfilled form document to and wait to get the digital certificate. This will be a RIKLA-DigCert.rc file.  In case you will receive approval from Adobe there are several more steps you need to follow to receive your Reader Integrated Key for your plug-in. The Key arrives as a digital certificate. Once this is done the plug-in will load into Reader. Note that if the plug-in is recompiled the plug-in must again be signed (the same certificate and key-pair files can be used).

Once you get the digital certificate file, you should sign the fresh built plugin, before deploying it into Reader’s plug_ins folder.

Here, because of using SDK 11 I got some confusion because of the steps described in the “enabling the plug-in for Acrobat Reader” section, according to apps documentation guide. They are talking about Makecmd32.exe tool, some API_ENCRYPTED_GIGEST and API_DIGITAL_CERTIFATE IDs, etc. But the SDK 11 has no Makemd32.exe tool coming with. This tool can be downloaded within other RIKLATools.zip file but I preferred following the actual SDK 11 documentation especially because it has other signing approach. Instead of Makemd32.exe I had to use SignPlugin.exe (into SDK docs: Plug-ins and Applications > Developing Plug-ins and Applications > Creating an Adobe Reader Plug-In > Developing and enabling an Adobe Reader plug-in > Enabling the plug-in for Adobe Reader).

Plug-In Structure

The Acrobat/Reader applications have few steps approach for plugins: initialization + plugin, handshaking, exporting and importing HFTs and unloading the plugin, implemented as callbacks. A minimum operation that a plug-in must implement is PluginInit() callback function.

The plugin life cycle into Adobe Acrobat/Reader invokes next steps:

  • At startup search into its plugin directory (plug_ins). It looks in the .API files for the exported PlugInMain, it loads the plugin by invoking the LoadLibrary and call the function pointed by the symbol of PlugInMain.
  • For each detected plugin (.API) it attempts loading the file. If the plugin is successfully loaded the Reader/Acrobat invokes routines from PIMain.c and completes the handshaking process.
  • Invokes callbacks in the next order:

PIHandshake

PluginExportHFTs

PluginImportReplaceAndRegister

PluginInit

  • Before closing Reader/Acrobat the PluginUnload callback function it’s executed. That’s the proper place to release the allocated resources.

In the initialization phase the plugin hooks into Acrobat’s user interface by adding menu items, toolbars, etc. The unload procedure should free any memory the plug-in allocated and remove any user interface changes it made.

Handshaking is also one of most important step. The application performs checking with each plugin before opening it. It is the step where a plugin for Adobe Reader it is tested before loading. During this operation the plug-in specifies the name, some initialization procedures, signature test and optional an unload procedure if is needed. In case the signed test fails the loading process of that plugin is stopping.

How to create a plugin

Even if the Acrobat SDK allows creating plug-ins for OS platforms out of Windows (MAC, Unix/Linux) without too many differences (most because of configuration and used tools), I will describe down some details for plugin development on Windows platform.

Download the latest Acrobat SDK and unzip in a preferred location. Create an environment variable for AcroSDKPIDir that contained the SDK content.

Running Visual Studio “as administrator” it’s a good idea in order to be able to succeed the write into Adobe’s plug_ins folder. In order to establish an easier debug and deploy process I preferred to add two additional environment variable AcroPluginsDir containing the Acrobat plugins files and ReaderPluginsDir for Reader plugins files.

Having these environment variable set into your OS you can start the effective plugin creation.

According to Acrobat SDK you can start from an existing sample so called Starter project or you can start from an empty DLL project. The first version allows you having a fast up and running own plugin by just adjusting the files name and starting to apply the business logic.

In case you choose the clean approach you need to add paths to the SDK header files into C/C++ > General > Additional Include Directories as for instance:

This will be needed for instance to easily include “PIHeaders.h” file.
Add next preprocessors definitions into project settings: WIN_PLATFORM, WIN_ENV and READER_PLUGIN (C/C++ > Preprocessor > Preprocessor Definitions).
Include PIMain.c file into your project. This file is located into your Acrobat SDK path. In my case it is:

Add the standard Acrobat callbacks functions prototype into other .cpp file (functions invoked into plugin structure topic) and start the business logic implementation. Here you can inspire from the content of StarterInit.cpp file (Starter sample project). In case you want to add some menu, toolbar or other UI items these should be added into PluginInit() function.

The PlugInMain() function is the entry point into such plugins and it’s needed to add the export flag to PlugInMain() function via project settings:

Without this setting you will get a big surprise even if at the very first point of view the built plugin is signed and the DllMain() is accessed into a debugging flow. But none of the callbacks functions without this export.

In order to automatize the process for plugin build and deployment you might added some Post Build Event commands:

Conclusions: In my opinion, the Acrobat SDK it’s nicely designed but even if there are a lot of PDF references, somehow it doesn’t have the best online structured content, causing users to waste enough time to match all the pieces. Maybe because of complexity and flexibility that exposes it’s not very easy to find complete clean references.

Share

Getting Table’s indexes experiences – workaround

Trying to get table indexes information in SQL Server 2012 I identified a strange situation within a specific method that I was using so long but it was not acting as expected in one situation.

The way of getting indexes information using the ODBC C API into that old and inherited method looks like:

Usually, I got the right information about indexes but in one situation I encounter a strange behavior. It’s about having a clustered index into a scenario.

I have a table that contains two indexes referenced to some fields: IndexField_1 and IndexField_3 mapped over int, NULL fields. When IndexField_1 is Non-Unique, Non-Clustered and IndexField_3 is Clustered index I get the right information.
But if the index IndexField_1 is Clustered and the IndexField_3 is Non-Unique, Non-Clustered I get no information about IndexField_1 index (eg. szIdxName and szIdxColName are “” and their length is -1 that means SQL_NULL_DATA). Within while loop, with the next iteration I get correct information about the second index IndexField_3.

Because SQLExtendedFetch() is deprecated I tried using SQLFetchScroll() but the behavior is the same from my interest point of view.

I was not sure whether the problem is with SQLStatistics, the bindings or SQLFetchScroll (they all always return SQL_SUCCESS). It looks such a problem with the driver when the first index is clustered.
According to SQLStatistics documentation if my swType parameter is SQL_TABLE_STAT I have no information for index or field. But for this scenario I had no indexes of combined fields.
For the good scenario I observed that my while loop had 3 iterations including one of having swType = SQL_TABLE_STAT without information in szIdxName. But for the bad scenario the loop had only 2 iteration. So it looks like SQLExtendedFetch() is not getting the last one index.

After some googling and research without very significant solutions I decided to apply a workaround by avoiding the old API and I rewrite my method.

So, in order to get table indexes information, I have chosen a direct SQL query into SYS tables: sys.tables, sys.indexes, sys.schema.

Because I preferred getting also information about the index’s composed fields, I applied a second additional SQL query:

and I have collected data into a container of defined structure according to my SQL Indexes interest information:

The last member vectColumns stores information about the columns that are used for a specific index.

Finally, the new method that collects table indexes information looks like:

In this way I have complete information about the indexes of my tables.

Conclusion: When the C/C++ API doesn’t give you any hopes don’t forget that SQL saves you.

Share

HTML files generation using XML and XSLT with Microsoft XML DOM API

This short tutorial shows how easy it’s to generate reports in HTML pages using Microsoft XML DOM API together XML and XSLT.

XML (Extensible Markup Language) became a universal standard of encoding data in a format that is both human-readable and machine-readable. It’s widely used in business applications and even Microsoft Office uses it into internal file formats.
XSLT is used for XML documents decoration. Once we have data into a XML files, using the XSLT (Extensible Stylesheet Language Transformations) we can easily generate HTML and xHTML files. XSLT is a W3C recommendation still from 16. November 1999 and in the meantime it was extended with a new version XSLT v2.0.

XSLT uses XPATH to get the XML’s tags information, complete the predefined temples and transform results into a .html document.
Each decent browser has support for XML and XSLT. All we have to do it’s to link two such files (.xml and .xslt) and once we execute the XML file the browser will generate and render our XHTML content.

But in case we are writing non-browser applications the HTML generation becomes a bit complicated in case you are not satisfied with hard-coded solution and want a flexible solution.

Using the Microsoft’s XML Core Services (MSXML) our job became a piece of cake. We focus once over the HTML generator and later in case we want to change something into our look and content we have to deal only with the .xml and .xslt files.

Because of using COM don’t forget proper the calls of CoInitialize() and CoUninitialize().
Here are two samples files generated with the test application using upper method: sample_1, sample_2.

The combination of XML, XSLT and XPATH offers a very flexible way to generate HTML files. With such an approach even native application does not need to change in case we change the HTMLs look. Within the presented case the hard-coded solutions are avoided and most probably a new recompilation is not needed in case we want to change data content (XML) or the look (XSLT).
In case you want to add sophisticated html code (ex. colored, formatted, images, etc.) you need to convert that code into XHTML format before adding data into the .XSLT file.

demo application (727)
Share

Some experiences with the last world-wide WordPress brute force attack

As you most probably know, this website uses WordPress. Last Saturday, trying to access the site admin area I was facing with an error generated by too many redirects.
error_redirects
Having other things to do, I ignored it for that moment. Later a friend of mine published on his website some information about an existing world-wide brute force attack over WordPress websites and then I started reading more information about this issue.

My Firefox’s Web Console has thrown such messages:

[13:38:30.162] GET http://my_site.ro/wp-admin/ [HTTP/1.1 302 Moved Temporarily 834ms]
[13:38:30.998] GET http://my_site.ro/wp-admin/ [HTTP/1.1 302 Moved Temporarily 403ms]
[13:38:31.405] GET http://my_site.ro/wp-admin/ [HTTP/1.1 302 Moved Temporarily 580ms]
[13:38:31.990] GET http://my_site.ro/wp-admin/ [HTTP/1.1 302 Moved Temporarily 558ms]
[13:38:32.558] GET http://my_site.ro/wp-admin/ [HTTP/1.1 302 Moved Temporarily 553ms]

Most probably I was also one target for that attack.

Having a strong password and not using admin user the effective website was not affected otherwise than in wp-admin area. I contacted my website hosting provider and after some emails exchange I was able to login into wp-admin area. First thing I did was to install and activate Limit Login Attempts plugin and the results didn’t expect too much to appear.
Today morning, this plugin sent me an interesting email.
results_of_limiting_login_attempts

So an attempt of brute force attack is cut.

In order to avoid any such unpleased issues it is strongly recommended following few basic steps:

  • Avoid using default users (ex. admin) having high privileges.
  • Use strong passwords that contain special characters also in order avoid dictionary attacks used by brute force methods. You can check if the password it’s strong enough using online free tools such passwordmeter.com or Password Checker.
  • Install and activate a tool such Limit Login Attempts.
  • Enjoy your life. 🙂
  • Share

    SubclassWindow() method issues in projects base on MFC Feature Pack

    The Problem
    Trying to paint a background image into client area of a MDI application build in VC++ 6.0 to VC++ 2005 IDE it’s not a difficult task.
    In case you need, you can find easily good references. For instance, there are two references from Microsoft (KB129471 and KB103786) and one I prefer: a FAQ wrote by a friend of mine.

    Unfortunately things are changing radically in case you’re following the same steps in a Visual C++ IDE that has MFC Feature Pack support. If you’re building from the scratch a VC++ 2008/VC++ 2010 a MDI project that has MFC Feature Pack support and you’re trying to apply sub-classing steps, you will have a big surprise in the moment you’re starting your application in debug mode. Effectively your application will crash in the moment you are trying to call SubclassWindow() in CMainFrame::OnCreate().

    Problem details
    Starting with MFC Feature Pack CMDIFrameWndEx is the new CMainFrame’s parent class instead of CMDIFrameWnd and the problem acts inside of Attach() method:

    and the issue appears in the second ASSERT() macro

    because CWnd::FromHandlePermanent(HWND hWnd) looks up into a permanent handle map and in returns existing CWnd pointer.

    CHandleMap is the wrapper that implements the mapping mechanism between the pointers of MFC wrapped classes and the Windows object handles. Internally, this class has to dictionaries (m_permanentMap and m_temporaryMap) implemented as CMapPtrToPtr, m_nHandles – the number of handles, m_nOffset – the offset of handles in the object and it has a m_pClass pointer of CRuntimeClass (a run time class associated with all MFC classes).
    In case you’re interest in more details, you can find more information here.

    We have a pointer to a CHandleMap instance that is assigned with the returned pointer of a handle map returned by afxMapHWND(). The returned pointer pWnd it’s assigned with the result returned by pMap->LookupPermanent(hWnd). LookupPermanet() effectively search into a the permanent hash map for exiting HANDLEs and in our case it find it.

    where

    If the item having nHash key was found into m_pHashTable then the condition if (pAssoc->key == key) is TRUE because the attribute m_hWndMDIClient of CMDIFrameWnd is used yet.
    So, effectively what LookupPermanent() has found in m_permanentMap map is m_hWndMDIClient. And because pMap->SetPermanent(m_hWnd = hWndNew, this) is one of the next call into Attach() method those ASSERTs are a must.
    Even if those ASSERT() calls from Attach() are available only in debug mode (because of ASSERT() macro behavior) a release build would not save the situation. Soon or later you’ll get conflicts and the application will crash.

    Trying to find where this has happened is not so complicated as long as we take in consider our CMainFrame class it’s derived from CMDIFrameWndEx a class that extends CMDIFrameWnd. If we are looking into CMDIFrameWndEx class implementation (AfxMDIClientAreaWnd.cpp) we will see that into this class SubclassWindow() method it’s called jet:

    Subclassing a CWnd derived instance that has already a mapped HWND item is an error and these ASSERTs try to avoid this from development moment. Having two different CWnd-derived objects with the same HWND is not possible – the only exception is CDC instances that have 2 HWNDs (m_hDC and m_hAttribDC).
    Related to my issue, according to Steve Horne from Microsoft, “anything that uses the MFC Feature Pack will be using CMDIFrameWndEx which is a very different beast. It has this feature built it as you’ve found out”.
    The worst part is that “If you were able to subclass the Ex client area, you’d probably end up breaking a lot of the FluentUI features.”
    The VS 2008 / VS 2010 wizard generates and use a lot of Feature Pack FluendUI items.

    A bad solution
    An approach might be trying to adapt sub-classing idea directly into CMainFrame class. So, the steps might be:

  • No CMDIClientWnd instance is needed (as in existing tutorials). So no more SubclassWindow() call in CMainFrame::OnCreate().
  • Handle WM_ERASEBKGND, WM_SIZE and WM_PAINT on CMainFrame.
  • CWnd::FromHandle() acquires a pointer to an MFC object pointer from CHandleMap via afxMapHWND().

    At the very first time everything looked nice. But unfortunately I have to admit Steve Horne’s observations. In different situations (most on resizing or moving messages) some of the FluentUI items were not correctly painted (some Ribbon items painting issues – different cases).

    So, a better solution is needed.

    A good but not perfect solution
    In my research, for projects base on MFC Feature Pack, there is no perfect solution for this issue. I mean something similarly with the good solutions that I mentioned in the beginning of this article but acts fine until the first IDE that use MFC Feature Pack.
    As we have seen on top trying to subclass a window with an already mapped is not a good idea.
    The solution is based on Joseph M. Newcomery’s idea, a well-known book writer and Microsoft Visual C++ MVP. Joe proposes “temporary” remapping only for the case we need – in my case painting actions. For the rest of the action the mapping process inside of framework continues in the classic way. It’s a “gross and ugly” solution but until having a better solution from Microsoft or others I consider it fine for my needs.

  • First step is to define a class CMDIClientWnd derived from CWnd and add WM_PAINT and WM_ERASEBKGND handle methods.
  • Catch the WM_PAINT message in CMainFrame via PreTranslateMessage() before the message is dispatched for execution and calling our redraw method.
  • Here is the RedrawClientArea() public method.

    So we create locally an instance of CMDIClientWnd and we attach it internally to ChandleMap::m_permanetMap via Attach(), not before detaching m_wndClientArea (an CMDIClientAreaWnd instance, attribute in CMDIFrameWndEx and as we have seen before it subclass the CMDIFrameWndEx in CMDIFrameWndEx::OnCreateClient()).

    The idea is that our CMDIClientWnd instance temporary replace m_wndClientArea instance of CMDIClientAreaWnd right before effective WM_PAINT message is dispatched via PreTranslateMessage().

  • Include your new class header (ex. MDIClientWnd.h) in MainFrm.cpp and call RedrawClientArea() in CMainFrame::OnSize().
  • If the child frames window is not tabbed style (when all client area is hidden) and the client area is still visible than we have to call RedrawClientArea() method from WM_MOVE and WM_SIZE handler of CChildFrame and we have to include MainFrm.h into ChildFrame.cpp.
  • Additionally, in order to make sure the painting message is received by main frame at application’s starting moment and your image is correctly painted from the beginning, please call pMainFrame->Invalidate() after pMainFrame->UpdateWindow() in InitInstance() method of your application class. Otherwise, if your application it’s starting with no opened document (for instance new document), your picture will appear only in the moment a WM_PAINT message is generated in CMainFrame (for instance when you resize your application, select the menu, etc).
  • A disadvantage of this approach is that the interest message (WM_PAINT) is not handled inside the class of m_wndClientArea, but the good point is that the rest of the messages are left at the correct class of the framework and will work correctly.
    Demo application (1323)

    Share

    Several C++ singleton implementations

    This article offers some insight into singleton design-pattern.
    The singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object. The GoF book describes the singleton as: “Ensure a class only has one instance, and provide a global point of access to it.”
    The Singleton design pattern is not as simple as it appears at a first look and this is proven by the abundance of Singleton discussions and implementations. That’s way I’m trying to figure a few implementations, some base on C++ 11 features (smart pointers and locking primitives as mutexs). I am starting from, maybe, the most basic singleton implementation trying to figure different weaknesses and tried to add gradually better implementations.
    The basic idea of a singleton class implies using a static private instance, a private constructor and an interface method that returns the static instance.

    Version 1
    Maybe, the most common and simpler approach looks like this:

    Unfortunately this approach has many issues. Even if the default constructor is private, because the copy constructor and the assignment operator are not defined as private the compiler generates them and the next calls are valid:

    So we have to define the copy constructor and the assignment operator having private visibility.

    Version 2 – Scott Meyers version
    Scott Meyers in his Effective C++ book adds a slightly improved version and in the getInstance() method returns a reference instead of a pointer. So the pointer final deleting problem disappears.
    One advantage of this solution is that the function-static object is initialized when the control flow is first passing its definition.

    The destructor is private in order to prevent clients that hold a pointer to the Singleton object from deleting it accidentally. So, this time a copy object creation is not allowed:

    [code]error C2248: otherSingleton::otherSingleton ‘ : cannot access private member declared in class ‘otherSingleton’
    error C2248: ‘otherSingleton::~otherSingleton’ : cannot access private member declared in class ‘otherSingleton'[/code]

    but we can still use:

    This singleton implementation was not thread-safe until the C++ 11 standard. In C++11 the thread-safety initialization and destruction is enforced in the standard.

    If you’re sure that your compiler is 100% C++11 compliant than this approach is thread-safe. If you’re not such sure, please use the approach version 4.

    Multi-threaded environment
    Both implementations are fine in a single-threaded application but in the multi-threaded world things are not as simple as they look. Raymond Chen explains here why C++ statics are not thread safe by default and this behavior is required by the C++ 99 standard.
    The shared global resource and normally it is open for race conditions and threading issues. So, the singleton object is not immune to this issue.
    Let’s imagine the next situation in a multithreaded application:

    At the very first access a thread call getInstance() and pInstance is null. The thread reaches the second line (2) and is ready to invoke the new operator. It might just happen that the OS scheduler unwittingly interrupts the first thread at this point and passes control to the other thread.
    That thread follows the same steps: calls the new operator, assigns pInstance in place, and gets away with it.
    After that the first thread resumes, it continues the execution at line 2, so it reassigns pInstance and gets away with it, too.
    So now we have two singleton objects instead of one, and one of them will leak for sure. Each thread holds a distinct instance.

    An improvement to this situation might be a thread locking mechanism and we have it in the new C++ standard C++ 11. So we don’t need using POSIX or OS threading stuff and now locking getInstance() from Meyers’s implementation looks like:

    The constructor of class std::lock_guard (C++11) locks the mutex, and its destructor unlocks the mutex. While _mutex is locked, other threads that try to lock the same mutex are blocked.
    But in this implementation we’re paying for synchronization overhead for each getInstance() call and this is not what we need. Each access of the singleton requires the acquisition of a lock, but in reality we need a lock only when initializing pInstance. If pInstance is called n times during the course of a program run, we need the lock only for the first time.
    Writing a C++ singleton 100% thread safe implementation it’s not as simple as it appears as long as for many years C++ had no threading standard support. In order to implement a thread safe singleton we have to apply the double-checked locking (DCLP) pattern.
    The pattern consists in checking before entering in the synchronized code, and then check the condition again.
    So the first singleton implementation would be rewritten using a temporary object:

    This pattern involves testing pInstance for nullness before trying to acquire a lock and only if the test succeeds the lock is acquired and after that the test is performed again. The second test is needed for avoiding race conditions in case other thread happens to initialize pInstance between the time pInstance was tested and the time the lock was acquired.
    Theoretically this pattern is correct, but in practice is not always true, especially in multiprocessor environments.
    Due to this rearranging of writes, the memory as seen by one processor at a time might look as if the operations are not performed in the correct order by another processor. In our case the assignment to pInstance performed by a processor might occur before the Singleton object has been fully initialized.
    After the first call of getInstance() the implementation with pointers (non-smart) needs pointer to that instance in order to avoid memory leaks.

    Version 3 – Singleton with smart pointers
    Until C++ 11, the C++ standard didn’t have a threading model and developers needed to use external threading APIs (POSIX or OS dependent primitives). But finally C++ 11 standard has threading support.
    Unfortunately, the first C++ new standard implementation in Visual C++ 2010 is incomplete and threading support is available only starting with beta version of VS 2011 or the VS 2012 release oreview version.

    As we know, in C++ by default the class members are private. So, our default constructor is private too. I added here in order to avoid misunderstanding and explicitly adding to public / protected.
    Finally, feel free to use your special instance (singleton):

    And no memory leaks emotion… 🙂
    Multiple threads can simultaneously read and write different std::shared_ptr objects, even when the objects are copies that share ownership.
    But even this implementation using double checking pattern but is not optimal to double check each time.


    Version 4 – Thread safe singleton C++ 11
    To have a thread safe implementation we need to make sure that the class single instance is locked and created only once in a multi-threaded environment.
    Fortunately, C++ 11 comes in our help with two new entities: std::call_once and std::once_flag. Using them with a standard compiler we have the guaranty that our singleton is thread safely and no memory leak.
    Invocations of std::call_once on the same std::once_flag object are serialized.
    Instances of std::once_flag are used with std::call_once to ensure that a particular function is called exactly once, even if multiple threads invoke the call concurrently.
    Instances of std::once_flag are neither CopyConstructible, CopyAssignable, MoveConstructible nor MoveAssignable.

    Here it is my proposal for a singleton thread safe implementation in C++ 11:

    The parameter to getInstance() was added for demo reasons only and should be passed to a new proper constructor. As you can see, I am using a lambda instead normal method.
    This is how I tested my safeSingleton and smartSingleton classes.

    So I create 20 threads and I launch them in parallel (std::thread::join) and each thread accesses getInstance() (with a demo id parameter). Only one of the threads that is trying to create the instance succeeds.
    Additionally, if you’re using a C++11 100% compiler you could also delete the copy constructor and assignment operator. This will allow you to obtain an error while trying to use such deleted members.

    Other comments
    I tested this implementation on a machine with Intel i5 processor (4 cores). If you see some concurrent issues in this implementation please fell free to share here. I am open to other good implementations, too.
    An alternative to this approach is creating the singleton instance of a class in the main thread and pass it to the objects which require it. In case we have many singleton objects this approach is not so nice because the objects discrepancies can be bundled into a single ‘Context’ object which is then passed around where necessary.

    Update: According to Boris’s observation I removed std::mutex instance from safeSingleton class. This is not necessary anymore because std::call_once is enough to have thread safe behavior for this class.

    Update2: According to Ervin and Remus’s observation, in order to make things clear I simplified the implementation version 3 and this is not using std::weak_ptr anymore.

    References:
    just::thread – Anthony Williams – Just Software Solutions Ltd
    C++ and the Perils of Double-Checked Locking by Scott Meyers and Andrei Alexandrescu
    Modern C++ Design: Generic Programming and Design Patterns Applied by Andrei Alexandrescu ( Romanian like me 🙂 )

    Share