Feeds:
Posts
Comments

Coming soon…

In this post I will demonstrate how to verify if a given password meet the current Windows password policy.

We will use the NetValidatePasswordPolicy API for that.

Instead of using C# pinvoke approach, we will call the API through Managed C++ then call the managed C++ DLL with C#. This approach will be much more cleaner and readable.

First, we create our Managed C++ DLL which contains our validation method :

using namespace System;

namespace pwdval
{
    public ref class srPasswordValidator
    {
        public :int ValidatePassword(System::String ^paramPassword)
        {
            pin_ptr<const wchar_t> wchDomain = PtrToStringChars(paramPassword);

            size_t convertedCharsPassword = 0;
            size_t sizeInBytesPassword = ((paramPassword->Length + 1) * 2);
            errno_t errPassword = 0;
            char    *chPassword = (char *)malloc(sizeInBytesPassword);

            errPassword = wcstombs_s(&convertedCharsPassword,
                                    chPassword, sizeInBytesPassword,
                                    wchDomain, sizeInBytesPassword);

            if (errPassword != 0)
                throw gcnew Exception("Password could not be converted");

            // first, find out the required buffer size, in wide characters
            int nPasswordSize = MultiByteToWideChar(CP_ACP, 0, chPassword, -1, NULL, 0);

            LPWSTR wPassword = new WCHAR[nPasswordSize];

            // call again to make the conversion
            MultiByteToWideChar(CP_ACP, 0, chPassword, -1, wPassword, nPasswordSize);

            NET_API_STATUS stat;
            NET_VALIDATE_PASSWORD_CHANGE_INPUT_ARG InputArg = {0};
            NET_VALIDATE_OUTPUT_ARG* pOutputArg = NULL;
            wchar_t* wzServer = 0;

            //wchar_t wzPwd = chPassword;
            InputArg.ClearPassword = wPassword;
            InputArg.PasswordMatch = TRUE;
            stat = NetValidatePasswordPolicy(wzServer, NULL, NetValidatePasswordChange, &InputArg, (void**)&pOutputArg);

            NET_API_STATUS intStatus = pOutputArg->ValidationStatus;

            NetValidatePasswordPolicyFree((void**)&pOutputArg);
            delete []wPassword;

            return intStatus;
        }

    };
}

This method returns an integer that we will convert to an Enum

enum enmResult
        {
            // <summary> 2234 - This operation is not allowed on this special group. </summary>
            SpeGroupOp = 2234,
            // <summary> 2235 - This user is not cached in user accounts database session cache. </summary>
            NotInCache = 2235,
            // <summary> 2236 - The user already belongs to this group. </summary>
            UserInGroup = 2236,
            // <summary> 2237 - The user does not belong to this group. </summary>
            UserNotInGroup = 2237,
            // <summary> 2238 - This user account is undefined. </summary>
            AccountUndefined = 2238,
            // <summary> 2239 - This user account has expired. </summary>
            AccountExpired = 2239,
            // <summary> 2240 - The user is not allowed to log on from this workstation. </summary>
            InvalidWorkstation = 2240,
            // <summary> 2241 - The user is not allowed to log on at this time. </summary>
            InvalidLogonHours = 2241,
            // <summary> 2242 - The password of this user has expired. </summary>
            PasswordExpired = 2242,
            // <summary> 2243 - The password of this user cannot change. </summary>
            PasswordCantChange = 2243,
            // <summary> 2244 - This password cannot be used now. </summary>
            PasswordHistConflict = 2244,
            // <summary> 2245 - The password does not meet the password policy requirements. Check the minimum password length, password complexity and password history requirements. </summary>
            PasswordTooShort = 2245
        }

You can find the complete enum definition in the sources downloadable at the end of the post.

