Showing posts with label programmation. Show all posts
Showing posts with label programmation. Show all posts

NodeJS edged with C#

NodeJS edged with C#

Hi everyone, it's been a while I didn't post on my blog mainly because I didn't had the time for mainly because I was coding some new stuff and working on a project of mine you'll know about really soon.

But enough of my life, today I wanted to show you some really cool piece of code, called edgejs ! There is some time that I'm seeing Microsoft making real efforts to participate to opensource community projects (some would say for their personal interests but never mind), and I personally think it is great to have major IT company to make that effort. Software development is about sharing knowledge and making great stuff that anybody can have access to.

That's why I've been making some experiments with really interesting projects like typescript, nancyfx or mono. These projects are pushed by opensource community and take advantage of Microsoft solid engineering projects to improve them. It's an interesting step toward open community or full disclosure as called in the IT security world.

Edge.JS


But enough of these thoughts for now, today I want to introduce a really interesting project created by  Tomasz Janczuk and called Edge.js and defined as :
"The Edge.js project allows you to use .NET Framework inside of a Node.js application."
This magical project allows you to call C# methods from NodeJS or NodeJS functions from a C# project. Why the hell would you want to do that you would say ? To find why it is very interesting, you have to go to the definition of both language/framework. NodeJS work in an asynchronous single threaded environment, but CLR allows you to work in a multi threaded environment. You have the best of both worlds ! For web development native asynchronous environment are really useful but for heavy computation you would rather prefer to use all available cores or even GPU capabilities !

Proof of Concept


So how it works ? You should have a look at the documentation explaining it very well and/or Tomasz blog for some extra stuff. In this post I will only explain how to create your mono DLL and call it from your NodeJS router.

First of all we'll create our mono library project to generate the DLL. You can imagine a prime number computation using multi-threaded algorithm but to make it simple we'll only create a function that takes an integer and sum it with himself :

using System;
using System.Threading.Tasks;

namespace PrimeNumber
{
    public class Startup
    {
        public async Task<object> Invoke(object input)
        {
            int v = (int)input;
            return Helper.Add (v);
        }
    }

    static class Helper
    {
        public static int Add (int v)
        {
            return v + v;
        }
    }
}


As you can see we have a Helper::Add method in charge of this. The other method should, by convention, be named Startup::Invoke. We define it as async so the call will be non-blocking in NodeJS side. Actually we also need to use await operator to have a really asynchronous call but because this is an introduction we do not integrate it but you can refer to this post for more details.

We compile our DLL to PrimeNumber.dll and copy it to our NodeJS project in assets directory and see what's next in node side.

On NodeJS side we have a server.js file that looks like this :

var edge = require('edge');

var clrMethod = edge.func('assets/PrimeNumber.dll');

clrMethod(123function(error, result){
  if(error) throw error;
  console.log(result);
});

As you can see it is pretty easy to use. By default the method Startup::Invoke is called in the same namespace as filename PrimeNumber but you can change almost all these options (see edge documentation)

Conclusion


As you can see this is pretty impressive. The project is still in development but open a lot of possibilities for web developers as us. I hope that this quick tour helped you.

See you, Flyers.

Google AppEngine Thoughts

Introduction


For sometimes now i've been working on Google AppEngine platform.

I've made different production back-ends and web services for professional applications. Thus i've been facing lot of problem resolution on AppEngine and after using the Google App Engine i want to share my experience on this particular platform.

First of all, I think Google make really great software and face lot of problem resolution before every one in the world. They've made an awesome map platform, mail platform, mobile platform and office software platform and others.

So it will be obvious that if they made such great applications, we, App Engine developers, would benefit such improvements in our development platform. That's why we oriented ourselves to this host media.

Data Store


Google App Engine offers an API in Java, Python and Go for developing applications. I mostly use the Python version.

The API offers lot of services from email sending to task queuing.

But like all Information System, we need a data store to save all needed data by our application. This is the datastore. Google use a proprietary datastore for storing those informations.

