C# – Use LINQ on .net framework 2.0

When I read a thread on mycsharp.de, I discovered a library which allow us to use LINQ in any application written on .Net Framework 2.0. It’s really great if we have this feature without installing mega framework 3.0. The library can be downloaded from google code http://code.google.com/p/linqbridge/downloads/list . You can download online .cs file or a .dll file as you link but I prefer using a .cs because I don’t have to merge .dll file to exe file after compilation. But how can LINQ work without .Net Framework 3.0. Does it depend on .Net Framework 3.0? The answer is NO. Let’s examine an example of LINQ with C# 3.0

Continue reading C# – Use LINQ on .net framework 2.0

C# – Append byte array to byte array

During my development a tool to download music file through MMS protocol I had to convert a packet to a byte array and send it through socket to the server. Each packet has its own format and therefore the simple way is to implement each class for each packet and insert a function GetBytes() to each class to convert all fields in packet into byte array. The problem is that the fields have various format and length so it issues a new task how to convert them to byte array and append each other.
To convert the fields to byte array is pretty simple, we just call the static GetBytes() functions of BitConverter class with appropriate arguments as example below

public static byte[] Append(byte rep, byte version, byte versionMinor, byte padding, uint sessionId, uint messageLength, int seal, uint chunkCount, short seq, short MBZ, double timeSent, byte[] MMSmessage)
{
	ByteAppend<byte> fcTemp = new ByteAppend<byte>();
	fcTemp.Add(new byte[] { rep });
	fcTemp.Add(new byte[] { version });
	fcTemp.Add(new byte[] { versionMinor });
	fcTemp.Add(new byte[] { padding });
	fcTemp.Add(BitConverter.GetBytes(sessionId));
	fcTemp.Add(BitConverter.GetBytes(messageLength));
	fcTemp.Add(BitConverter.GetBytes(seal));
	fcTemp.Add(BitConverter.GetBytes(chunkCount));
	fcTemp.Add(BitConverter.GetBytes(seq));
	fcTemp.Add(BitConverter.GetBytes(MBZ));
	fcTemp.Add(BitConverter.GetBytes(timeSent));
	fcTemp.Add(MMSmessage);
	return fcTemp.ToArray();
}

You can see in the code snippet above I convert all native type to byte array easily. However to append them we need to write our own one class so that we can hang each byte array directly behind the previous one.

class ByteAppend<T> : IEnumerable<T>
{
	LinkedList<T[]> m_lstItems = new LinkedList<T[]>();
	int m_nCount;

	public int Count
	{
		get
		{
			return m_nCount;
		}
	}

	public T[] ToArray()
	{
		T[] aTemp = new T[Count];
		for (int nIndex = 0; nIndex < Count; nIndex++)
		{
			aTemp[nIndex] = this[nIndex];
		}
		return aTemp;     
	}

	public void Add(T[] aItems)
	{
		if (aItems == null)
			return;
		if (aItems.Length == 0)
			return;

		m_lstItems.AddLast(aItems);
		m_nCount += aItems.Length;
	}

	private T[] GetItemIndex(int nRealIndex, out int nOffset)
	{
		nOffset = 0; 
		int nCurrentStart = 0; 

		foreach (T[] items in m_lstItems)
		{
			nCurrentStart += items.Length;
			if (nCurrentStart > nRealIndex)
				return items;
			nOffset = nCurrentStart;
		}
		return null;
	}

	public T this[int nIndex]
	{
		get
		{
			int nOffset;
			T[] i = GetItemIndex(nIndex, out nOffset);
			return i[nIndex - nOffset];
		}
		set
		{
			int nOffset;
			T[] i = GetItemIndex(nIndex, out nOffset);
			i[nIndex - nOffset] = value;
		}
	}

	#region IEnumerable<T> Members

	public IEnumerator<T> GetEnumerator()
	{
		foreach (T[] items in m_lstItems)
			foreach (T item in items)
				yield return item;
	}

