Codility.com


On the codility.com website you can test your programming skills. My first! result is here.
You can choose only one free demo test but you can purchase different packages for more tests.
Try it! :-)
Posted on 15:36 by csharper and filed under , , , , | 0 Comments »

Dynamic DLL loading with reflection


We often have to load different class libraries runtime. The code segment below solves this problem efficiently. Only you have to call the InvokeDllMethod of the DllLoader class with these parameters: first is the absolute path of the DLL you want to load, second is the name of the method you want to call and the third is the input parameters in an object array for the method of the DLL.

In the GetClassReference method we are searching for the method's class as a class which implements the IComparable interface. So in this case we suppose that the class which implements the IComparable interface has the method that we passed as the second parameter of InvokeDllMethod. Here you can search the class in different ways (e.g. name of class).

This solution is very efficient because we don't load the assembly or the class again if we loaded it before. We use two hashtables (one for classes, one for assemblies) to store references. Hashtables are efficient data structures because we can insert elements and search in the hashtable in constant time, so it is very fast. If we load same assemblies in every method calling, our program will be so redundant...
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace SampleApp
{
    public static class DllLoader
    {
        private class DllLoaderClassInfo
        {
            public Type type;
            public object ClassObject;
 
            public DllLoaderClassInfo() { }
 
            public DllLoaderClassInfo(Type t, object c)
            {
                type = t;
                ClassObject = c;
            }
        }
 
        private static Hashtable AssemblyReferences = new Hashtable();
        private static Hashtable ClassReferences = new Hashtable();
 
        private static DllLoaderClassInfo GetClassReference(string AssemblyName)
        {
            if (ClassReferences.ContainsKey(AssemblyName) == false)
            {
                Assembly assembly;
                if (AssemblyReferences.ContainsKey(AssemblyName) == false)
                {
                    AssemblyReferences.Add(AssemblyName, assembly = Assembly.LoadFrom(AssemblyName));
                }
                else
                {
                    assembly = (Assembly)AssemblyReferences[AssemblyName];
                }
                foreach (Type type in assembly.GetTypes())
                {
                    bool implementsIComparable = typeof(IComparable).IsAssignableFrom(type);
                    if (implementsIComparable)
                    {
                        DllLoaderClassInfo ci = new DllLoaderClassInfo(type, Activator.CreateInstance(type));
                        ClassReferences.Add(AssemblyName, ci);
                        return (ci);
                    }
                }
                throw (new Exception("Could not instantiate class!"));
            }
            return ((DllLoaderClassInfo)ClassReferences[AssemblyName]);
        }
 
        public static object InvokeDllMethod(string assemblyName, string methodName, object[] args)
        {
            DllLoaderClassInfo ci = GetClassReference(assemblyName);
            object Result = ci.type.InvokeMember(methodName, BindingFlags.Default | BindingFlags.InvokeMethod, null, ci.ClassObject, args);
            return (Result);
        }
    }
 
    private class Program
    {
        private static void Main(string[] args)
        {
            object[] inputParams = new object[] { "abc", 1, DateTime.Now };
            DllLoader.InvokeDllMethod(@"D:\ClassLibraries\SampleClassLib.dll", "SampleMethod", inputParams);
        }
    }
}

Posted on 13:43 by csharper and filed under , , , , | 0 Comments »

Checking equality of arrays with a generic method


In this case we define the equality of two arrays as all array elements are pairwise equal.
The method below compares two arrays and it says that those are equal or not. The first and the second parameter is any kind of array. With the third boolean parameter you can give that method has to ignore position of elements in the array or not. In the method's generic parameter you have to give the type of the arrays. The two arrays must be the same type.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace SampleApp
{
    public static class Utils
    {
        public static bool arraysAreEquals(Array a1, Array a2, bool ignorePositionOfElements)
        {
            if (a1 == null && a2 == null)
                return true;
            else if ((a1 == null && a2 != null) || (a1 != null && a2 == null))
                return false;
            else
            {
                if (a1.Length != a2.Length)
                    return false;
                else
                {
                    if (ignorePositionOfElements)
                    {
                        Array.Sort(a1);
                        Array.Sort(a2);
                    }
                    for (int i = 0; i < a1.Length; i++)
                    {
                        T x1 = (T)a1.GetValue(i);
                        T x2 = (T)a2.GetValue(i);
                        if (!x1.Equals(x2))
                            return false;
                    }
                }
            }
            return true;
        }
    }
 
    private class Program
    {
        private static void Main(string[] args)
        {
            string[] array1 = new string[] { "cba", "abc", "bca" };
            string[] array2 = new string[] { "bca", "cba", "abc" };
            Utils.arraysAreEquals<string>(array1, array2, false); // result is: false
            Utils.arraysAreEquals<string>(array1, array2, true);  // result is: true
        }
    }
}

Posted on 12:42 by csharper and filed under , , | 1 Comments »

Visual Studio 2010 Productivity Power Tools


The Visual Studio 2010 Productivity Power Tools is a set of extensions to Visual Studio 2010 Professional (and above) which improves developer productivity.

It has a lot of useful extensions:
  • Solution Navigator
  • Quick Access
  • Auto Brace Completion
  • Searchable and Reference Dialog
  • Highlight Current Line
  • HTML Copy
  • Triple Click
  • etc...
You can find it here:

Posted on 12:25 by csharper and filed under , , , , | 0 Comments »

