Archive for the ‘C# (C-Sharp)’ Category.

WPF Localization at run-time

I needed a better WPF Localization solution and I came up with one and posted it over on my WPF blog.

I would love some feed back, so if you are interested, check it out.

How to change language at run-time in WPF with loadable Resource Dictionaries and DynamicResource Binding (Example 1)

C# Dictionary

In C# there is an object called Dictionary<TKey, TValue> that can be used to store data.  The Dictionary<TKey, TValue> is essentially a collection of KeyValuePair<TKey, TValue> objects.

C# Dictionary Example 1 – A word dictionary

In this example, we create a simple dictionary with a few words and there definitions and show you how they are accessed.

using System;
using System.Collections.Generic;
using System.Linq;

namespace DictionaryExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<String, String> words = new Dictionary<string, string>();
            words.Add("Hello", "An expression or gesture of greeting.");
            words.Add("Goodbye", "A concluding remark or gesture at parting.");
            words.Add("Computer", "A programmable usually electronic device that can store, retrieve, and process data.");
            words.Add("Friend", "One attached to another by affection or esteem");

            Console.WriteLine("Word - Definition");
            Console.WriteLine("===================================================");
            foreach (KeyValuePair<string, string> pair in words)
            {
                Console.WriteLine(string.Format("{0} - {1}", pair.Key, pair.Value));
            }
        }
    }
}

Accessing values in a C# Dictionary

You can access the value using the key. In the case of our word dictionary, the word is the key and the definition is the value.

While you could access the value as follows, there is a problem with the below method.

    private string GetDefinition(String inWord, Dictionary<String, String> inDictionary)
    {
        return inDictionary[inWord];
    }

Do you know what the problem is?  Right, it doesn’t handle a missing value.  If the value doesn’t exist, this will throw a KeyNotFoundException.

Handling a missing value in a C# Dictionary

There are two ways to prevent the KeyNotFoundException.

Method 1 – Use TryGetValue()

TryGetValue() return a bool It takes in the Key and also an out reference. It populates the out reference. Here is an example.

    private string GetDefinition(String inWord, Dictionary<String, String> inDictionary)
    {
        string retVal;
        // String is set to null if the value is not found
        return inDictionary.TryGetValue(inWord, out retVal) ? retVal : ;
    }

I am not a big fan of how the TryGetValue() function was implemented to return a bool However, I understand why it was implemented to return a bool. One might wonder why it returns bool. You may be thinking that TryGetValue() could return a value if found, null otherwise, right? Wrong! Reason 1 – Don’t forget that the value might actually be null. Reason 2 – While this Dictionary used a nullable type, string, another implementation might implement using a type that is not nullable, such as int.

Method 2 – Using ContainsKey()

Alternately you could check if the value exists first using ContainsKey(). Here is an example.

    private string GetDefinition(String inWord, Dictionary<String, String> inDictionary)
    {
        return inDictionary.ContainsKey(inWord) ? inDictionary[inWord] : string.Empty;
    }

I prefer this because to me, it is more readable than the TryGetValue() function, but feel free to make your own opinion.

Looping through a C# Dictionary

Now imagine you wanted to get all the words and their definitions that start with a certain letter. In this case you are creating a Dictionary that is a subset of the full Dictionary. You could do this with a foreach loop. Notice that the object in the foreach loop is a KeyValuePair.

        private Dictionary<String,String> GetWordsAndDefinitionsWhereWordsStartWith(Dictionary<String, String> inDictionary, char inChar)
        {
            Dictionary<String, String> wordsAndDefinitionsWhereWordsStartWithC = new Dictionary<string, string>();
            foreach (KeyValuePair<string, string> pair in inDictionary)
            {
                if (pair.Value.StartsWith(inChar.ToString(), StringComparison.CurrentCultureIgnoreCase))
                    wordsAndDefinitionsWhereWordsStartWithC.Add(pair.Key, pair.Value);
            }
            return wordsAndDefinitionsWhereWordsStartWithC;
        }

You could alternately use LINQ against the C# Dictionary to get the method body to be a single line.

    private Dictionary<String,String> GetWordsAndDefinitionsWhereWordsStartWith(Dictionary<String, String> inDictionary, char inChar)
    {
        return inDictionary.Where(pair => pair.Value.StartsWith(inChar.ToString(), StringComparison.CurrentCultureIgnoreCase)).ToDictionary(pair => pair.Key, pair => pair.Value);
    }