	#endregion

	#region IEnumerable Members

	System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
	{
		return GetEnumerator();
	}

	#endregion
}

After append them together, we just need to call ToArray() to get the complete byte array back.

C# – Enum of string

When I am building a class for associating my program for a specific file extension, I remembered to an old solution for building an enumeration with type of string. To declare an enumeration in C#, we use code below

enum NameOfEnumeration
{
	Enum01,
	Enum02,
	...
	EnumN
}

The enum keyword is used to declare an enumeration, a distinct type consisting of a set of named constants called the enumerator list. Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. So enum supports only byte, sbyte, short, ushort, int, uint, long, or ulong. What would we do if we want to have an enumeration with string? The following example code below will illustrate how an enumeration of string can be built. However it doesn’t work exactly as we expect , for example, it won’t return a string we cast its value but we need to call a method from a helper class to get it’s string. The string of enum value will be stored through DescriptionAttribute which specifies a description for a property or event. Then when we want to get string, we just access this description and fetch value back. For example, we have a Bookstore enum

enum BookStore
{
	[DescriptionAttribute("www.amazon.com")]
	AMAZON,
	[DescriptionAttribute("www.barnesandnoble.com")]
	BARNESNOBLE,
	[DescriptionAttribute("www.abebooks.com")]
	ABEBOOKS,
	[DescriptionAttribute("www.borders.com")]
	BORDERS,
	[DescriptionAttribute("www.powells.com")]
	POWELLBOOKS,
	[DescriptionAttribute("www.booksamillion.com")]
	BOOKSAMILLION
}

You can see that there is an url string for each enum value. We would like to use these string values in our code, but we can not use them as enum value. So declare these strings in description attribute and get them later through these two static functions

class EnumString
{
	public static string GetString(Enum enValue)
	{
		FieldInfo fiInfo = enValue.GetType().GetField(enValue.ToString());
		DescriptionAttribute[] daArray = fiInfo.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
		return daArray.Length > 0 ? daArray[0].Description : "";
	}

	public static object GetValue(string strDescription, Type tyEnum)
	{
		string[] arrNames = Enum.GetNames(tyEnum);
		foreach (string strTemp in arrNames)
		{
			if (GetString(Enum.Parse(tyEnum,strTemp) as Enum).Equals(strDescription)) return Enum.Parse(tyEnum,strTemp);
		}
		throw new Exception("No value found for this description");
	}
}

The GetString function receives an enum value as its argument and gives string value back. On the contrary, the GetValue function receives a string value and enum type to specify to which enum value the string belongs to.

 static void Main(string[] args)
{
	Console.WriteLine(EnumString.GetString(BookStore.ABEBOOKS));
	Console.WriteLine(EnumString.GetValue("www.amazon.com", typeof(BookStore)).ToString());
	Console.ReadLine();
}

New Year Eve 2010 Munich Germany

On 31.12.2009 I went to the restaurant of my cousin to help him because his restaurant in this day was full of customers. I was there from 17h30 to 23h45 and really tired after hard work of a waiter. This video below is the scene near by the restaurant at 0h on 01.01.2010. The Germans went down to the street and fire fireworks. It must be more beautiful if I am in center of Munich (Marienplatz) or near by where I live (Nymphenburge Palace). But anyway I can not travel a long way from the restaurant to center in 15 minutes. Therefore I could only take the video near by the restaurant. In the video you’ll see the restaurant is “Chinese Fuh Guei Restaurant” but please don’t think I am a Chinese. I am not Chinese. And Happy New Year “und guten Rutsch in neues Jahr”.

Happy New Year

An old year has gone, a new year is standing in front of the door. I wish all of you a happy, lucky new year. As Edith Lovejoy Pierce says “We will open the book. Its pages are blank. We are going to put words on them ourselves. The book is called “Opportunity” and its first chapter is New Year’s Day”.