Saturday, 9 August 2014

Json.NET vs JavascriptSerializer performance comparison

In this post, I will talk about Json.NET and the native JavascriptSerializer libraries.
Json.NET, mostly known under NewtonSoft.Json is a library specialized into de/serialization to json format. The library becomes a standard as from VS 2012 as jquery was as from VS 2010.It is available here.
JavascrtipSerializer is a .NET native object  doing the same stuff as Json.NET, this class belongs to the  System.Web.Script.Serialization namespace.

As seen in the home page of Json.NET, it seems to be 250% faster than the javascriptSerializer. In this post, I will try to build a litte enterprise level scenario to see what really happens in background.

Version used :
- Json.NET 6.0.0.0, the latest release at writing
- .NET Framework 4.0

In this labs, I will use two simples objects named SuperObject and ObjectChild

SuperObject has :
- 20 string properties 
-  20 double properties
- 20 datetime? properties
- 20 List<ObjectChild> properties

ObjectChild has :
- 20 string properties 
- 20 double properties
- 20 datetime? properties

Its simulates a massive structure and hierachy that is close to industrial scenario : object are fetched from the database, all of its properties are set, all dependencies are loaded and the final object is serialized ( JsonResult, WEB.API ) into Json then send to the client (view).

I have filled all those properties automatically by using some reflexion trick.
- Guid string was injected to all string type
- DateTime.Now for all DateTime? type
- A large number for the double type

All tests are done on a DELL quad core i7 720qm laptop which allow me to use multithreading on the test program. The full source code is at the end of this post.


Results :
 

 For a small object size ( 1 to 10 nested object ), JavascriptSerializer is bit faster than the Json.NET. The difference is around 2/3, so I have to consider that for a simple structure with a small data, JavascriptSerializer is more effficient  and more lightweight ( see diagram below).
When the data increase, my choice goes on Json.NET serializer. It becomes very efficient tool if we want to get data faster. For 1000 nested object number, Json.NET takes "only" 7500 ms to execute, JavascriptSerializer 23seconds.


The both tools serialize object to json format. The json string length is different. JavascriptSerializer wins every time on this metric. If you need to return a lightweight data, use JavascriptSerializer. It is usefull if the client is on a low-bandwidth location.
As example for 1000 nested object number, Json.NET produces 65464018 chars and 61503685 for JSerializer, a difference of 33960333 chars !

 For the same object serialized earlier, the deserialization result is unexpected. In all of my study case, the JavascriptSerializer performs very quickly. So in all deserialization , I will use JavascriptSerializer.Deserialize method.



What happens if I use Json.NET for serialization and JavascriptSerializer for deserialization ?
No issue. Even if the produced json string  is not the same, each of these tools can independently deserialize the string to the right object without data loose.

Conclusion:
- When deserializing, use JavascriptSerializer.Deserialize
- If reducing the amount of data is a must, using JavascriptSerializer may do the job
- For small data, it's up to you.
- For complex and heavy structure of data, use Json.NET to serialize.
- For optimization, think to serialize with Json.NET and deserialize with JavascriptSerializer.


Monday, 5 May 2014

Comprendre le chargement dynamique de modules sous ASP.NET 4.5 en 5 minutes [HttpApplication.RegisterModule, PreApplicationStartMethod] - Dynamically load modules in ASP.NET 4.5

Les mots clés de ce post sont :
- HttpApplication :
- HttpModule : toute classe qui implémente l'interface IHttpModule. Un module est un programme qui s'execute durant le traitement d'une requête par IIS.
- HttpApplication.RegisterModule : méthode disponible sur .NET 4.5, permettant de charger un module.
- PreApplicationStartMethod
1- Commencez par créer un projet web (Webform ou MVC) sous le framework 4.5.
 Ci-dessous mon projet, encadrés en bleu les fichiers que je vais modifier.
2- Le fichier DevenvaModule.cs est mon module personnalisé. Il va ajouter une entête particulière à toutes les réponses aux requêtes http.
Ci-dessous le code complet


