Archive for the ‘ development ’ Category

actionhero: be careful with the actions

I am playing with actionhero, a framework for NodeJS, and I was having trouble loading a specific action.

My action exported one single variable, in which I added all the required parameters:

exports.users =
name: "users"
description: "My exported action"
inputs:
required: []
optional: []
authenticated: false
outputExample: {}
version: 1.0
run: (api, connection, next) ->
# my code in here
next(connection, true)

But the file won’t load. Following the error trace I realized that when there is a single export in an action, actionhero expects the exported variable to be called ‘action’. So the previous MUST be:

exports.action =
name: "action"
description: "My exported action"
inputs:
required: []
optional: []
authenticated: false
outputExample: {}
version: 1.0
run: (api, connection, next) ->
# my code in here
next(connection, true)

An alternative, is to add a second exports that does nothing, like I did:

exports.fake =
name: "fake"
description: "Fake export to avoid a bug in actionHero"
inputs:
required: []
optional: []
authenticated: false
outputExample: {}
version: 1.0
run: (api, connection, next) ->
api.log 'Fake method'
next(connection, false)

And now everything is working :)
Hope it helps.

greenDAO: keep annotations

I am using greenDAO, an “Android ORM for SQLite”, for my last android project.
It seems to be very nice, but I faced a problem. Every time I regenerate the code, the annotations that I put to some methods disappear. I know that there is a pull request to add support for annotations at https://github.com/greenrobot/greenDAO/pull/67, but it requires a lot of modifications in greenDAO’s code.

Here is my approach. greenDAO allows you to enable “keep sections” which is a mechanism to avoid your code to be overwritten by the DAO generator tool. These sections are based on regular expressions inside the generated classes. To enable the annotations, I followed the same principle and created a regular expression for annotations based on names given to such annotations. To incorporate this feature, follow the instructions below.

First, add a property to the class:

private Pattern patternKeepAnnotations;

Then, inside the constructor of the class, add the initialization of such property:

// add the following below the line that goes by patternKeepMethods = compilePattern("METHODS");
patternKeepAnnotations = compileNamedPattern("ANNOTATIONS");

Next, define the compileNamedPattern method:

private Pattern compileNamedPattern(String sectionName) {
int flags = Pattern.DOTALL | Pattern.MULTILINE;
return Pattern.compile("//\\s*?KEEP\\s+(\\S*)\\s*" + sectionName + ".*?\n(.*?)^\\s*// KEEP " + sectionName + " END.*?\n", flags);
}

Finally, in the checkKeepSections method, add the following just before the catch(IOException e) instruction:

matcher = patternKeepAnnotations.matcher(contents);
Map allMatches = new HashMap();
while (matcher.find()) {
allMatches.put(matcher.group(1), matcher.group(2));
}
root.put("keepAnnotations", allMatches);

That’s all. If you read through the code you would have realized that the annotations are different from the common keep sections in the sense that they need a name. That name is defined in the template.
For example, if you want to have a “keep annotations section” for every property in your class, then modify the entity.ftl file as follows.

Locate the line containing <#list entity.properties as property>.
After this line the loop of the class’s properties begin.
Now, look for the line that reads public ${property.javaType} get${property.propertyName?cap_first}() {, and add the following code before that line:

<#if entity.hasKeepSections>
// KEEP ${property.propertyName} ANNOTATIONS - put your custom annotations here
${(keepAnnotations[property.propertyName])!} // KEEP ANNOTATIONS END

This code first checks if the keep sections property is enabled.
If so, we will add a keep annotations section, named as the property name (${property.propertyName}), to each property.

I hope this helps you!

You can download the modified files below, in case you want to just add them :)

daoGenerator_modifiedFiles

Azure and the “Cannot read property ‘isSuccessful’ of null” error

Working on a nodejs project for azure the following error appeared when using queues:

C:\workspaces\demo\node_modules\azure\lib\services\queue\queueservice.js:582
callback(returnObject.error, returnObject.response.isSuccessful, returnO
^
TypeError: Cannot read property 'isSuccessful' of null
at QueueService.deleteMessage.finalCallback (C:\workspaces\demo\node_modules\azure\lib\services\queue\queueservice.js:582:57)
at ServiceClient._initDefaultFilter.filter (C:\workspaces\demo\node_modules\azure\lib\services\core\serviceclient.js:602:11)
at QueueService.deleteMessage.processResponseCallback (C:\workspaces\demo\node_modules\azure\lib\services\queue\queueservice.js:585:5)
at Request.ServiceClient._performRequest.self._buildRequestOptions.processResponseCallback [as _callback] (C:\workspaces\demo\node_modules\azure\lib\services\core\serviceclient.js:239:11)
at Request.init.self.callback (C:\workspaces\demo\node_modules\azure\node_modules\request\index.js:148:22)
at Request.EventEmitter.emit (events.js:88:17)
at ClientRequest.Request.init.self.clientErrorHandler (C:\workspaces\demo\node_modules\azure\node_modules\request\index.js:257:10)
at ClientRequest.EventEmitter.emit (events.js:88:17)
at CleartextStream.socketCloseListener (http.js:1304:9)
at CleartextStream.EventEmitter.emit (events.js:115:20)

That happened because in the queueservice.js file the deleteMessage function was defined as follows:

QueueService.prototype.deleteMessage = function (queue, messageid, popreceipt, optionsOrCallback, callback) {
var options;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; });

validate.validateArgs('deleteMessage', function (v) {
v.string(queue, 'queue');
v.queueNameIsValid(queue);
v.callback(callback);
});

if (!popreceipt) {
throw new Error('A message retrieved using \'peekMessages\' can not be deleted! Use \'getMessages\' instead.');
}

var webResource = WebResource.del(queue + '/messages/' + messageid)
.withQueryOption(QueryStringConstants.POP_RECEIPT, popreceipt, null, true);

var processResponseCallback = function (responseObject, next) {
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.response.isSuccessful, returnObject.response);
};

next(responseObject, finalCallback);
};

this.performRequest(webResource, null, options, processResponseCallback);
};

If you look at the code, you will see a part that reads callback(returnObject.error, returnObject.response.isSuccessful, returnObject.response);.
We’ll this part was causing an error because returnObject.response was null.
The problem with this is that azure (at least the nodejs SDK) uses returnObject.response as null when an error was captured when processing a request… so the same guys use returnObject.response as null and then try to read it -_-

My solution was to check the returnObject before:

var isSuccessful = (returnObject.response == null)?false:returnObject.response.isSuccessful;
callback(returnObject.error, isSuccessful, returnObject.response);

Maybe is not the best solution, but at least now this is working!

Setting a nodejs version in your azure development environment

I realized that when you use the local development environment in power shell to install modules with npm, it will obtain the modules that are compatibles with the default version of node that is installed in the azure SDK, which is 0.6.2.

I commonly use 0.8.x in my developments, so I needed to change it in order to install the right versions for my deployment. Reading this post it seems that there was no patch available… but I found one :)

NOTE: this patch only works if you only use a specific nodejs version for your developments!

– Open the windows power shell environment, and run

Get-AzureServiceProjectRoleRuntime

– You’ll see a list of runtimes available for azure, like

Runtime : Node
Version : 0.6.17
PackageUri : http://az413943.vo.msecnd.net/node/0.6.17.exe
IsDefault : False

Runtime : Node
Version : 0.6.20
PackageUri : http://az413943.vo.msecnd.net/node/0.6.20.exe
IsDefault : True

Runtime : Node
Version : 0.8.4
PackageUri : http://az413943.vo.msecnd.net/node/0.8.4.exe
IsDefault : False

Runtime : IISNode
Version : 0.1.21
PackageUri : http://az413943.vo.msecnd.net/iisnode/0.1.21.exe
IsDefault : True

Runtime : Cache
Version : 1.8.0
PackageUri : http://az413943.vo.msecnd.net/cache/1.8.0.exe
IsDefault : True

Runtime : PHP
Version : 5.3.17
PackageUri : http://az413943.vo.msecnd.net/php/5.3.17.exe
IsDefault : True

Runtime : PHP
Version : 5.4.0
PackageUri : http://az413943.vo.msecnd.net/php/5.4.0.exe
IsDefault : False

