Some interesting Spec Explorer videos from Channel9. It is all you need to get started with Model Based Testing.
The idea behind spec explorer is to make a model of the requirements of your products and let Spec Explorer generate millions of interesting test cases. You just need to find enough CPU power to run all the generated test cases :-)!

Continue reading »

 

.Net offers multiple ways to manage impersonation and its level. The important point to understand is what is being impersonated: the thread or the process also is the impersonation happening on the process or is it happening only on the network. Below classes will show you how to impersonate in all this cases.

First class: ImpersonateManager – allows starting impersonation and will apply to the thread scope. You will need to allow unsafe code in your project build properties.  Below program is an example of using the ImpersonateManager.

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Before impersonation: " + WindowsIdentity.GetCurrent().Name);

            try
            {
                ImpersonateManager.ImpersonateUser("domainName", "userName", "password");
                Console.WriteLine("Impersonated User: " + WindowsIdentity.GetCurrent().Name);
            }
            catch (System.ComponentModel.Win32Exception e)
            {
                Console.WriteLine("Exception while trying to impersonate: " + e);
            }

            ImpersonateManager.StopImpersonation();
            Console.WriteLine("After impersonation: " + WindowsIdentity.GetCurrent().Name);

            Console.ReadKey();
        }
    }

The ImpersonateManager.cs is like this:

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;

[assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode = true)]
[assembly: PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")]
namespace ImpersonateThread
{
    public class ImpersonateManager
    {
        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
            int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

        [DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
        private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr lpSource,
            int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr* Arguments);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public extern static bool CloseHandle(IntPtr handle);

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

        // OurIdentity
        private static WindowsImpersonationContext _impersonatedUser;

        // Tokens
        private static IntPtr tokenHandle = new IntPtr(0);
        private static IntPtr dupeTokenHandle = new IntPtr(0);

        // If you incorporate this code into a DLL, be sure to demand FullTrust.
        [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
        public static void ImpersonateUser(string domainName, string userName, string password)
        {
            const int LOGON32_PROVIDER_DEFAULT = 0;
            const int LOGON32_LOGON_INTERACTIVE = 2;

            tokenHandle = IntPtr.Zero;

            // Call LogonUser to obtain a handle to an access token.
            bool returnValue = LogonUser(userName, domainName, password,
                LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                ref tokenHandle);

            if (false == returnValue)
            {
                // Logon failure
                int ret = Marshal.GetLastWin32Error();
                throw new System.ComponentModel.Win32Exception(ret);
            }

            // Use the token handle returned by LogonUser.
            WindowsIdentity newId = new WindowsIdentity(tokenHandle);

            // Now the thread is impersonated.
            _impersonatedUser = newId.Impersonate();
        }

        public static void StopImpersonation()
        {
            // Stop impersonating the thread.
            _impersonatedUser.Undo();

            // Free the tokens.
            if (tokenHandle != IntPtr.Zero)
            {
                CloseHandle(tokenHandle);
            }
        }
    }
}



Now this might not be enough for your need, you might need more than thread impersonation.

There are basically two main logon scenarios in this case:

1)      The user you want to impersonate is on the same domain as the current process

  • Load the profile in the registry (like runas /profile)
  • Sample with: ProcessImpersonator.ImpersonateProcess_WithProfile()

2)      The user you want to impersonate is on a domain without trust relationship

  • Use the specified credentials on the network only (like runas /netuse)
  • Sample with : ProcessImpersonator.ImpersonateProcess_NetCredentials()

Below program do exactly this, it will start another executable (located in the same folder and having a name of test.exe).

class Program
    {
        static void Main(string[] args)
        {
            // Will impersonate the process based on a user existing on the same domain
            ProcessImpersonator.ImpersonateProcess_WithProfile(@"C:\test.exe",
                "domain", "user", "password");

            // Will impersonate the call from the process based on a user on a domain
            // with no trust relationship.
            ProcessImpersonator.ImpersonateProcess_NetCredentials(@"C:\test.exe",
                "Otherdomain", "user", "password");
            Console.ReadKey();
        }
    }

ProcessImpersonator.cs looks like this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
using System.Text;

namespace ImpersonateThread
{
    public class ProcessImpersonator
    {
        [Flags]
        enum LogonFlags
        {
            LOGON_WITH_PROFILE = 0x00000001,
            LOGON_NETCREDENTIALS_ONLY = 0x00000002
        }

