Saturday, 9 August 2014

Create generic type object by using Activator class

This post aims to show how to create an object from a generic class using the activator class.
Given the class :
public class MyObject
{
        public string Name { get; set; }

}
We can instantiate a new MyObject object by :
var newObject =   (MyObject)Activator.CreateInstance(typeof(MyObject));

What happens if the class looks like :

  public class DataObject<T>
    {
        public DataObject(string name)
        {
            Name = name;
        }
        public string Name { get; set; }
        public List<T> ContenList { get; set; }
    } 
 We can achieve this goal with :

 var dataObjectBody = (DataObject<string>)Activator.CreateInstance(typeof(DataObject<>).MakeGenericType(typeof(string)),"Foody");
 The MakeGenericType tells that we want to use the generic T as a string type.
The "Foody" value is used for the constructor name parameter when the Activator.CreateInstance creates the object at runtime.

In the case where the class uses a multi generic type like:
 public class DataObject1<T,TU>
    {
        public DataObject1(string name)
        {
            Name = name;
        }
        public string Name { get; set; }
        public List<T> ContenListT { get; set; }
        public List<TU> ContenListU { get; set; }
    } 
The same method is being used, we need to do small changes on the arguments

 var obj1 =
                (DataObject1<string, string>)
                    Activator.CreateInstance(typeof (DataObject1<,>).MakeGenericType(typeof (string), typeof (string)),
                        "Foody");


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