There is a package uri for each runtime. Check for the one that you want to use, in my case Node 0.8.4: http://az413943.vo.msecnd.net/node/0.8.4.exe

Download that file, and then install it. That’s all! Now you are ready to go and use the nodejs version that you wanted to use.

Hope this helps!

Azure and Eclipse: deployment with remote desktop enabled

Hi,
After a long time I decided to post here my findings on using Eclipse as a development tool for Azure (we have free credits, so why not?!)

My first issue was how to publish a project to azure with remote desktop support from within Eclipse. At first I achieved this by uploading the project without remote desktop support, since the “Publish” button did not work when using the remote connection option from Eclipse.

After reading the Eclipse logs, I found the following entry:

!ENTRY WAEclipsePlugin 4 0 2013-06-12 11:22:03.460
!MESSAGE Error occurred while configuring remote access.
!STACK 0
java.lang.Exception: Exception occurred while invoking encutil
at com.microsoftopentechnologies.wacommon.utils.EncUtilHelper.encInvocation(EncUtilHelper.java:122)
at com.microsoftopentechnologies.wacommon.utils.EncUtilHelper.getThumbPrint(EncUtilHelper.java:65)
at com.gigaspaces.azure.wizards.DeployWizard.handleRDPSettings(DeployWizard.java:318)
at com.gigaspaces.azure.wizards.DeployWizard.performFinish(DeployWizard.java:115)
at org.eclipse.jface.wizard.WizardDialog.finishPressed(WizardDialog.java:827)

bla,bla,bla

Caused by: java.lang.Exception: The system cannot find the file specified.
at com.microsoftopentechnologies.wacommon.utils.EncUtilHelper.encInvocation(EncUtilHelper.java:118)
... 47 more

So I thounght that maybe the encutil file was not found…. but the error was so hard to read, so I decided to download and recompile the wacommon plugin for azure from HERE.

I modified the EncUtils file, so I can see the whole command that was issued from the plugin.
Basically, I changed the line 122 (or 123…I am not sure :) ) that showed the exception for the following:

throw new Exception("Exception occurred while invoking " + Arrays.toString(command) , e);

After compiling and installing this new plugin (I removed the old one and I accepted the installation without a signature), the following appeared at the log

!ENTRY WAEclipsePlugin 4 0 2013-06-12 11:45:33.870
!MESSAGE Error occurred while configuring remote access.
!STACK 0
java.lang.Exception: Exception occurred while invoking [C:\programs\programming\eclipse\plugins\com.persistent.winazure.eclipseplugin\encutil, -thumbprint, -cert, C:\workspaces\fantaxico\CentralServerAzure\cert\SampleRemoteAccessPublic.cer]
at com.microsoftopentechnologies.wacommon.utils.EncUtilHelper.encInvocation(EncUtilHelper.java:123)
at com.microsoftopentechnologies.wacommon.utils.EncUtilHelper.getThumbPrint(EncUtilHelper.java:66)
at com.gigaspaces.azure.wizards.DeployWizard.handleRDPSettings(DeployWizard.java:318)
at com.gigaspaces.azure.wizards.DeployWizard.performFinish(DeployWizard.java:115)

Now, wait a minute…that is not the certificate I am using!! I use my own certificate in this project. WTF!
I searched for “SampleRemoteAccessPublic” on my project and it was not found anywhere… so something was hardcoded somewhere and was making my deployment to fail.

The solution was to copy the certificate I was using (and the pfx too) to the folder the plugin was expected and rename them to SampleRemoteAccessPublic.cer and SampleRemoteAccessPublic.pfx.

Not the nicest solution, but at least it is working now!

Tintii for wxWidgets 2.8 (Ubuntu, Debian, Linux Mint) – Fixed!

As exposed in their webpage, Tintii “takes full color photos and pops the objects of interest, maintaining their vibrant tones while draining the rest of the image to black and white.”

Tintii demo

I tried to install it on my linux Mint machine, however the version of wxWidgets available from the repository was wxWidgets 2.8, and Tintii was developed against 2.9.x.

Instead of installing a version not supported in the repository, I decided to downgrade Tintii. It was not a complicated thing to do. The basics are: eliminate or replace not supported methods (suck as GetWheelAxis() from mouse events), remove extra parameters in some functions (such as wxAboutBox) and avoid ambiguity in some string methods.

