Un peu de mon expérience dans le monde .NET
# Thursday, October 04, 2007
Le code source de l’implémentation de Framework .NET 3.5 sera disponible

Scott Guthrie, General Manager de la division Developer chez Microsoft, vient de larguer une petite bombe sur son blog …

 

Le code source de l’implémentation de Framework .NET 3.5 sera disponible en lecture (pas de modification).  De plus, ces sources seront intégrées directement dans Visual Studio 2008. Cela veux dire qu’en mode debug, il sera possible de faire du pas à pas dans son propre code. Si la méthode appelée est une méthode du Framework, VS fera alors du pas à pas dans le code du Framework …

 

La seule initiative de ce type que je connaisse chez MS était le projet Rotor, qui proposait en 2002 de partager une partie des sources code utilisées pour la CLR. C’était les prémices du Framework .NET et permettait de comprendre en partie la plomberie interne de la CLR.

 

Le post de Scott Guthrie (avec quelques copies d’écans).

Le post sur le même sujet de Shawn Burke, chef de ce projet chez MS.


Thursday, October 04, 2007 8:28:09 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0]  VS2008 | Rotor | shared-source

# Monday, October 01, 2007
Récupérer le nom de la méthode en cours d’exécution

On a toujours voulu récupérer le nom de la méthode en cours d’exécution, quelque soit le langage, afin de tracer les erreurs d’exécution. En VB4,5 et 6, chacun a développer sa propre technique car rien de bien sérieux n’existait.

 

En .NET, nous avons les NameSpace System.Diagnostics & System.Reflection pour résoudre ce problème :

 

StackFrame stackFrame1 = new StackFrame();

MethodBase methodBase1 = stackFrame1.GetMethod();

Permet de récupérer le nom de la méthode en cours d’exécution.

 

StackTrace stackTrace = new StackTrace();

StackFrame stackFrame = stackTrace.GetFrame(1);

MethodBase methodBase = stackFrame.GetMethod();

Permet de récupérer le nom de la méthode qui a appelé la méthode en cours d’exécution.

 

Très utile afin de tracer les exceptions…


Monday, October 01, 2007 11:28:56 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0]  C# | Log

# Thursday, September 27, 2007
Multi-écran

Je travail en mode dual monitor et j'aime ça ;)

Par défaut, Windows manage assez bien cette configuration. J'utilise néanmoins deux applications (gratuites) pour améliorer "l'expérience utilisateur" : 

Enjoy.

 


Thursday, September 27, 2007 8:16:52 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0]  Utilitaires | Windows | monitor

# Friday, September 14, 2007
Couleur

Je ne pensais pas qu'un site ne parlant que des couleurs allait autant me passionner. Je vous invite a vous rendre sous http://www.colourlovers.com/ pour vous faire une idée !

 


Friday, September 14, 2007 12:45:30 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0]  Color

Outils de Refactoring gratuit pour VS

J'utilise personellement Resharper et en suis très content.

J'ai néanmoins découvert un autre produit gratuit (pour ASP.NET) et me suis penché sur les différentes offres. Et il n'y a pas grand chose ...

Avec VS2008, de nouvelles options de Refactroing font leurs appartition, mais uniquement pour C#.

Devexpress offre son produit Refactor! Il se décompose en plusieurs versions:

Resource Refactoring Tool from CodePlex
Permet facillement d'extraire un ressource Hard codé et de la placer dans un fichier ressource. http://www.codeplex.com/ResourceRefactoring

Une ressource incontournable concernant le refactoring est le site de Martin Fowler : http://www.refactoring.com/

 


Friday, September 14, 2007 9:09:45 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0]  Refactoring

iPhone : Facture salée, même sans conversations ...

 Pour un entrepreneur Américain partis en croisiére avec sa famille en Europe.

En effet, L'iPhone met les emails à jour même si l'appareil est éteint, afin que vous puissiez les lire dès que vous l'allumez. Si ce service n'est pas payant aux États-Unis, il peut s'avérer très cher lorsqu'on voyage à l'étranger (24,99 dollars les 20 Mégaoctets).

Apple, précise toutefois qu'il est écrit dans les "termes et conditions" que le prix du trafic de données est payant en dehors des États-Unis.

L'histoire complète ici.


Friday, September 14, 2007 8:49:25 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0]  Main

# Friday, August 31, 2007
Vaut son pesant de cacahouètes …

 Dans une ListView, on ajoute les colonnes en ajoutant des ColumnHeader. Cette objet à une propriété Width, qui permet de définir la largeur de la colonne en pixels.

 

C’est maintenant que cela devient rigolo ! Il est possible (et c’est même documenté ici) d’assigner une valeur négative (-1 ou –2) … -1 ajustera la largeur de la colonne à la largeur maximum des éléments affichés dans celle-ci. –2 ajustera la largeur de la colonne à la largeur du texte du header …

 