3- La classe ModulesLoader est la classe qui va s'occuper de l'enregistrement des modules via la méthode statique HttpApplication.RegisterModule


4- La dernière étape consiste à utiliser l'attribut PreApplicationStartMethod, cet attribut s'applique à un assembly et permet l'enregistrement du module en toute transparence.
Dans le fichier AssemblyInfo.cs, ajouter en dernière ligne :



Cette déclaration permettra de connaitre le type et le nom de la méthode de la classe cible qui va permettre le chargement dynamique du module.

Après ces modifications, testez une page de l'application. Le module est bien entré dans le traitement de la requête :




Conclusion :
Nous avons vu dans ce post une technique :
 - souple : nous pouvons choisir dynamiquement les modules à charger (cf. méthode LoadModules)
 - transparente : l'enregistrement du module ne nécessite pas de toucher ni au global.asax, ni au web.config du site , ni au fichier de configuration du serveur.

Domaine d'application :
module sur une solution multi-tenant.

Friday, 31 May 2013

TF400533: In order for this wizard to upgrade to the latest version of SQL Server Express, you will first need to install Service Pack 2 or newer, and then re-run this wizard. It is recommended that you run Microsoft Updates which will install the current service pack automatically (You may need to enable Microsoft Updates from the Windows control panel).

This error may occur when trying to install Visual Studio TFS 2012 RC2 on a windows server station that has already a SQL server installed.
One solution is to updrage the windows version.
The solution that I've choosed is to remove all SQL server instances on my server ( I work on a dev machine so uninstalling is not really a matter ).
The TFS installer will reinstall a fresh sql server.

Saturday, 11 May 2013

Data-Driven Test with visual studio 2012 - how to feed test method with sql server datas.

Data-driven test is one way to test our system with predefined values. 

In this post, i will test a method named "Divide" and feed it with values defined in a SQL server database table. The test engine will loop as many as row exist in this table. 

The method "Divide" looks like 

public class Helper
{
        public int Divide(int a, int b)
        {
            return a / b;
        }

} 

After creating a Unit test projet in visual studio 2012, add a dll referencing the class to be tested.
By default, a class "UnitTest1" has been created and contains a test method TestMethod1.

 [TestClass]
public class UnitTest1
{
        [TestMethod]
        public void TestMethod1()
        {

        }
} 

1- The first step to do is to add a TestContext property in this class. TestContext is an object in which general/global properties are accessible and available for the current run.
Our class becomes :

 [TestClass]
public class UnitTest1
{
         private TestContext _testContext;
        /// <summary>
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///</summary>
        public TestContext TestContext
        {
            get
            {
                return _testContext;
            }
            set
            {
                _testContext = value;
            }
        }

        [TestMethod]
        public void TestMethod1()
        {

        }
} 

Sql script used in this example :
create table DivideBoundaryValues(num int,den int)
insert into DivideBoundaryValues values(0,1),(1,2),(4,2)


Then decorate the TestMethod1 with DataSource Attribute

  [DataSource("System.Data.SqlClient", "server=WIN-0LQSDB1L1T3\\SQL2008D;Database=DataDrivenStore;User Id=SSS;Password=SSS", "DivideBoundaryValues", DataAccessMethod.Sequential)]
     
        [TestMethod]
        public void TestMethod1()
        {

         }

The first parameter in the constructor is the provider. System.Data.SqlClient is a good candidate in our case.
The second parameter is a standard connection string like the one in the app.config or web.config.
The third one is the name of the table in which values will be retrieved.
The last one tell that data order will be used  as they are ordered in the table.

Add the System.Data dll in the UnitTest1 project. It will be usefull in the next step ( when using DataRow).

Finally , the TestMethod1() looks like :
  [DataSource("System.Data.SqlClient", "server=WIN-0LQSDB1L1T3\\SQL2008D;Database=DataDrivenStore;User Id=Administrator;Password=jY4i42u123456;integrated security=true", "DivideBoundaryValues", DataAccessMethod.Sequential)]
     
        [TestMethod]
        public void TestMethod1()
        {
            Helper helper = new Helper();
            var a = (int)TestContext.DataRow[0];
            var b = (int)TestContext.DataRow[1];
            Assert.AreEqual(2, helper.Divide(a,b));
        } 