Get members from given Active Directory group using LDAP filters


You have to add System.DirectoryServices.dll as a reference to your project. If you cannot find it under the .NET tab on the 'Add reference' dialog, you have to browse it from the C:\Windows\Microsoft.NET\framework\vX.Y\ path.

public List<string> GetAllUsersFromGroup(string domain, string group)
{
    List<string> retVal = new List<string>();
    DirectoryEntry entry = new DirectoryEntry(String.Concat("LDAP://", domain));
    DirectorySearcher searcher = new DirectorySearcher("(&(objectCategory=group)(cn=" + group + "))");
    searcher.SearchRoot = entry;
    searcher.SearchScope = SearchScope.Subtree;
    SearchResult result = searcher.FindOne();
    foreach (string member in result.Properties["member"])
    {
        DirectoryEntry de = new DirectoryEntry(String.Concat("LDAP://", domain, "/", member.ToString()));
        if (de.Properties["objectClass"].Contains("user") && de.Properties["cn"].Count > 0)
        {
            retVal.Add(de.Properties["cn"][0].ToString());
        }
    }
    return retVal;
}
Posted on 17:55 by csharper and filed under , , , , | 2 Comments »

Multiple web service references sharing types


To share types between more web service references, generate proxy classes manual with the wsdl.exe (for example in a Visual Studio command prompt) like this:

wsdl /sharetypes WebServiceURL1 WebServiceURL2 ... WebServiceURLn
/o:OutputFileName.cs /n:NamespaceName

Just add this .cs file to your project and use the generated namespace's classes, you should't add any web reference. The types which are the same on more web services will be generated only once to a common namespace. This is very useful, because you needn't copy a lot of properties...

Posted on 22:05 by csharper and filed under , , , , , | 1 Comments »

XML syntax highlighting in a rich textbox


Source: http://www.codeproject.com/KB/cs/RTFSyntaxColour.aspx

private void AddColouredText(string strTextToAdd)
{
    //Use the RichTextBox to create the initial RTF code
    txtbox.Clear();
    txtbox.AppendText(strTextToAdd);
    string strRTF = txtbox.Rtf;
    txtbox.Clear();
 
    /* 
     * ADD COLOUR TABLE TO THE HEADER FIRST 
     * */
 
    // Search for colour table info, if it exists (which it shouldn't)
    // remove it and replace with our one
    int iCTableStart = strRTF.IndexOf("colortbl;");
 
    if (iCTableStart != -1) //then colortbl exists
    {
        //find end of colortbl tab by searching
        //forward from the colortbl tab itself
        int iCTableEnd = strRTF.IndexOf('}', iCTableStart);
        strRTF = strRTF.Remove(iCTableStart, iCTableEnd - iCTableStart);
 
        //now insert new colour table at index of old colortbl tag
        strRTF = strRTF.Insert(iCTableStart,
            // CHANGE THIS STRING TO ALTER COLOUR TABLE
            "colortbl ;\\red255\\green0\\blue0;\\red0\\green128\\blue0;\\red0\\green0\\blue255;}");
    }
 
    //colour table doesn't exist yet, so let's make one
    else
    {
        // find index of start of header
        int iRTFLoc = strRTF.IndexOf("\\rtf");
        // get index of where we'll insert the colour table
        // try finding opening bracket of first property of header first                
        int iInsertLoc = strRTF.IndexOf('{', iRTFLoc);
 
        // if there is no property, we'll insert colour table
        // just before the end bracket of the header
        if (iInsertLoc == -1) iInsertLoc = strRTF.IndexOf('}', iRTFLoc) - 1;
 
        // insert the colour table at our chosen location                
        strRTF = strRTF.Insert(iInsertLoc,
            // CHANGE THIS STRING TO ALTER COLOUR TABLE
            "{\\colortbl ;\\red128\\green0\\blue0;\\red0\\green128\\blue0;\\red0\\green0\\blue255;}");
    }
 
    /*
     * NOW PARSE THROUGH RTF DATA, ADDING RTF COLOUR TAGS WHERE WE WANT THEM
     * In our colour table we defined:
     * cf1 = red  
     * cf2 = green
     * cf3 = blue             
     * */
 
    for (int i = 0; i < strRTF.Length; i++)
    {
        if (strRTF[i] == '<')
        {
            //add RTF tags after symbol 
            //Check for comments tags 
            if (strRTF[i + 1] == '!')
                strRTF = strRTF.Insert(i + 4, "\\cf2 ");
            else
                strRTF = strRTF.Insert(i + 1, "\\cf1 ");
            //add RTF before symbol
            strRTF = strRTF.Insert(i, "\\cf3 ");
 
            //skip forward past the characters we've just added
            //to avoid getting trapped in the loop
            i += 6;
        }
        else if (strRTF[i] == '>')
        {
            //add RTF tags after character
            strRTF = strRTF.Insert(i + 1, "\\cf0 ");
            //Check for comments tags
            if (strRTF[i - 1] == '-')
            {
                strRTF = strRTF.Insert(i - 2, "\\cf3 ");
                //skip forward past the 6 characters we've just added
                i += 8;
            }
            else
            {
                strRTF = strRTF.Insert(i, "\\cf3 ");
                //skip forward past the 6 characters we've just added
                i += 6;
            }
        }
    }
    txtbox.Rtf = strRTF;
}

Posted on 12:36 by csharper and filed under , , , | 1 Comments »