Il aura fallu combien d’ingénieurs pour arriver à cette solution ?


Friday, August 31, 2007 8:10:46 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0]  Tips | WinForms

# Monday, August 27, 2007
Changer le WindowsIdentity en cours d’exécution (impersonalisation)…

 Par défaut, le WindowsIdentity (system.security.principal) est celui de l’utilisateur logué, et est récupérable en utilisant l’instruction suivante :

WindowsIdentity.GetCurrent()

 

Dans le cadre d’un projet, j’avais besoin que mon code s’execute temporairement sous une autre identité que celle de l’utilisateur executant l’application. Après quelques recherche, voici les trois étapes a effectuer :

 

1 - Se loguer avec le nouveau compte

 

Pour se faire, on va utiliser l’API advapi32, dont voici la signature :

[DllImport("advapi32.dll", SetLastError=true)]
public static extern bool LogonUser(
    string lpszUsername,
    string lpszDomain,
    string lpszPassword,
    int dwLogonType,
    int dwLogonProvider,
    out IntPtr phToken
    );

 

Le code suivant retourne vrai si le login à réussi. Il retourne surtout le handler du token lié à ce login, que nous utiliserons plus tard.

LogonUser(

« nom d’utilisateur »,

« domaine »,

« mot de passe »,

2,

0,

ref TokenHandler)

 

2 – Dupliquer le token

 

A nouveau, il faut utiliser l’API advapi32 :

[DllImport("advapi32.dll", SetLastError=true)]
public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int
   SECURITY_IMPERSONATION_LEVEL, out IntPtr DuplicateTokenHandle);

 

Le code suivant retourne vrai si la duplication à réussie. Il retourne aussi le token utiliser plus tard afin de créer un nouveau WindowsIdentity.

DuplicateToken(

TokenHandler,

2,

ref pDuplicateTokenHandle);

 

 

3 – Créer un nouveau WindowsIdentity

 

Opération qui est un jeu d’enfant, via le code suitant :

 

WindowsIdentity newId = new WindowsIdentity(pDuplicateTokenHandle);

WindowsImpersonationContext impersonatedUser = newId.Impersonate();

 

 

Dorénavant, WindowsIdentity.GetCurrent() retoune le nouveau WindowsIdentity et le code s’execute avec les droits de celui-ci. Pour revenir à l’état avant impersonalisation, il suffit d’utiliser la méthode Undo de WindowsImpersonationContext


Monday, August 27, 2007 3:09:47 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0]  Securité

# Wednesday, August 15, 2007
SQL Tips

Comment reconstruire tous les indexes d'une base de données :
EXEC sp_MSforeachtable @command1="print '?' DBCC DBREINDEX ('?', ' ', 80)"


Wednesday, August 15, 2007 7:25:39 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0]  Main

# Friday, August 10, 2007
Windows Mobile en mode Kiosk

Voici l'article que j'ai publié sous www.codeproject.com, résultat de mon expérience suite au développement d'un POC ...

Introduction

Windows Mobile is a great production device. But by default, the device give access to all functionalities (e-mail, contacts ...) and in particular context, you will probably be interested to restrict end-user access to some of these functionalities.