        [Flags]
        enum CreationFlags
        {
            CREATE_SUSPENDED = 0x00000004,
            CREATE_NEW_CONSOLE = 0x00000010,
            CREATE_NEW_PROCESS_GROUP = 0x00000200,
            CREATE_UNICODE_ENVIRONMENT = 0x00000400,
            CREATE_SEPARATE_WOW_VDM = 0x00000800,
            CREATE_DEFAULT_ERROR_MODE = 0x04000000,
        }

        [StructLayout(LayoutKind.Sequential)]
        struct ProcessInfo
        {
            public IntPtr hProcess;
            public IntPtr hThread;
            public uint dwProcessId;
            public uint dwThreadId;
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        struct StartupInfo
        {
            public int cb;
            public string reserved1;
            public string desktop;
            public string title;
            public uint dwX;
            public uint dwY;
            public uint dwXSize;
            public uint dwYSize;
            public uint dwXCountChars;
            public uint dwYCountChars;
            public uint dwFillAttribute;
            public uint dwFlags;
            public ushort wShowWindow;
            public short reserved2;
            public int reserved3;
            public IntPtr hStdInput;
            public IntPtr hStdOutput;
            public IntPtr hStdError;
        }

        [DllImport("advapi32.dll", CharSet = CharSet.Unicode, ExactSpelling = true,
         SetLastError = true)]
        static extern bool CreateProcessWithLogonW(
            string principal,
            string authority,
            string password,
            LogonFlags logonFlags,
            string appName,
            string cmdLine,
            CreationFlags creationFlags,
            IntPtr environmentBlock,
            string currentDirectory,
            ref StartupInfo startupInfo,
            out ProcessInfo processInfo);

        [DllImport("kernel32.dll")]
        static extern bool CloseHandle(IntPtr h);

        ///
        /// This will use the Logon_NetCredentials_only value.
        /// Usefull for inter-domain scenario without trust relationship
        /// but the system does not validate the credentials.
        ///
        public static void ImpersonateProcess_NetCredentials(string appPath, string domain,
            string user, string password)
        {
            ImpersonateProcess(appPath, domain, user, password,
             LogonFlags.LOGON_NETCREDENTIALS_ONLY);
        }

        ///
        /// This will use the Logon_With_Profile value.
        /// Useful to get the identity of an user in the same domain.
        ///
        public static void ImpersonateProcess_WithProfile(string appPath, string domain,
            string user, string password)
        {
            ImpersonateProcess(appPath, domain, user, password, LogonFlags.LOGON_WITH_PROFILE);
        }

        ///
        /// Call CreateProcessWithLogonW
        ///
        private static void ImpersonateProcess(string appPath, string domain, string user,
            string password, LogonFlags lf)
        {
            StartupInfo si = new StartupInfo();
            si.cb = Marshal.SizeOf(typeof(StartupInfo));
            ProcessInfo pi = new ProcessInfo();

            //
            if (CreateProcessWithLogonW(user, domain, password,
            lf,
            appPath, null,
            0, IntPtr.Zero, null,
            ref si, out pi))
            {
                CloseHandle(pi.hProcess);
                CloseHandle(pi.hThread);
            }
            else
            {
                throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
            }
        }
    }
}

For more information on the topic:

MSDN – CreateProcessWithLogonW.
MSDN – WindowsIdentity.
Geeks with blogs – Managed CreateProcessWithLogonW.

 

With the new TaskFactory class from .Net 4.0 it has become incredibly easy to manage dependencies between multiple tasks.
In below code sample, the TaskFactory receive 6 tasks to execute. Additional logic is added as:
- Task A will only be run when Task B and C are completed.
- Task C will only be run when Task F, E or D is completed.

If you are confused with the ‘=>’ have a look at lambda expression.

using System;
using System.Threading;
using System.Threading.Tasks;

namespace TasksDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            UseTask demoTask = new UseTask();
            Console.ReadKey();
        }
    }

    class UseTask
    {
        public UseTask()
        {
            // Set the TaskFactory - Create and schedule objects
            var tf = new TaskFactory(
                TaskCreationOptions.AttachedToParent,
                TaskContinuationOptions.AttachedToParent);

            var F = tf.StartNew(() => DoSomething(‘F’));
            var E = tf.StartNew(() => DoSomething(‘E’));
            var D = tf.StartNew(() => DoSomething(‘D’));

            // C will be started only when F, E or D has been completed
            var C = tf.ContinueWhenAny(new Task[]{F, E, D}, tasks => DoSomething(‘C’)); 

            var B = tf.StartNew(() => DoSomething(‘B’));

            // A will only happens once B and C are completed.
            var A = tf.ContinueWhenAll(new Task[] {B, C}, tasks => DoSomething(‘A’));
        }

        private void DoSomething(char @char)
        {
            Console.WriteLine(“DoSomething called - {0}”, @char);
            Random rd = new Random();
            Thread.Sleep(rd.Next(1000, 3000));
            Console.WriteLine(“DoSomething called - {0} - DONE”, @char);
        }
    }
}

 