where DataRow[0] is the first col in the table, DataRow[1] the second, and so on...

As we can see in this figure, VS executes 3 times the TestMethod1, one row one call.

Data Source can be also retrieved from CSV, XML File or a custom provider .

For the CSV case , just change the datasource attribute to :
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV","|DataDirectory|\\data.csv","data.csv",DataAccessMethod.Sequential), DeploymentItem("C:\\Sources\\data.csv")] 
In this example : datas are stored in a file named  data.csv
The only constraint when using CSV is that lines must be comma-separated.

Saturday, 4 May 2013

Génération de données de test pour un "coverage testing" avec Pex - French version

Un test de couverture nécessite le parcours des différentes arbres de conditions dans la méthode à tester.
Considérons la méthode suivante :

        public void ComplexTask(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                throw new ArgumentNullException();
            }
            else
            {
                if (input.Contains("ERROR"))
                {
                }
                else if (input.Contains("SUCCESS"))
                {

                }
                else if (input.StartsWith("_"))
                {

                }
                else
                {

                }
            }
        }

Pour assurer le parcours intégral de l'exécution, il faut au moins avoir des valeurs correspondants à chaque condition.
Pex est un outil permettant de générer automatiquement ces tables de valeurs, cet outil est disponible ici 
Il suffit juste de copier la méthode dans l'éditeur de Pex puis la renommer par Puzzle et enfin l'executer. A la fin du traitement, l'outil affiche les valeurs intéressantes ( "boundary values" )

  

Installation d'un Tuner TV sur Windows Server 2008 R2 - French Version




Ce post fournit une solution sur la problématique d'installation d'un Tuner TV sur un poste Windows Server 2008 R2 64 bits. 
Par défaut, une station Windows server 2008 R2 n'embarque pas le BDA ( cf ci-dessous). Ce composant permet l'interfacage avec des appareils de capture comme les Tuners. La BDA existe par contre sur Windows 7 / Vista.   
Le Tuner marche bien sur une autre machine tournant sur Windows 7 x64 , langue en-US.

Pour de plus amples informations, veuillez se reporter à :

- Broadcast Driver Architecture : http://en.wikipedia.org/wiki/Broadcast_Driver_Architecture
- Le feature "Desktop Experience" sur Windows Server 2008 R2

Les appareils utilisés dans ce post sont :

- PC DELL Inspirion core 17 , Windows Server 2008 R2 x64 Trial
- un tuner Tv Tuner USB AverMedia ( occasion achetée à 5 euros)

Après avoir installé l'appareil, windows ne reconnait pas le périphérique. L'application du tuner se lance mais le système affiche : "not connected device"

En faisant des recherches sur MSDN ( la version pro ) , il s'avère que le problème est lié au BDA ainsi qu'au "Desktop experience"

1- Installer le feature "Desktop experience"

Start >  Administrative tools > Server Manager > Features > Add features > "desktop experience"



2- Installation du BDA

Dans cette partie, il faut prendre les fichiers suivants depuis une machine Windows 7 x64

Dans C:\Windows\SysWOW64 
(*) => C:\Windows\SysWOW64\en-US ( dépendant de la langue de la machine)

 et les copier dans le même repertoire que la machine Windows server 2008 R2

bda.inf
bdaplgin.ax
BdaSup.sys
ccdecode.inf
ccdecode.sys
dx9bdaxp.cat
dxbda.inf
ipsink.ax
kstvtune.ax.mui *
kswdmcap.ax.mui *
ksxbar.ax.mui *
mpe.inf
mpe.sys
Mpeg2Data.ax
msdv.sys
MSDvbNP.ax
MSVidCtl.dll.mui * 
msyuv.dll
nabtsfec.inf
nabtsfec.sys
ndisip.inf
ndisip.sys
psisdecd.dll
psisrndr.ax
slip.inf
slip.sys
streamip.inf
streamip.sys
vbisurf.ax
wstcodec.inf
wstcodec.sys
wstdecod.dll