This database system is supposed to be optimized for cluster saving and data accessing who is particularly suited for cloud computing.

It is called Big Tables and is based on NoSQL specifications and so on it is not a relational database. So no many to many relations or on delete cascade.

Thankfully, it is possible to simulate such comportment using ReferenceProperty and/or Parent-child relationship.

Map Reduce algorithm


The BigTable database is based on the Map Reduce algorithm to order its internal data. This is certainly due to the usage of GFS for storing data.

MapReduce algorithm is very useful in distributed environment to speed up filtering and treatment of data. The drawback of this method is that it is really applicable only using background tasking.

Moreover, the MapReduce algorithm prevent performance introduced by common database system features such as B-trees and hash partitioning.

Like in Filesystems, MapReduce have proven his limitation and like it is said in this wired article that Google too has decided to migrate its infrastructures on another filesystem called Colossus.

So we should think that Google is going to apply those changes to the Google App Engine too soon or later. But for the moment, using BigTable lead sometimes to really bad performances for realtime data accessing on some applications.

That's why you should rely on the memcache API when you have such a scenario in some of your project... for the moment.

Alternatives


Other option can be to use another Cloud Computing based hoster. Like Amazon, Yahoo or a more opensource option like OpenShift.

Some of those systems use opensource technology. The one that I like are Apache Hadoop for filesystem or MongoDB for database. It offers good performances and scalability and it offers the necessary flexibility in development that is needed on a lot of projects.

LOTFREE #9

Le zine LOTFREE reprend du service !

Après plus de 5 ans d'attente, voila un nouvel opus du e-zine éponyme LOTFREE.

Le LOTFREE 09 est sorti !!!

J'en parle ici car j'y ai participé puisque j'y ai diffusé un article sur le logiciel que j'ai développé appelé FlyDoor qui permet d'updater automatiquement et de façon transparente vos logiciels/malware.

Bonne Lecture. Flyers.

Asmongueur for asm coders

Voici un site web rassemblant des ressources concernant le développement en assembleur.

Vous pouvez également diffuser vos propres sources sur le site.

Ça se passe par ici : asmongueur.free.fr.

H.264 Decoder in javascript

Une performance impressionnante de la part de Michael Bebenita qui a eu l'idée de convertir le code en C du décodeur vidéo H.264 de Android en Javascript. Bien sûr le script est encore en phase de test mais donne des résultats intéressant. En effet le script tourne aux alentours des 20 FPS sous la nightly build de Firefox. Malheureusement les résultats ne sont vraiment pas les mêmes sur les versions stables de Chrome ou Firefox. Le script s'appel Broadway et il est prévu d'utiliser WebGL pour tirer partie de la puissance du GPU.

Vous pouvez accéder à la démonstration à cette adresse : devongovett.github.com/Broadway.

New CSS 3 in 3D

Bonjour à tous,

Aujourd'hui nous allons nous intéresser à une nouvelle feature intégrée dans CSS 3. Il s'agit des transformations 3D qui ont été intégrées dans le moteur Web WebKit.

Cette nouvelle feature permet de simuler de la 3D ( ce n'est pas de la vrai 3D comme WebGL ) pour des rendus vraiment sympas.

Hakim El Hattab a réalisé une démonstration de cette feature destinée aux appareils mobiles. J'ai modifié cette démonstration pour qu'elle prenne en charge les navigateurs PC basés sur WebKit tels que Safari ou Google Chrome.

Alors comment cela fonctionne-t-il me demanderait vous ? Et bien c'est assez simple, dans un premier temps on réalise un cube à l'aide de la propriété CSS -webkit-transform de cette manière :
#back {
width: 600px;
height: 500px;
background: rgba(0,100,120,1);
text-align: center;
-webkit-transform: translateZ(-49px); // on place le fond à -49
}

#front {
width: 600px;
height: 500px;
background: url('../stripe.png') no-repeat bottom;
-webkit-transform: translateZ(50px); // on place le premier plan à 50
}