You could just get the words and not the definitions in a List<String> as well.

    private List<String> GetWordstartingWith(Dictionary<String, String> inDictionary, char inChar)
    {
        List<String> wordsStartingWith = new List<String>();
        foreach (KeyValuePair<string, string> pair in inDictionary)
        {
            if (pair.Value.StartsWith(inChar.ToString(), StringComparison.CurrentCultureIgnoreCase))
                wordsStartingWith.Add(pair.Key);
        }
        return wordsStartingWith;
    }

Again, you could use LINQ against the C# Dictionary to make this function one line.

    private List<String> GetWordstartingWith(Dictionary<String, String> inDictionary, char inChar)
    {
        return (from pair in inDictionary where pair.Value.StartsWith(inChar.ToString(), StringComparison.CurrentCultureIgnoreCase) select pair.Key).ToList();
    }

References

LANDesk Support Tools – Android Edition (Demo)

This is my first real project written for Android. Yes, I wrote it in C# using Mono for Android.

How to connect to the LANDesk MBSDK using C#?

This article is to demonstrate to LANDesk admins how to connect to the LANDesk MBSDK with C#.

Prerequisites

LANDesk

  1. A LANDesk Core Server accessible via the network.
  2. Credentials to connect to the LANDesk Core Server.

Basically if you can hit the MBSDK with a browser and login, you are good to go.

http://CoreServer/mbsdkservice/msgsdk.asmx

Visual Studio

  1. It is assumed that you have Visual Studio Professional installed

Step 1 – Create a Visual Studio Project

  1. In Visual Studio, Go to File | New | Project.
  2. Select that project type.
    Note: For this example I chose Console Application.
  3. Give the Project a name.
    Note: I named my project TalkToMBSDK.
  4. Click OK.
    Note: I went ahead and left my client application configured for .NET 4 even though I know the server currently is .NET 3.5 Sp1.

Step 2 – Add a Web Reference to the MBSDK

  1.  In you new Visual Studio project, right-click on the project and click Add Service Reference.
    Note: We actually need a Web  Reference but this is how we get there.
  2. Click Advanced on the bottom left.
  3. Click on Add Web Reference, also on the bottom left.
  4. Enter the URL to the MBSDK on your Core Server: http://CoreServer/mbsdkservice/msgsdk.asmx
  5. Change the Web Reference Name (on the right) to mbsdk.
    Note: You can name it whatever you want, but because there is an object called MBSDK (all uppercase), I chose to make the namespace mbsdk (all lowercase).
  6. Click Add Reference.

Step 3 – Test using the LANDesk SDK

  1. In the Program.cs add the following code.  You next steps are in the code comments.
using System.Net;
using TalkToMBSDK.mbsdk;

namespace TalkToMBSDK
{
    class Program
    {
        static void Main(string[] args)
        {
            // Step 1 - You need to use your credentials
            string user = "SomeUser";
            string password = "SomePassword";
            string domain = "SomeDomain.tld";

            // Step 2 - Configure a CredentialCache object with the URL and your creds
            string uri = "http://CoreServer/MBSDKService/MsgSDK.asmx";
            CredentialCache MyCredentialCache = new System.Net.CredentialCache();
            MyCredentialCache.Add(new System.Uri(uri), "NTLM", new NetworkCredential(user, password, domain));

            // Step 3 - Create an MBSDK object and set its CredentialCache object to the one you just created
            MBSDK sdk = new MBSDK();
            sdk.Credentials = MyCredentialCache;

            // Step 4 - Go ahead an call methods from the MBSDK
            // Note: If you get 401 unathorized, are you a LANDesk Administrator?
            string[] configs = sdk.GetClientConfigurations();
            DeviceList list = sdk.ListMachines("");
            string who = sdk.WhoAmI();
        }
    }
}

Have fun LANDesk Admins.

A test of encapsulation security in C#

I am taking a Computer Security course as part of my Masters of Computer Science and a specific question inspired the idea of testing the security of Encapsulation in C#.

I was curious, if exposing an object that is not exposed would be as simple as changing a single bit with a hex editor.

So I created two projects:

A dll that doesn’t expose two objects.

namespace EncapsulatedLibrary
{
    class Class1
    {
        public int i = 27;
    }

    class Class2
    {
        public int i = 29;
    }
}

An executable that references the dll and tries to use objects that are not exposed.

using EncapsulatedLibrary;

namespace TestLink
{
    class TestLinkProgram
    {
        static void Main(string[] args)
        {
            Class1 c1 = new Class1();
            int val1 = c1.i;
            Class2 c2 = new Class2();
            int val2 = c2.i;
        }
    }
}