Isn’t that beautiful?

 

 For developers the quality of a program can be often express in the time used to finish the computation. With current multicore processor we have to move our thinking from a serial execution to a concurrent execution. Using delegates in an asynchronous way can force the CLR to allocate multiple threads to your computation.

In below code sample, you will see that I call one method multiple times. This method simply waits 5 seconds. Calling 6 times this method in a synchronous way makes the time to finish obvious: at least 30 seconds! Now using the BeginInvoke method from my delegate I can add multiple threads to these computations. On my machine the time to achieve this is now 9 seconds only!

using System;
using System.Diagnostics;
using System.Text;
using System.Threading;

 

namespace Threads

{

    class Program

    {

        public delegate string myDelegate(string txt);

 

        static void Main(string[] args)

        {

            SynchronousDelegateSample();

            AsynchronousDelegateSample();

 

            Console.WriteLine(“Main thread exits.”);

            Console.ReadKey();

        }

 

        static void SynchronousDelegateSample()

        {

            Stopwatch sw = new Stopwatch();

            sw.Start();

 

            /*

             * All the calls to the delegate will be synchronous

             * This mean that the order will always be 1,2,3,4,5,6

             * The thread used will always be the same.

             */           

            myDelegate dm = new myDelegate(DelegateMethod);

            Console.WriteLine(dm(“calling delegate (1)”));

            Console.WriteLine(dm(“calling delegate (2)”));

            Console.WriteLine(dm(“calling delegate (3)”));

            Console.WriteLine(dm(“calling delegate (4)”));

            Console.WriteLine(dm(“calling delegate (5)”));

            Console.WriteLine(dm(“calling delegate (6)”));

 

            sw.Stop();

            Console.WriteLine(“All work was done in: {0} milliseconds.\n\n”, sw.ElapsedMilliseconds);

        }

 

        static void AsynchronousDelegateSample()

        {

            Stopwatch sw = new Stopwatch();

            sw.Start();

 

            /*

             * All the work will be invoked in a blink.

             * Multiple thread will be used to compute the result of the method.

             */

            myDelegate dm = new myDelegate(DelegateMethod);

            IAsyncResult result1 = dm.BeginInvoke(“calling delegate (1)”, null, null);

            IAsyncResult result2 = dm.BeginInvoke(“calling delegate (2)”, null, null);

            IAsyncResult result3 = dm.BeginInvoke(“calling delegate (3)”, null, null);

            IAsyncResult result4 = dm.BeginInvoke(“calling delegate (4)”, null, null);

            IAsyncResult result5 = dm.BeginInvoke(“calling delegate (5)”, null, null);

            IAsyncResult result6 = dm.BeginInvoke(“calling delegate (6)”, null, null);

 

            /*

             * EndInvoke is synchronous we force to wait for the asynchronous results.

             */

            string r1 = dm.EndInvoke(result1);

            string r2 = dm.EndInvoke(result2);

            string r3 = dm.EndInvoke(result3);

            string r4 = dm.EndInvoke(result4);

            string r5 = dm.EndInvoke(result5);

            string r6 = dm.EndInvoke(result6);

 

            sw.Stop();

            Console.WriteLine(“All asynchronous  work was done in: {0}”,

                sw.ElapsedMilliseconds);

        }              

 

        /// <summary>

        /// Method called by our delegate

        /// Will wait for a random time (between 1 and 10000 milliseconds).

        /// </summary>