Here is now hows we use the DLL to validate a password :

        private object pwValidator;

        public PwdVal()
        {
            foreach (string curModule in Directory.GetFiles(ModuleSearchPath, "srPasswordValidator.dll"))
            {
                try
                {
                    Assembly objAssembly = Assembly.LoadFile(curModule);
                    System.Type objType = objAssembly.GetType("pwdval.srPasswordValidator");

                    if ((objType != null))
                    {
                        pwValidator = Activator.CreateInstance(objType);

                        break;
                    }
                }
                catch (Exception ex)
                {
                    pwValidator = null;
                }
            }
        }

        private string ModuleSearchPath
        {
            get { return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); }
        }

        public bool ValidatePassword(string paramPassword, ref string paramReason)
        {
            try
            {
                if (pwValidator == null)
                {
                    paramReason = "Could not validate the password - pwValidator is NULL";
                    return false;
                }

                object obj = pwValidator.GetType().GetMethod("ValidatePassword").Invoke(pwValidator, new object[] { paramPassword });

                if (obj == null)
                {
                    paramReason = "Could not validate the password - obj is NULL";
                    return false;
                }

                int val = Int32.Parse(obj.ToString());

                enmResult intResult = (enmResult)val;

                paramReason = intResult.ToString();

                return intResult == enmResult.Success;
            }
            catch (Exception ex)
            {
                paramReason = ex.Message;
                return false;
            }
        }

You can download sources and sample here : http://dl.free.fr/q04LOHSpM

As you may know, Windows is virtualizing some parts of the registry under 64 bit.

So if you try to open, for example, this key : “HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\90”, from a 32 bit C# application running on a 64 bit system, you will be redirected to : “HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server\90”

Why ? Because Windows uses the Wow6432Node registry entry to present a separate view of HKEY_LOCAL_MACHINE\SOFTWARE for 32 bit applications that runs on a 64 bit systems.

If you want to explicitly open the 64 bit view of the registry, here is what you have to perform :

You are using VS 2010 and version 4.x of the .NET framework

It’s really simple, all you need to do is, instead of doing :

//Will redirect you to the 32 bit view
RegistryKey sqlsrvKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\90");

do the following :

RegistryKey localMachineX64View = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
RegistryKey sqlsrvKey = localMachineX64View.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\90");

Prior versions of the .NET framework