#wall-left {
height: 500px;
width: 100px;
left: 0px;

background: #bbb;
// le mur gauche est placé sur l'axe X puis tourné sur l'axe Y de 90 degrés
-webkit-transform: translateX(-50px) rotate3d(0, 50, 0, 90deg);
}

#wall-right {
height: 500px;
width: 100px;
right: 0px;
background: #bbb;
// on fait de même pour le mur droit en inversant l'angle de rotation
-webkit-transform: translateX(50px) rotate3d(0, 50, 0, -90deg);
}

#wall-top {
height: 100px;
width: 600px;
top: 0px;
background: #999;
-webkit-transform: translateY(-50px) rotate3d(50, 0, 0, 90deg);
}

#wall-bottom {
height: 100px;
width: 600px;
bottom: 0px;
background: #999;
-webkit-transform: translateY(50px) rotate3d(50, 0, 0, -90deg);
}


La propriété -webkit-transform permet de spécifier un ensemble de transformations sur les couleurs, la rotation, la taille mais aussi le placement de l'élément. Une fois que l'on a notre belle boîte en CSS 3, il faut faire en sorte que cette boîte se déforme par rapport aux mouvements de la souris.

Pour cela nous utilisons la propriété -webkit-perspective-origin qui nous permet de définir l'origine de l'effet de perspective définit par -webkit-perspective. Cette propriété nous permet de définir la profondeur de champs et le point de vu pour un effet de perspective. Celui-ci est calculé automatiquement par le moteur WebKit pour nous :D.

Nous calculons donc les coordonnées de l'origine du point de vu de la perspective et appliquons les modifications de coordonnées à l'aide d'une boucle de cette façon :
function onMouseMove( event ) {
perspective.tx = Math.round( ( event.clientX / window.innerWidth ) * 100 );
perspective.ty = Math.round( ( event.clientY / window.innerHeight ) * 100 );
};

function update() {
// Interpolate towards the target perspective
perspective.cx += ( perspective.tx - perspective.cx ) * 0.1;
perspective.cy += ( perspective.ty - perspective.cy ) * 0.1;

// Apply the current perspective
world.style.webkitPerspectiveOrigin = perspective.cx + '% ' + perspective.cy + '%';
world.style.perspectiveOrigin = perspective.cx + '% ' + perspective.cy + '%';

// Rinse, repeat
setTimeout( update, 1000 / 30 );
}

Et voilà notre cube 3D qui s'oriente en fonction de la souris fonctionne. Enfin presque, dans certains cas il faut penser à placer les murs au-dessus ou au-dessous des autres éléments à l'aide de la propriété z-index.

Pour les appareils mobiles (iPhone / iPad en l'occurence) la tâche est un peu plus complexe. Nous pouvons accéder au gyroscope  à l'aide de la propriété accelerationIncludingGravity ce qui permet de savoir comment est penché notre appareil. Puis il nous faut détecter l'orientation l'appareil (portrait ou paysage) ce qui se fait par le biais de la propriété window.orientation qui sera égale à 90 ou 0.

A l'aide de ces informations nous pouvons alors placer notre point d'origine d'effet de perspective ainsi :
function onMotionChange( event ) {
if ( orientation ) {
var beta = -event.accelerationIncludingGravity.z;
var gamma = -event.accelerationIncludingGravity.y;
}else {
var beta = -event.accelerationIncludingGravity.z;
var gamma = -event.accelerationIncludingGravity.x;
}

perspective.tx = ( ( gamma / 5 ) + 0.5 ) * 100;
perspective.ty = ( ( beta / 5 ) - 0.5 ) * 100;

event.preventDefault();
}


A noter l'utilisation de la fonction preventDefault() qui permets de surcharger la fonction de base de l'évènement. Ainsi vous pouvez modifier le comportement par default de l'évènement lors de la rotation de l'appareil.

C'est ainsi que se termine cet article sur cette fonctionnalité plutôt intéressante du CSS 3. WebKit a également une page dédiée aux transformations 3D.

Most seen