3- Une fois les 32 fichiers copiés, il faut enregistrer les fichiers *.DLL et *.ax un par un par la commande :

%systemroot%\SysWOW64\regsvr32 /s %systemroot%\SysWOW64\NOM_DU_FICHIER

Cette opération doit être faite sur une commande DOS et en tant qu'administrateur

4- Redémarrer la machine après la manip

5- Lancer le Tuner et zapper 



    

Sunday, 21 April 2013

Installation de windows 7 sur un HP Pavilion Dv7/Core 7/16Go RAM quand on n'a pas les DVD de restauration ( french version)

La semaine dernière, j'ai fait l'acquisition d'un Laptop HP Pavilion dv7. 


Cet appareil convient à mes besoins pour ces raisons :
- puissance : core i7 - 4 coeurs et 8 coeurs logiques
- taille de RAM maxi : 16Go, me convient bien car j'envisage d'y installer un hyperviseur ( hyper-V ou un simple VMWare esxi)
- l'appareil possède aussi 2 slots pour accueillir 2 disques durs (possibilité d'un SSD) et facilement accessible en comparaison avec un Dell inspirion 


La photo ci-dessous montre comment il est compliqué d'accèder physiquement au DD d'un Dell : il faut enlever le lecteur DVD, puis le clavier, puis la plaque en alu en dessous du clavier ( en faisant attention aux 3 connecteurs qui sont reliés a la CM...)

  
Pour ces raisons, j'ai fait le choix de m'en procurer un. L'appareil coute 1300euros.

Etant donné que c'est la première fois que j'utilise un HP, j'ignorais complètement la nécessité de créer des DVD de restaurations afin qu'on puisse plus tard réinstaller/revenir à la configuration en sortie d'usine.
 Sans ces DVD, il n'est pas possible de faire une réinstallation de manière classique : même si on a un DVD d'install de Windows Seven, cela ne passera pas car HP a pris des mesures de protection de ses appareils . Le problème est fréquent par exemple :
http://h30434.www3.hp.com/t5/Notebook-Operating-Systems-e-g-Windows-8-and-Software/Windows-7-clean-install-VM-on-Pavilion-dv7-notebook/td-p/209563

Les comportements suivants sont rencontrés lors de l'installation si on n'a pas les originaux des DVD de restauration :
- reboot de la machine très souvent
- 3 fois sur 5, la machine ne reconnait pas les disques durs
- la machine ne detecte pas non plus la souris   
- au max, on n'arrive meme pas ici :
La solution officielle est d'aller chez HP afin qu'il en fournisse les jeux de DVD. Il faut venir avec la machine et en 48 heures minimum les DVD sont disponibles . C'est payant.

Après avoir tenté presque toutes les astuces sur les forums, je n'arrivais pas a installer le windows 7 , pour info, la version que je suis entrain d'installer a ete telechargé sur le site de microsoft, un ISO que j'ai mis ensuite sur un DVD ( gravure en 2x).

Finalement j'ai tenté de faire l'install sur mon DELL et après remettre le disque fraichement installé sur le HP.
0 - Commencer d'abord a récupérer les pilotes du HP sur internet, on y trouve facilement un package pret a etre installe.
1- Démontage du DELL 
  


2- Demontage du HP pour pouvoir y extraire les DD.

3-  On branche le DD HP sur le Dell
4- On installe de manière classique

  
5- A la fin d'installation, installer le package de pilote meme si cela ne convient pas l'architecture d'un DELL.

6- Remettre le DD sur le HP
7- J'ai rencontré un pbm d'écran bleu windows lors du 1er demarrage
8- Réinstaller une deuxieme fois les jeux de pilotes , maintenant sur le HP
9- Fin.

Maintenant le HP est restauré et le windows 7 marche bien. Après cette expérience, je n'ai plus de crainte a faire des manipulations xtrem sur les HP.