For the prior versions of the framework, we have to use P/Invoke and call the function RegOpenKeyExW with parameter KEY_WOW64_64KEY

        enum RegWow64Options
        {
            None = 0,
            KEY_WOW64_64KEY = 0x0100,
            KEY_WOW64_32KEY = 0x0200
        }

        enum RegistryRights
        {
            ReadKey = 131097,
            WriteKey = 131078
        }

        /// <summary>
        /// Open a registry key using the Wow64 node instead of the default 32-bit node.
        /// </summary>
        /// <param name="parentKey">Parent key to the key to be opened.</param>
        /// <param name="subKeyName">Name of the key to be opened</param>
        /// <param name="writable">Whether or not this key is writable</param>
        /// <param name="options">32-bit node or 64-bit node</param>
        /// <returns></returns>
        static RegistryKey _openSubKey(RegistryKey parentKey, string subKeyName, bool writable, RegWow64Options options)
        {
            //Sanity check
            if (parentKey == null || _getRegistryKeyHandle(parentKey) == IntPtr.Zero)
            {
                return null;
            }

            //Set rights
            int rights = (int)RegistryRights.ReadKey;
            if (writable)
                rights = (int)RegistryRights.WriteKey;

            //Call the native function >.<
            int subKeyHandle, result = RegOpenKeyEx(_getRegistryKeyHandle(parentKey), subKeyName, 0, rights | (int)options, out subKeyHandle);

            //If we errored, return null
            if (result != 0)
            {
                return null;
            }

            //Get the key represented by the pointer returned by RegOpenKeyEx
            RegistryKey subKey = _pointerToRegistryKey((IntPtr)subKeyHandle, writable, false);
            return subKey;
        }

        /// <summary>
        /// Get a pointer to a registry key.
        /// </summary>
        /// <param name="registryKey">Registry key to obtain the pointer of.</param>
        /// <returns>Pointer to the given registry key.</returns>
        static IntPtr _getRegistryKeyHandle(RegistryKey registryKey)
        {
            //Get the type of the RegistryKey
            Type registryKeyType = typeof(RegistryKey);
            //Get the FieldInfo of the 'hkey' member of RegistryKey
            System.Reflection.FieldInfo fieldInfo =
            registryKeyType.GetField("hkey", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

            //Get the handle held by hkey
            SafeHandle handle = (SafeHandle)fieldInfo.GetValue(registryKey);
            //Get the unsafe handle
            IntPtr dangerousHandle = handle.DangerousGetHandle();
            return dangerousHandle;
        }

        /// <summary>
        /// Get a registry key from a pointer.
        /// </summary>
        /// <param name="hKey">Pointer to the registry key</param>
        /// <param name="writable">Whether or not the key is writable.</param>
        /// <param name="ownsHandle">Whether or not we own the handle.</param>
        /// <returns>Registry key pointed to by the given pointer.</returns>
        static RegistryKey _pointerToRegistryKey(IntPtr hKey, bool writable, bool ownsHandle)
        {
            //Get the BindingFlags for private contructors
            System.Reflection.BindingFlags privateConstructors = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
            //Get the Type for the SafeRegistryHandle
            Type safeRegistryHandleType = typeof(Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid).Assembly.GetType("Microsoft.Win32.SafeHandles.SafeRegistryHandle");
            //Get the array of types matching the args of the ctor we want
            Type[] safeRegistryHandleCtorTypes = new Type[] { typeof(IntPtr), typeof(bool) };
            //Get the constructorinfo for our object
            System.Reflection.ConstructorInfo safeRegistryHandleCtorInfo = safeRegistryHandleType.GetConstructor(
            privateConstructors, null, safeRegistryHandleCtorTypes, null);
            //Invoke the constructor, getting us a SafeRegistryHandle
            Object safeHandle = safeRegistryHandleCtorInfo.Invoke(new Object[] { hKey, ownsHandle });

            //Get the type of a RegistryKey
            Type registryKeyType = typeof(RegistryKey);
            //Get the array of types matching the args of the ctor we want
            Type[] registryKeyConstructorTypes = new Type[] { safeRegistryHandleType, typeof(bool) };
            //Get the constructorinfo for our object
            System.Reflection.ConstructorInfo registryKeyCtorInfo = registryKeyType.GetConstructor(
            privateConstructors, null, registryKeyConstructorTypes, null);
            //Invoke the constructor, getting us a RegistryKey
            RegistryKey resultKey = (RegistryKey)registryKeyCtorInfo.Invoke(new Object[] { safeHandle, writable });
            //return the resulting key
            return resultKey;
        }

        [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
        public static extern int RegOpenKeyEx(IntPtr hKey, string subKey, int ulOptions, int samDesired, out int phkResult);

Then we can open our registry key like this :

RegistryKey sqlsrvKey = _openSubKey(Registry.LocalMachine, @"SOFTWARE\Microsoft\Microsoft SQL Server\90", false, RegWow64Options.KEY_WOW64_64KEY);

As you can see, the framework 4 make our life easier:)

Introduction

When developping our applications we can experience than some reference types have the same behavior than value types. As a matter of fact there is no more references to the copied object . It’s the case for  System.String and System.Nullable<T> which are called immutable object because when affecting new value to these variables a perfect copy is created to set the new value.

Immutable objects have many advantages :

  • No side effect
  • Thread safe
  • Perfect key of map (because of their unchanging Hashcode)
  • A simple copy of the reference represent a implementation of the Cloneable interface

What’s happen when we want to persist these object, by disconnecting them around your system? As a matter of fact, when the object is immutable it is difficult to rebuilt the instance because of its only “getters” and readonly attributes.

Let’s see a possible solution by constructing an immutable class Person.

/// <summary>
    /// Immutable class Person
    /// </summary>
    [DataContract]
    public class Person
    {
        private static readonly DataContractSerializer dcSerializer = new DataContractSerializer(typeof(Person));

        [DataMember]
        private readonly string m_Name;

        public Person(string name)
        {
            this.m_Name = name;
        }

        public String Name
        {
            get
            {
                return this.m_Name;
            }
        }
}

To proceed we’ll be using DataContractSerializer class to perform with DataContract & readonly attribute as DataMember : It serializes and deserializes an instance of a type into an XML stream or document using a supplied data contract. This class cannot be inherited (source msdn).

public String ObjectToXML()
{
      using (MemoryStream m = new MemoryStream())
      {
           dcSerializer.WriteObject(m, this);
           m.Position = 0;

           using (StreamReader reader = new StreamReader(m))
           {
                 return reader.ReadToEnd();
            }
      }
}

public static Person XmlToObject(String xmlStream)
{
       using (MemoryStream m = new MemoryStream())
       using (StreamWriter writer = new StreamWriter(m))
       {
            writer.Write(xmlStream);
            writer.Flush();
            m.Position = 0;
            return dcSerializer.ReadObject(m) as Person;
       }
}

And you can use it as following code :

Person p = new Person("Zizou");
String serializedZizou = p.ObjectToXml();
Person ObjectP = Person.XmlToObject(serializedZizou);
String name = ObjectP.Name;

Enjoy!:)