        /// <param name=”txt”>Any string are okay.</param>

        /// <returns>A string confirming the end of the process.</returns>

        static string DelegateMethod(string txt)

        {

            // Wait 5 seconds.

            Thread.Sleep(5000);

 

            // Work is finished

            Console.WriteLine(txt + ” \n> Thread ID is: {0}”,

                Thread.CurrentThread.ManagedThreadId.ToString());

            return “>> “ + txt + ” Done !”;

        }

    }

}

Delegate can also be used to call method from different classes. I let you check at the documentation on Msdn.

 

 

This is my first post of, I hope, a series related to WPF and C#.

The examples below are made with VS (Visual Studio) 2010 and .Net 4.0, for this precise example you can make it work with .Net 3.5 at least.

During the life of an application we can listen for some important events, these events can help us to drive the logic of our application from the startup to the end of an application life.

If you are creating a simple WPF Application in VS you will get a file called App.xaml for free. In this file you can add arguments to handle events.

<Application x:Class=”WpfAppStartup.App”

             xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”

             xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”

             Startup=”Application_Startup”

             Exit=”Application_Exit”

             Activated=”Application_Activated”

             Deactivated=”Application_Deactivated”

             SessionEnding=”Application_SessionEnding”

             StartupUri=”MainWindow.xaml”>

 

As you can see in the above code, I added the Startup and Exit arguments in the Application node.
(Tip: just write ‘Startup=’ and then press Tab on your keyboard to have the method name and signature automatically created in App.xaml.cs file).

Below is the list of Events you can catch and a short description.

Name

Description

Startup

Called when Application.Run() is called, shortly before the main window is displayed. This is where you can extract all cmdline arguments.

Exit

Called when the application is shut down, shortly before the Run() methods returns.

Activated

Called when application get focus.

Deactivated

Called when application lose focus.

SessionEnding

Occurs when the Windows session is ending (log off or shut down computer).

DispatcherUnhandledException

Called when an Unhandled application occurs in your application (main thread).

 

Now back to our first goal: getting the arguments array!

private void Application_Startup(object sender, StartupEventArgs e)

{

if (e.Args.Length > 0)

       {

             foreach (string arg in e.Args)

              {

                    // logic for arguments processing.

              }

}

       else

       {

             // No arguments!

}

 

MessageBox.Show(“Application.Run() is called, “ +

“this happen before the main window is displayed.”);

}


If there are any unclear sentence, please feel free to comment!

 

Just noticed that Visual Studio 2010 pro (beta 1) is now available to download as a web installer.

I am personnaly quite new to the VS world, I have been using it daily for only 9 month now. I must say that I am still quite impresse by the simplicity and the power this tool have.

Just try it, it is free so you can make up your own opinion and tell me what you think of it :)

For more info just head to the VS 2010 beta website.

Enjoy,
Ahmet

 

In the two previous posts (Enumerate all classes from a namespace and Enumerate all Namespaces from Root) we gather enough information to enumerate namespaces and classes. In this post we are going to see how to enumerate all the instances from a class via WQL.

using System;
using System.Collections.Generic;
using System.Text;
using System.Management;

namespace WmiNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            //Represents the scoop for management operations
            ManagementScope ms = new ManagementScope();

            //Represents the management query
            ObjectQuery wql = new ObjectQuery("select * from Win32_DiskDrive");

            //Retrieve a collection of management objects
            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher(ms, wql);

            //Represents different collections
            ManagementObjectCollection oc = searcher.Get();

            //The enumerator of the collection
            ManagementObjectCollection.ManagementObjectEnumerator oe =
                oc.GetEnumerator();

            Console.WriteLine("This class got " + oc.Count + " instance(s)\n");

            //Enumerate the collection
            while (oe.MoveNext())
            {
                Console.WriteLine("\n********* " +
                                  oe.Current.GetPropertyValue("Name") + "\n");

                //Foreach of the properties existing in one of our instance
                //display the propety name and her value
                foreach (PropertyData prop in oe.Current.Properties)
                {
                    Console.WriteLine("> " + prop.Name + " (" + prop.Value + ")");
                }
            }

            Console.ReadLine();
        }
    }
}

Below is a screenshot of what I get after executing this program:

wmi Class Instance Screenshoot

Next step will be to add, update or delete instance from a class.

Ahmet