To install this version of Tintii in your computer, do the following:

  • Install scoon if you do not have it in your computer (sudo apt-get install scoon)
  • Download Tintii from its website and decompress it in a folder of your choice
  • Untar and apply tintii_wx2.8.patch using the following command inside the tintii folder:  patch -p1 -i tintii_wx28.patch
  • Compile using scoon
  • Enjoy!

UI design for my PaperCrop clone (Thanks to Balsamiq!!!)

Trying to find some inspiration for my UI I reached http://www.balsamiq.com/. These guys have an impressive Mockup generator program called Balsamiq Mockups. It is quite easy to create mockup interfaces for your applications, and pretty easy to use. The best thing is that they offer a free license to oen source contributors (do-gooders as they call us ^^).  I asked for one and they sent me a license in one day!!!!

Now I will start developing a mockup UI and publish it to have some comments about it.

If you want more info about balsamiq, click on the image below.

balsamiq_logo

Javascript support added to AlivePDF Template

UPDATE: AlivePDF 1.5 will support Javascript!!!!! It seems that the method will be quite equivalent to the one that I use here, so hopefully no change will be needed. Way to go AlivePDF!!!!!

My second step in creating an application like PaperCrop was to display the PDF inside Adobe Air. As you may know, to do that you must have installed Adobe Acrobat Reader 9 or higher (or was it 8?). After installing the reader you can see the PDF using the browser of adobe air, by navigating to the page with the PDF embedded on it. A very nice example is “Cross-scripting PDF content in an Adobe Air application”

The main issue: you cannot control a PDF file unless it has the javascript code embedded. This was a problem, as there was no way to add javascript in a PDF file in Adobe Air…until now ^^

I added javascript support to AlivePDF Template, so now you can add the required scripts to control the file, as shown in the webpage above.

You can download the source code from the google code webpage of the project.

An example on how to use it is shown below. Enjoy!!!!

	var myPDF : PDFi = new PDFi ( Orientation.PORTRAIT, Unit.MM, Size.LETTER );
	myPDF.setViewerPreferences("true", "true", "true");
	myPDF.javascript = "" +
		"var msgHandlerObject = new Object();\n" +
		"msgHandlerObject.onMessage = myOnMessage;\n" +
		"msgHandlerObject.onError = myOnError;\n" +
		"msgHandlerObject.onDisclose = myOnDisclose;\n" +
		"\n" +
		"function myOnMessage(aMessage)\n" +
		"{\n" +
		"	if (aMessage.length==1) {\n" +
		"		switch(aMessage[0]) \n" +
		"		{\n" +
		"			case 'ZoomIn':  \n" +
		"			    zoom *= 2; \n" +
		"				break;\n" +
		"			case 'ZoomOut': \n" +
		"			    zoom /= 2; \n" +
		"				break;\n" +
		"			case 'PageUp': \n" +
		"			    pageNum--; \n" +
		"				break;\n" +
		"			case 'PageDn': \n" +
		"			    pageNum++; \n" +
		"				break;\n" +
		"			default: \n" +
		"				app.alert('Unknown message: ' + aMessage[0]);\n" +
		"		}\n" +
		"	}\n" +
		"	else\n" +
		"	{\n" +
		"	    app.alert('Message from hostContainer: \\n' + aMessage);\n" +
		"	}\n" +
		"}\n" +
		"\n" +
		"function myOnDisclose(cURL,cDocumentURL)\n" +
		"{\n" +
		"	return true;\n" +
		"}\n" +
		"\n" +
		"function myOnError(error, aMessage)\n" +
		"{\n" +
		"	app.alert(error);\n" +
		"}\n" +
		"\n" +
		"this.hostContainer.messageHandler = msgHandlerObject;\n" +
		"\n";

	var pagecount:Number = myPDF.setSourceFile(File.desktopDirectory.nativePath + File.separator + "PDFControlFlex" + File.separator + "src" + File.separator + "test.pdf" ); //"H:/readings/thesisStatement/p263-jain_challenges_environmental_design_for_pervasive_computing_systems.pdf");
	for(var i:Number = 1; i<=pagecount; i++) {
		var tplidx:Number = myPDF.importPage(i, '/MediaBox');
		myPDF.addPage();
		myPDF.useTemplate(tplidx, 0, 0, Math.ceil(myPDF.getTemplateSize(i).w));
	}

	var f : FileStream = new FileStream();
	var file : File = new File(File.desktopDirectory.nativePath + File.separator + "PDFControlFlex" + File.separator + "src" + File.separator + "MyPDFi.pdf");
	f.open( file, FileMode.WRITE);
	var bytes : ByteArray = myPDF.save(Method.LOCAL);
	f.writeBytes(bytes);
	f.close();