Introduction

When an assembly has been loaded in an Application Domain, the embeded code can be executed.

This code can be executed in the current Application Domain or in another one, we will see how to proceed by differents way.

For all the following examples we will use a namespace MyNameSpace containing 2 classes :  ObjectRemote & Program.

 // This namespace contains code to be called.
 namespace MyNameSpace
 {
   public class ObjectRemote : System.MarshalByRefObject
   {
     public ObjectRemote ()
     {
       System.Console.WriteLine("Hello, World! (ObjectRemote Constructor)");
     }
   }
   class Program
   {
     static void Main()
     {
       System.Console.WriteLine("Hello, World! (Main method)");
     }
   }
}

I) Loading assembly in the current AppDomain

To reach some code from another application you can load your assembly in the current AppDomain or create a new AppDomain and load your assembly inside.

The following example shows how to load an assembly in the current AppDomain :

static void main()
{
  //Load the assembly into the current AppDomain
 System.Reflection.Assembly newAssembly = System.Reflection.Assembly.LoadFrom(@"c:\MyNameSpace.exe")

 //Instanciate ObjectRemote:
 newAssembly.CreateInstance("MyNameSpace.ObjectRemote");
}

II)Loading assembly in another AppDomain

When using this approach, you have to use ExecuteAssembly method of AppDomain class to reach the default entry point or CreateInstanceFrom method to create an instance of the ObjectRemote.

static void main()
{
//Load the assembly into another AppDomain and call the default entry point
System.AppDomain newAppDomain = new System.AppDomain.CreateDomain("");
NewAppDomain .ExecuteAssembly(@"c:\MyNameSpace.exe")

//Create an instance of ObjectRemote
NewAppDomain.CreateInstanceFrom(@" :\MyNameSpace.exe"," MyNameSpace.ObjectRemote");
}

Enjoy😉

IoC Pattern

Introduction:

IoC (inversion of control) is a design pattern used to uncouple classes to avoid strong dependencies between them.
As a matter of fact every system does not make assumptions about what other systems do or should do, so no side effect when replacing a system by another one.

Let’s have a first example showing classes having strong dependencies between them. Here we have a main class Singer, which let us know the song style and what formation it is.

public class Song
{
  public string GetStyle()
  {
      return "Rock n Roll !";
  }
}

public class LineUp
{
  public string GetFormation()
  {
      return "Trio";
  }
}

public class Singer
{
  Song song;
  LineUp lineUp;

  public Singer()
  {
      song = new Song();
      lineUp = new LineUp();
  }

  public string Sing()
  {
      return "Singer sings " + song.GetStyle() + " and it is a " +  lineUp.GetFormation();
  }
}

