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.

 
 

Monday 15 April 2013

CultureInfo : le killer de performance ( Franglais )

In this post, je démontre qu'une application peut rapidement perdre en performance, allant jusqu'à 1000% du temps d'execution, par une utilisation abusive du constructeur de la classe CultureInfo.
Study case :

 Just copy the code below in the main method of a console app and then execute it

            DateTime today = DateTime.Now;
            //Feed the list by dummy data
            List<DateTime> tenDaysAgo = new List<DateTime>();
            for (int i = 0; i < 10000; i++)
            {
                tenDaysAgo.Add(today.AddDays(-i));
            }
           
            //Start the stopwatch
            Stopwatch sw = new Stopwatch();
            sw.Start();
            foreach (var item in tenDaysAgo)
            {
                //Define the currentCulture
                IFormatProvider currentCulture = new CultureInfo("FR");
                //Try to parse with the currentCulture
                DateTime.TryParse(item.ToString(), currentCulture, DateTimeStyles.None, out dateOut);          
            }
            sw.Stop();
            Console.WriteLine("Ellapsed time = " + sw.ElapsedMilliseconds + " ms");
            Console.ReadLine();



 It took about 20000 ms to execute on my laptop ( Dell core i7 Q, 16Go RAM ).

 As you've seen the program performs very poorly
The issue comes from this instruction :
          IFormatProvider currentCulture = new CultureInfo("FR");
 inside the foreach loop. It takes about 3ms second to create an instance of CultureInfo.

Solution :

DateTime today = DateTime.Now;
            //Feed the list by dummy data
            List<DateTime> tenDaysAgo = new List<DateTime>();
            for (int i = 0; i < 10000; i++)
            {
                tenDaysAgo.Add(today.AddDays(-i));
            }
           
            //Start the stopwatch
            IFormatProvider currentCulture = new CultureInfo("FR");
            Stopwatch sw = new Stopwatch();
            sw.Start();
            foreach (var item in tenDaysAgo)
            {
                //Define the currentCulture
               
                //Try to parse with the currentCulture
                DateTime.TryParse(item.ToString(), currentCulture, DateTimeStyles.None, out dateOut);          
            }
            sw.Stop();
            Console.WriteLine("Ellapsed time = " + sw.ElapsedMilliseconds + " ms");
            Console.ReadLine(); 
 


 The above code does the same thing but takes just 77 ms to execute. 

Conclusion
 En général, toujours éviter de faire des constructions d'objets à l'intérieur d'une boucle. Cela peut engendrer une perte de performance énorme à partir d'un certain volume de données.

 
  

Friday 12 April 2013

Planificateur de taches en .NET

Planifier un "background task" est une opération fréquente dans la gestion de notre système d'informations.
Ex : 
- exécuter une action chaque jour à minuit pour une application on-premise
- faire un état statistique à 2:00 am pour une application hebergée dans le cloud Windows azure.

Plusieurs solution sont à notre disposition , entre autre :
- le Windows Task Scheduler  à l'intérieur d'un worker role
- l'utilisation de bibliothèque spécialisée comme Quartz.net

Vous pouvez voir Quartz.net ici
https://github.com/quartznet/
http://quartznet.sourceforge.net/