Oct 4
IEnumerable versus implicit conversion
icon1 Mikkel Meyer Andersen | icon4 October 4, 2007 at 20:02 (UTC) | icon3 No Comments »
icon3

Maybe it’s really just a sick thought, but who cares?! What is actually going to happen if one is enumerating an object which implements both an enumerator-interface and an implicit conversion to a type also implementing an enumerator-interface? At this time I actually know the answer (for Mono at least), but if we should reason about it, it’s almost given that it should use the direct implementation of the enumarator-interface and in that way avoid an implicit conversion.

Now it’s time to shower this post with some code (inspired by [1]):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
using System.Collections;
using System.Collections.Generic;
 
namespace experiments
{
	class MainClass
	{
		public static void Main(string[] args)
		{
			C<int> c = new C<int>(1, 2, 3, 4, 5);
 
			Console.WriteLine("IEnumerable<T>:");
			foreach (int e in c)
			{				
				Console.WriteLine(e);
			}
			Console.WriteLine();
 
			Console.WriteLine("Implicit conversion to List<T>:");			
			foreach (int e in (List<int>)c)
			{
				Console.WriteLine(e);
			}
			Console.WriteLine();
 
			Console.WriteLine("Implicit conversion to T[]:");
			foreach (int e in (int[])c)
			{
				Console.WriteLine(e);
			}
		}
	}	
 
	class C<T> : IEnumerable<T> 		
	{		
		protected List<T> list;
 
		public C(params T[] elements)
		{		
			this.list = new List<T>();
 
			for (int i = 0; i < elements.Length; ++i)
			{
				this.list.Add(elements[i]);
			}
		}
 
		public IEnumerator<T> GetEnumerator() 
		{
			for (int i = this.list.Count - 1; i >= 0; --i)
			{
				yield return this.list[i];
			}
		}
 
		IEnumerator IEnumerable.GetEnumerator() 
		{
			return GetEnumerator();
		}
 
		public static implicit operator List<T>(C<T> c)
		{
			return new List<T>(c.list);
		}		
 
		public static implicit operator T[](C<T> c)
		{
			T[] arr = new T[c.list.Count];			
 
			if (c.list.Count > 0)
			{
				int j = 0;
 
				for (int i = c.list.Count / 2; i >= 0; --i)
				{
					arr[j++] = c.list[i];
				}
 
				for (int i = (c.list.Count / 2) + 1; i < c.list.Count; ++i)
				{
					arr[j++] = c.list[i];
				}
			}
 
			return arr;
		}		
	}
}

And the result:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
IEnumerable<T>:
5
4
3
2
1
 
Implicit conversion to List<T>:
1
2
3
4
5
 
Implicit conversion to T[]:
3
2
1
4
5

..gets as expected – still a interesting test (in my opinion), though.

[1]: “C# Precisely” by Peter Sestoft and Henrik I. Hansen

Oct 4

The other day I had to use a web service from a C# 2.0 application. No problem – the .NET 2.0-frameworks provides tons of functionality. To jump into the exciting issue, I’d generated the proxy classes using WSDL, and started communicating with the WS. When no errors occured everything worked fine, but if something went wrong I just got an standard non-informative SoapHeaderException with no details whatsoever. Certainly less useful than a wet newspaper.

The problem was that a SOAP-fault (this name avoids mixing up the concepts of SOAP- and run-time exceptions) occurred, but the actual description of the error in the SOAP-response was not deserialized properly and was therefore not included in the run-time exception. The SOAP-response looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<soapenv:envelope
	xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
	xmlns="http://tews6/wsdl"
	xmlns:xsd="http://www.w3.org/2001/XMLSchema"
	xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://schemas.xmlsoap.org/soap/envelope/ http://schemas.xmlsoap.org/soap/envelope/">
	<soapenv:body>
		<soapenv:fault>
			<faultcode>soapenv:Client</faultcode>
			<faultstring>Error performing operation.</faultstring>
			<detail>
				<imsexception version="6.0">
					<exception>
						<name>CheckForDuplicates</name>
						<code>500</code>
						<description><!--[CDATA[User id johndoe is a duplicate. ProcessStep::BLTHValidate TabName:  ERRORLEVEL::Error]]--></description>
					</exception>
				</imsexception>
			</detail>
		</soapenv:fault>
	</soapenv:body>
</soapenv:envelope>

I read about this several places, and all these said that it was just the way .NET worked in that area. Sounds a bit odd, but nevertheless I instead started to figure out how to solve it.

The solution is actually quite simple, but it took some time to figure out how it should be done. It consists of three parts:

  • A custom Exception so that it can be caught separately
  • A SoapExtension that handled serialization and deserialization of the SOAP-messages and in that way were possible to intervene if a SOAP-fault occurred and throw the custom exception instead of a generic SoapException
  • A SoapExtensionAttribute used to mark the web methods should use the SOAP-extension

It actually works very well! The only drawback is that every web method has to be marked with the attribute – but just another opportunity to celebrate sed!

Jul 4
Not null or not null or…
icon1 Mikkel Meyer Andersen | icon4 July 4, 2007 at 22:13 (UTC) | icon3 No Comments »
icon3

Excuse me for publishing such a shot post (it’s now the last one, so please don’t feel too annoyed), but this little nice thing in C# can be nice to know:

1
2
3
string a = null;
string b = "hello";
string c = a ?? b; // c equals "hello"

In other words, it returns the first argument that is not null.

May 5
Thread safe queue
icon1 Mikkel Meyer Andersen | icon4 May 5, 2007 at 18:21 (UTC) | icon3 No Comments »
icon3

It’s often quite nice to have a blocking queue (thread safe queue) – how many times haven’t you used the producer/consumer-pattern? Because we’re lazy we make one class we can use every time (long live recycling) instead of making that blocking mechanism implicit in out program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System;
using System.Threading;
using System.Collections.Generic;
 
namespace Scienco
{
    class ThreadSafeQueue<T> 
        where T : class
    {
        private Queue<T> mQueue; 
        private Semaphore mSemaphore;
 
        public ThreadSafeQueue()
        {
            mQueue = new Queue<T>();
            mSemaphore = new Semaphore(0, int.MaxValue);
        }
 
        public void Enqueue(T element)
        {
            if (element == null)
            {
                throw new ArgumentNullException();
            }
 
            lock (this.mQueue) 
            {
                this.mQueue.Enqueue(element);
            }
 
            this.mSemaphore.Release();
        }
 
        public T Dequeue()
        {
            this.mSemaphore.WaitOne();
 
            lock (this.mQueue)
            {
                if (this.mQueue.Count > 0)
                {
                    return this.mQueue.Dequeue();
                }
 
                else
                {
                    return null;
                }
            }
        }
    }
}

You probably don’t like my coding-style in some way ({, mQueue or whatever) – please feel free to follow whatever guidelines rocking your world.