AlivePDF Template now available at Google code

Check it out at:

http://code.google.com/p/alivepdf-template/

A PDF import library for AlivePDF

Sometime ago I decided to create a PDF converter that allowed users to select the sections of PDF to be included in the final PDF. The idea is quite similar to PaperCrop, and actually I modified PaperCrop first to extract text and not only create images (if you want a version of my modified version contact me ^^). Anyway, I felt that PaperCrop was an excellent software (I still does), but it is too difficult to manage C++ code for me, and the lack of versions for Linux and MacOSX, motivated me to create a new software to do that.

Due to my background, my first thought was Java. I am (modestly apart) an expert in Java, and I feel quite comfortable using it. However, the PDF rendering tools available for Java where not good at all. I tried three: Multivalent, SUN’s PDF-Renderer and JPedal. All of them presented some problems at rendering, so I drop them… what to do then, go back to PaperCrop and C++ or try something different? I decided to try something different. I always liked the idea of mixing the desk and the web, so I decided to do it in Adobe AIR. Why AIR and not SilverLight or JavaFX? Well, as I already discussed, Java’s PDF renderers are not good. And I’m not familiar to Silverlight. Actionscript is quite similar to Java in structure, and I already programmed some stuff in Flash long time ago. So there we go, Adobe AIR was selected.

Now, my problem was what to use to develop such software. My first trouble, how to generate PDF files from actionscript. AlivePDF is THE solution for this in Adobe AIR (and Flex). And actually is quite good, and very simple to use. The only problem was that AlivePDF does not accept an existing PDF as input for a new one. The solution: to program a PDF importer ^^

AlivePDF is based on FPDF, a PHP PDF library, which is quite easy to extend. One of the extension, FPDi, allows you to import existing PDF files into a new PDF as a template. I decided to port this extension into AlivePDF, and it took me a couple of days to do so. You can download the AlivePDFTemplate library here:

Please be aware that this is a beta release. I tested with few cases only. It is licensed under the Apache 2.0 license, so you can use it and modify it the way you want.

To use it, you can use the following example as a reference, or check the FPDi website for more examples.

//Must create a new PDFi instance (not PDF)
	var myPDF : PDFi = new PDFi ( Orientation.PORTRAIT, Unit.MM, Size.LETTER );
				
// Import a file!!!! Just set the source file to an existing PDF
	var pagecount:Number = myPDF.setSourceFile(File.desktopDirectory.nativePath + File.separator + "FPDF_TPL-Manual-1.1.pdf" );
// Import a page. The first argument is the page number, the second the way it will be imported
	var tplidx:Number = myPDF.importPage(1, '/MediaBox'); 

//This is important, you MUST add a page first!!!!
	myPDF.addPage();
//Use the template in the current page
	myPDF.useTemplate(tplidx, 10, 10, 90);

// This is not part of the original PDF. Just a test ^^
	myPDF.setFont( FontFamily.ARIAL, Style.BOLD );
	myPDF.setFontSize ( 18 );
	myPDF.setXY( 10, 40 );
	myPDF.addMultiCell ( 300, 1, "This is my PDF Headline" );

//Save the file
	var f : FileStream = new FileStream();
	var file : File = File.desktopDirectory.resolvePath("MyPDFi.pdf");
	f.open( file, FileMode.WRITE);
	var bytes : ByteArray = myPDF.save(Method.LOCAL);
	f.writeBytes(bytes);
	f.close();  

I will upload this as a new project in google code or some other place, to have a better development control. I hope you enjoy it!!!!