Ok, now if you compile these, the dll compiles fine, but the exe fails to build.

Now try to use a hex editor to change the compiled version of the dll to expose these objects.

So real quick, I copied the dll and then changed the classes to public and recompiled. Then using a hex editor, HxD, I compared the two files.

Sure enough, on row 00000390, the 13th octet, I changed it from 00 to 01 and now Class1 is public.
On the very next row, 000003A0, the 10th octet, I changed it from 00 to 01 and now Class2 is public.

With this simple hack, I have made two objects public that should not be public. While in this example, this is not malicious, there are ways this could be used maliciously. Imagine if you had functionality limitations on users and they should not have rights to do certain processes but due to exposing a library, they can do these processes.

So now the next question left to be answered is this: What tools exist as controls to prevent such an attack?

How to find the duplicate in an array using Big O of N?

Question

Write an algorithm that finds the duplicate in an array using Big O of N, not Big O of N^2.

Information

The array is an integer array and has a MAX_VALUE items (lets just use 1000 as an example). All integers are between 0 and MAX_VALUE (pretend the input is limited to values between 0 and MAX_VALUE). There is only one duplicate and you are not sure where it is. What is the most efficient way to find it.

    int[] i = new int[1000];

There is one duplicate and it is the worst case duplicate.  You can simulate a worst case duplicate as follows:

    for (int i = 0; i < 999; i++)
    {
        array[i] = i+1;
    }
    array[999] = 999;

So the duplicates are the second to last and the last.

Answer

This is one possible answer that assumes the values are between 0 and MAX_VALUE.

    /// <summary>
    /// Efficient because it has a Big O of n.
    /// </summary>
    public int FindDuplcate(int[] inArray)
    {
        bool[] tmpArray = new bool[1000];
        for (int i = 0; i < inArray.Length; i++)
        {
            if (tmpArray[inArray[i]] == true)
                return i;
            tmpArray[inArray[i]] = true;
        }
        return -1;
    }

Incorrect answers

Here is a little test app with two incorrect answers and two possible correct answer. Feel free to comment with your answers.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace FindDuplicateInArray
{
    class Program
    {
        const int MAX_VALUE = 1000;        

        static void Main(string[] args)
        {
            // Worst case
            int[] array = new int[MAX_VALUE];
            for (int i = 0; i < MAX_VALUE - 1; i++)
            {
                array[i] = i + 1;
            }
            array[MAX_VALUE - 1] = MAX_VALUE - 1;

            // Incorrect answer: Big O of N^2
            //IFindADuplicateInArrays dupFinder1 = new BruteForceDupFinder();
            //int dup = dupFinder1.FindDuplcate(array);

            // Incorrect answer: Big O of N^2
            //IFindADuplicateInArrays dupFinder2 = new LessBruteForceDupFinder();
            //int dup = dupFinder2.FindDuplcate(array);

            // Possible correct answer: Big O of N but with a limitation
            //IFindADuplicateInArrays dupFinder3 = new EfficientDupFinderWithLimitation();
            //int dup = dupFinder3.FindDuplcate(array);

            // Possbile correct answer: Big O of N
            IFindADuplicateInArrays dupFinder3 = new EfficientDupFinder();
            int dup = dupFinder3.FindDuplcate(array);

            Console.WriteLine(dup);
        }

        public interface IFindADuplicateInArrays
        {
            int FindDuplcate(int[] inArray);
        }

        /// <summary>
        /// Incorrect Answer: This is simple N*N alogithm. Big 0 = N^2
        /// </summary>
        public class BruteForceDupFinder : IFindADuplicateInArrays
        {
            #region IFindADuplicateInArrays Members

            public int FindDuplcate(int[] inArray)
            {
                for (int i = 0; i < inArray.Length; i++)
                {
                    for (int j = 0; j < inArray.Length; j++)
                    {
                        if (i != j && inArray[i] == inArray[j])
                            return j;
                    }
                }
                return -1;
            }

            #endregion
        }

        /// <summary>
        /// Incorrect Answer: This is N(N-1)/2 which is N*N/2-n/2 so remove the constants N^2-N.
        /// When there is N^2-N you can keep the N that grows fastest: Big O = N2
        /// But the original alrogithm is less N^2 than just N^2.
        /// </summary>
        public class LessBruteForceDupFinder : IFindADuplicateInArrays
        {
            #region IFindADuplicateInArrays Members

            public int FindDuplcate(int[] inArray)
            {
                for (int i = 0; i < inArray.Length; i++)
                {
                    for (int j = i + 1; j < inArray.Length; j++)
                    {
                        if (inArray[i] == inArray[j])
                            return j;
                    }
                }
                return -1;
            }

            #endregion
        }

        /// <summary>
        /// Possible Answer: Efficient because it has a Big O of n.
        /// Limitation: If an item in the array is greater than the MAX_VALUE,
        ///             an ArrayIndexOutOfBoundsException occurs.
        /// </summary>
        public class EfficientDupFinderWithLimitation : IFindADuplicateInArrays
        {
            #region IFindADuplicateInArrays Members

            public int FindDuplcate(int[] inArray)
            {
                bool[] tmpArray = new bool[1000];
                for (int i = 0; i < inArray.Length; i++)
                {
                    if (tmpArray[inArray[i]] == true)
                        return i;
                    tmpArray[inArray[i]] = true;
                }
                return -1;
            }

            #endregion
        }

        /// <summary>
        /// Possible Answer: Efficient because it has a Big O of n.
        /// </summary>
        public class EfficientDupFinder : IFindADuplicateInArrays
        {
            #region IFindADuplicateInArrays Members
            public int FindDuplcate(int[] inArray)
            {
                Dictionary<int, bool> table = new Dictionary<int, bool>();
                for (int i = 0; i < inArray.Length; i++)
                {
                    if (table.Keys.Contains(inArray[i]))
                        return i;
                    table.Add(inArray[i], true);
                }
                return -1;
            }
            #endregion
        }
    }
}