You'll have two options:

  • Integrate in the standard Sheel
  • Customize the system in kiosk mode

    I'll focus on the second option. In order to set the system in kiosk mode, we'll have to:

  • Write an application with a screen which will work like the 'Today' screen
  • Control the hardware button to restrict access to Windows Mobile functionalities
  • Of course, have the application launch at startup
  • This is a non exhaustive list...

    Background

    I will not focus on Compact Framework development and OS low level library interaction. But keep in mind the .Net Compact Framework Artchitecture:

  • Framework
  • Common Language Runtime
  • Windows CE

    You will then understand why we reference microsoft.windowsce.forms for low level functionality

    I also use OpenNETCF www.openNETCF.com for reading/writing registry. Library is fully explained on their web-site.

    Using the code

    Our first task is to create a new Smart Device project from Visual Studio. As mentioned in the introduction, we'll set properties of the default Form Form1.cs in order to create a 'Today' like screen. You can do it using the properties windows or by code :

    public frmKiosk()
    {
        InitializeComponent();
    
        ControlBox = false;
        FormBorderStyle = FormBorderStyle.None;
        MaximizeBox = false;
        MinimizeBox = false;
        WindowState = FormWindowState.Maximized;
    }
    

    Now, we'll have to control hardware button. This is done using the Microsoft.WindowsCE.Form.MessageWindows. This class will allow us to intercept Windows Messages and decide how to handle them (internal routine, raising events to be handled by other class, or ... do nothing). This will allow us to intercept messages send by hardware button and simply decide to not react to them!

    The logic is quite simple:

  • Create a class which will inherit from MessageWindows. Override the WndProc method to catch windows message and implement our own business logic. We will intercept only HOTKEY message, but the same code could be use to handle all windows message type (full list here: http:\\www.pinvoke.net)
  • Unregister the hardware button : by default, message raised by hardware button are handled by the default process
  • Register the hardware button : message raised by hardware button will be handled by our custom MessageWindows

    The code of our custom MessageWindows will be like this:

    public class internalMessageWindow : MessageWindow
    {
            // Which message type ?
            public const int WM_HOTKEY = 0x0312;
    
            Form referedForm;
    
            public internalMessageWindow(Form referedForm)
            {
                this.referedForm = referedForm;
            }
    
            protected override void WndProc(ref Message msg)
            {
                switch (msg.Msg)
                {
                    case WM_HOTKEY:
                        // Do no reply to this key ...
                        return;
                }
                base.WndProc(ref msg);
            }
    }
    

    We have now to link our form with our custom WindowsMessage

    FormCode
    {    
        internalMessageWindow messageWindow;
        public Form Constructor()
        {
            this.messageWindow = new internalMessageWindow(this); 
        }        
    }
    

    And unregister/register hardware buttons using UnregisterFunc1 and RegisterRecordKey from coredll.dll (see http:\\www.pinvoke.net for signature detail

    FormCode
    {    
        public Form Constructor()
        {
            ...
            RegisterHKeys.RegisterRecordKey(this.messageWindow.Hwnd);
        }        
    }
    public class RegisterHKeys
        {
            [DllImport("coredll.dll", SetLastError = true)]
            public static extern bool RegisterHotKey
            ...
            and
            private static extern bool UnregisterFunc1
            ...
            
            public static void RegisterRecordKey(IntPtr hWnd)
            {
                UnregisterFunc1(KeyModifiers.Windows, (int)KeysHardware.Hardware1);
                RegisterHotKey(hWnd, (int)KeysHardware.Hardware1, KeyModifiers.Windows, (int)KeysHardware.Hardware1);
                
                // Repeat for every single hardware button you wan to handle
            }
        }
    

    Now, we need to force our application to start avery time the Windows Mobile is started. This could be done using the CeRunAppAtEvent function of the coredll.dll library. This function allows linking an application to a specific event of the device. In our context, we'll link our application to the Wakeup event. This mean that every time the device is started, the Wakeup event will be raised, an as we will like our application with this event, our application will be started.

    To link application to event, we'll use this code:

    Win32.CeRunAppAtEvent(_kioskName, NotificationEvent.Wakeup);
    

    And we'll use this code to 'unlink' application / event:

    Win32.CeRunAppAtEvent(_kioskName, NotificationEvent.Wakeup);
    

    So now, we have a start page, which appears every time the device is started. And we have also caught button events to disable hardware interaction. Final step is to allow end-user to launch specific application and wait that this application to be closed to return to our start page.

    This is a quite easy step, using ProcessStartInfo class. This will allows us to start an application in a new process and put our current application in a waiting state, waiting that a specific process exit.

    To start a new process, we'll use this code, which will return the process handler:

    private static Process LaunchApp(string filename)
    {
        ProcessStartInfo s = new ProcessStartInfo();
        s.FileName = filename;
        s.UseShellExecute = true;
        return Process.Start(s);
    }
    

    And we have just to add routine to start an application, waiting the process to exit, with this code:

    private void but_Click(object sender, EventArgs e)
    {
        this.Hide();
        Process ela = LaunchApp(application2);
        ela.WaitForExit();
        this.Show();
    }
    

    Things to be aware

  • Hard reset of the device is not handled. Doing an hard reset will unsubscribe the application from the Wakeup event.
  • This solution is not portable ! Form is designed for a specific resolution (240x320 in this sample) and device with the default four hardware buttons. Installing it a device with other specification will fail.

    How to

    Handling non standard hardware button
    The sample is based on default device, with four buttons. If your target device has more buttons, or that MessageWindow didn't catch button interaction, you'll have to validate your button code. Use Registry Editor (Remote Registry Editor) and go in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shell\Keys\. You will see multiple "Folders", corresponding to your hardware keys, like 40C1, 40C2, ... Convert the last two letters to Decimal and you will get your button key (C1=193,C2=194,...)

    Conclusion

    This sample is far from a production product, but show that handling specific device like PocketPC is quite easy. Interacting with such hardware need a little bit of pinvoke, as compact framework encapsulates some but not all functionalities. Any comments/proposition are welcomes

    Reference

  • MSDN : Get an Application to Automatically Start When a mobile Device Wakes Up?

    History

  • 08/10/2007: Posted to CodeProject

  • Friday, August 10, 2007 12:43:10 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0]  Windows Mobile