here’s the Main method :

Singer singer = new Singer();
Console.WriteLine(singer.Sing());

As result we have : singer sings Rock n Roll ! and it is a Trio
But what would we do if we want to hear another song?? Hearing the same one is good but at the end it could break your tears!!

Implementation of interfaces to replaces instanciate classes (Song, LineUp), and by this way uncoupling main class Singer with the others.

public interface ISong
{
  public string GetStyle();
}

public interface ILineUp
{
  public string GetFormation();
}

public class Song : ISong
{
  public string ISong.GetStyle()
  {
      return "Hip Hop !";
  }
}

public class LineUp : ILineUp
{
  public string ILineUp.GetFormation()
  {
      return "Solo";
  }
}

public class Singer
{
  ISong _isong;
  ILineUp _ilineup;

  public string Singer(ISong is, ILineUp il)
  {
      _isong = is;
      _ilineup = il;
  }

  public string Sing()
  {
      return Singer sings " + _isong.GetStyle() + "it is a " +  _ilineup.GetFormation();
  }
}

here’s the Main method : Now if we want to here another artist, we just have to
instanciate so many class that we want

//Creating dependencies
Song oldsong = new Song();
LineUp oldlineUp = new LineUp();
//Injection of dependencies
Singer singer = new Singer(oldsong,oldlineup);
Console.WriteLine(singer.Sing());

//Creating dependencies
Song newsong = new Song();
LineUp newlineUp = new LineUp();
//Injection of dependencies
Singer singer = new Singer(newsong,newlineup);
Console.WriteLine(singer.Sing());

Thanks for reading !!

Introduction:

As you have seen in this article Parallel.For loop in C#4.0 invokes a given instruction, passing in arguments :

  • an Integer type “from inclusive”
  • an Integer type “to exclusive”
  • a delegate for the action to be done

This is done on multiple threads.
In this article we will see a way to implement a static For method in C#2.0 having the same behavior.

First of all, let’s implementing our delegate which will be passed in parameter of our For static method.

public delegate void DelegateFor(int i);
public delegate void DelegateProcess();

Now the For static method

public class Parallel
{
   public static void For(int from, int to, DelegateFor delFor)
   {
      //step or chunck will be done as 4 by 4
      int step = 4;
      int count = from - step;
      int processCount = Environment.ProcessorCount;

      //Now let's take the next chunk 
      DelegateProcess process = delegate()
      {
         while (true)
         {
            int iter = 0;
            lock (typeof(Parallel))
            {
               count += step;
               cntMem = count;
            }
            for (int i = iter ; i < iter  + step; i++)
            {
              if (i >= to)
                return;
                delFor(i);
            }
         }
      };

     //IAsyncResult array to launch Thread(s)
     IAsyncResult[] asyncResults = new IAsyncResult[processCount];
     for (int i = 0; i < processCount; ++i)
     {
         asyncResults[i] = process.BeginInvoke(null, null);
     }
     //EndInvoke to wait for all threads to be completed
     for (int i = 0; i < threadCount; ++i)
     {
        process.EndInvoke(asyncResults[i]);
     }
  }
}

Don’t forget that a bigger step would perform the process by reducing lock waiting time. In consequence we would increase parallelism which is not a good idea because of the context changing between a thread and another one which consumes resources.

Do the call like this

class Program
{
  public static void Main(string[] args)
  {
     Parallel.For(0, 100, delegate (int i)
     {
        Console.WriteLine(i + " " + TID);
     });

     Console.Read();
   }

   public static string TID
   {
     get
     {
       return "TID = " +     System.Threading.Thread.CurrentThread.ManagedThreadId.ToString();
      }
   }
}

Or using lambda exression in C#3.0😉

public static void Main(string[] args)
{
  Parallel.For(0, 100, (int i) => Console.WriteLine(i + " " + TID));
  Console.Read();
}

Thanks for reading !!

Follow

Get every new post delivered to your Inbox.