Run this through Visual Studio’s Performance Analysis tool once for each answer (comment and uncomment). To really see the difference, change MAX_VALUE to 1 million.

WPF MVVM Tutorial

WPF jobs trend up according to Indeed.com

According to Indeed.com the amount of WPF job trends up rapidly.

Since XAML is going to be used in Windows 8 as well, it is not going away any time in the next decade. Also, declarative UI will improve in the future, not disappear. So there is job security in this.

Listing available Properties of an DirectoryEntry object

If you are messing with IIS in C# code, you can do quite a bit if you System.DirectoryServices and the DirectoryEntry object. This can be extended if you know the name of the items in a the DirectoryEntry’s property collection. You can get these as follows:

using System;
using System.Collections.Generic;
using System.DirectoryServices;

namespace FindIISLogWithCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> AvailableProperties = new List<string>();
            DirectoryEntry folderRoot = new DirectoryEntry("IIS://localhost/W3SVC");
            PropertyCollection pc = folderRoot.Properties;
            foreach (PropertyValueCollection p in pc)
            {
                AvailableProperties.Add(p.PropertyName);
            }

            // Sort alphabetically
            AvailableProperties.Sort();
            foreach (String prop in AvailableProperties)
            {
                Console.WriteLine(prop);
            }
        }
    }
}

Of course, different DirectoryEntry objects can have different lists. However, this exact one created the following list on a Windows 2008 R2 64-bit Server with IIS installed and configured.

AccessFlags
AccessSSLFlags
AnonymousUserName
ApplicationDependencies
AppPoolId
AspDiskTemplateCacheDirectory
AuthFlags
DefaultDoc
DirBrowseFlags
DontLog
HttpCustomHeaders
HttpErrors
IIs5IsolationModeEnabled
KeyType
LogFileDirectory
LogPluginClsid
NTAuthenticationProviders
RedirectHeaders
ScriptMaps
SSIExecDisable
SslUseDsMapper
TraceUriPrefix
WebSvcExtRestrictionList

A snippet for Properties in a ViewModel

If you are using MVVM you probably should create a snippet very similar to the following to save time.

C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC#\Snippets\1033\Visual C#\propvm.snippet

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>propvm</Title>
			<Shortcut>propvm</Shortcut>
			<Description>Code snippet for property and backing field for a ViewModel that calls NotifyPropertyChanged.</Description>
			<Author>Jared Barneck</Author>
			<SnippetTypes>
				<SnippetType>Expansion</SnippetType>
			</SnippetTypes>
		</Header>
		<Snippet>
			<Declarations>
				<Literal>
					<ID>type</ID>
					<ToolTip>Property type</ToolTip>
					<Default>int</Default>
				</Literal>
				<Literal>
					<ID>property</ID>
					<ToolTip>Property name</ToolTip>
					<Default>MyProperty</Default>
				</Literal>
			</Declarations>
			<Code Language="csharp"><![CDATA[public $type$ $property$
	{
		get { return _$property$;}
		set
		{
			_$property$ = value;
			NotifyPropertyChanged("$property$");
		}
	} private $type$ _$property$;
	$end$]]>
			</Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>