Archiv der Kategorie ‘Programming‘

Part II: Mimic SynchronizationContext behaviour on .NET CF

Sonntag, den 15. Februar 2009

I just posted the second part of the article Part I: Mimic SynchronizationContext behaviour on .NET CF on planetgeek.ch! On the article I try to show how the basic behavior of the SynchronizationContext can be achieved on the .NET compact framework platform. Please refer to the article under:

http://www.planetgeek.ch/2009/02/15/part-ii-mimic-synchronizationcontext-behaviour-on-net-cf/

Part I: Mimic SynchronizationContext behaviour on .NET CF

Sonntag, den 8. Februar 2009

Before I got into the details of the problem I want to briefly describe what the SynchronizationContext class really does and what it’s main purpose really is in the first part of the article. From that perspective I’m going to show how the basic functionality of the SynchronizationContext class can be implemented for the .NET compact framework in the second part of the article..

The msdn library documentation states:

Provides the basic functionality for propagating a synchronization context in various synchronization models.

I must admit the first time when I read this definition I didn’t really get the key point behind the SynchronizationContext class. Detailed look into the implementation of SynchronizationContext and its base classes provided me the following information:

The SynchronizationContext class is a class belonging to the System.Threading namespace. The SynchronizationContext provides a model to make the communication between threads easier and more robust especially if multiple threading contexts/apartments such as “UI threading context” etc. are present.

To get a deeper understanding of the definition above I want to give you a short example. Imagine if you have a separate thread performing an intense calculation such as calculating the n-th Fibonacci number. When the separate thread has finished its long running operation you want to display the n-th Fibonacci number on a user interface. Normally (without using the SynchronizationContext class) you would need to do the following (or at least something similar):

private delegate void FibonacciResultDelegate(long fibonacciResult);
 
private void MethodCalledByTheFibonacciThread(long fibonacciNumber)
{
   if( fibonacciResultTextBox.InvokeRequired)
   {
      FibonacciResultDelegate fibonacciDelegate =
         MethodCalledByTheFibonacciThread;
      fibonacciDelegate.Invoke(this, new object[] { fibonacciNumber });
      return;
   }
   fibonacciResultTextBox.Text = fibonacciNumber.ToString();
}


With the SynchronizationContext class we can invoke delegates in the context of a different thread. For the example above we could do the following:

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
public class FibonacciPresenter
    {
        private readonly Thread workerThread;
 
        private readonly SynchronizationContext context;
 
        private readonly IFibonacciView fibonacciView;
 
        public FibonacciWorker(IFibonacciView view)
        {
            fibonacciView = view;
 
            context = SynchronizationContext.Current;
 
            workerThread = new Thread(new ThreadStart(FibonacciCalc));
 
            workerThread.Start();
        }
 
        private void FibonacciCalc()
        {
            long result = CalculateFibonacciNumber( ... );
            context.Post(new SendOrPostCallback(delegate(object state)
            {
               fibonacciView.DisplayResult(result);
            }), null);
        }
 
        // details omitted...
    }

In code line 13 we can see how the SynchronizationContext is retrieved. The SynchronizationContex.Current property points to the SynchronizationContext of the thread where the FibonacciWorker was created (in my example the FibonacciWorker would be created in a control). Then the FibonacciCalc method can post (asynchronous) or send (synchronous) a SendOrPostCallback delegate containing the “job” which needs to be marshaled over the SynchronizationContext. Therefore the line fibonacciView.DisplayResult(result) would be invoked on the UI thread which allows us to remove the “invoke required” code parts and directly set the fibonacci calculation result to the textbox text property.

We can briefly summarize that the purpose of the SynchronizationContext is to post (asynchronous) or send (synchronous) SendOrPostCallback delegates in the correct threading context which simplifies marshaling.

Delegate.DynamicInvoke for .NET Compact Framework

Sonntag, den 18. Januar 2009

As you might already know I’m a certified windows mobile application developer. My speciality is hybrid application development for applications which target both the full .NET framework platform and also the mobile platform. Of course nobody wants to write the same code for each platform again so you have to come up with some tricks and solutions to overcome some limitations on the compact framework.

One such limitation is the missing Delegate.DynamicInvoke method. The Delegate.DynamicInvoke method allows to dynamically invoke delegates late-bound. That means normally when you are invoking a method via a delegate you actually need to have knowledge about the target type where the delegate gets executed. With Delegate.DynamicInvoke this is not longer necessary. The beauty of this is, that you can have base code like the following:

// Elsewhere
RegisterDelegate(SomeClass.SomeMethod);
RegisterDelegate(SomeOtherClass.SomeOtherMethod);
FireForAllWith(1, 2, 3, 4);
 
// Code in some utility
public void FireForAllWith(params object[] args)
{
   someGenericCollection.ForEach(dlg => dlg.DynamicInvoke(args));
}
public void RegisterDelegate(Delegate dlg)
{
   someGenericCollection.Add(dlg);
}

But if you try to use Delegate.DynamicInvoke in the compact framework your infrastructure code will not compile because for some obscure reasons microsoft decided not to implement Delegate.DynamicInvoke for .NET compact framework. Here is my solution to this problem:

I created an extension method for the delegate class with the name DynamicInvoke. This extension method uses a small trick to implement the DynamicInvoke behaviour of the full framework platform.

    public static class DelegateExtensions
    {
        public static object DynamicInvoke(this Delegate dlg, params object[] args)
        {
            return dlg.Method.Invoke(dlg.Target, BindingFlags.Default, null, args, null);
        }
    }

As you can see I’m using the delegates method property which returns a MethodInfo object. On the MethodInfo I’m able to call Invoke and pass the arguments to the bound method. But the problem here is that Invoke requires a target where the method gets executed. This is where the delegates target property comes into play. That’s the whole magic and you’re able to dynamically invoke late bound methods via Delegate.DynamicInvoke.

Download DelegateExtensions for the source code.

Linq to SQL is announced dead…

Mittwoch, den 3. Dezember 2008

Now it’s almost official:

[...]

We’re making significant investments in the Entity Framework such that as of .NET 4.0 the Entity Framework will be our recommended data access solution for LINQ to relational scenarios.  We are listening to customers regarding LINQ to SQL and will continue to evolve the product based on feedback we receive from the community as well.

Tim Mallalieu
Program Manager, LINQ to SQL and Entity Framework

http://blogs.msdn.com/adonet/archive/2008/10/29/update-on-linq-to-sql-and-linq-to-entities-roadmap.aspx

ConfigurationSectionHandler the easy way

Montag, den 1. Dezember 2008

Have you ever had the need to develop your own configuration section handler for application configuration files (app.config) in C#. Everybody that has been doing this lately knows how tedious this can be. But there is a quick and easy way to implement simple configuration section handlers in C#. This post shows you how…

Sample

In the sample we are going to implement a simple configuration section handler which will input an enumeration and a simple string constant. I quickly define the interface:

 

1
2
3
4
5
6
7
public interface ITracelightConfigurationSectionHandler : 
IConfigurationSectionHandler
   {
      LanguageEnumeration Language { get; }
 
      string SomeInput { get; }
   }

And the enumeration. Now here comes the first trick into the play. We are going to define our enumeration as a DataContract with the DataContractAttribute from the System.Runtime.Serialization namespace. Every enumeration member that we want to be able to serialize must be marked with the EnumMemberAttribute. This allows us later to transparently deserialize the enumeration from the application configuration file.

1
2
3
4
5
6
7
8
9
using System.Runtime.Serialization;
 
[DataContract]
public enum LanguageEnumeration {
   [EnumMember]
   German,
   [EnumMember]
   English,
}

Next we need the concrete class which implements our configuration section handler interface. The class itself are we going to mark as DataContract with the DataContractAttribute. Important here is the Namspace property in the DataContractAttribute must be set to “” (see Line 7). In the Create Method from the IConfigurationSectionHandler interface we are going to use the DataContractSerializer and instantiate it with our concrete class (which implements the ITracelightConfigurationSectionHandler interface). In Line 19 we specify that we want to read the object out of the serializer and must also specify false as second parameter (this surpresses name checking while deserialization). Then we can read the properties out of the configSection instance. Set it on the properties on the instance and return a reference to ourself (this). And we are done!

You only have to remember to set the DataMemberAttribute on every property you want to serialize or deserialize. With the datamember property you can also define how the name looks like in the configuration. If you don’t define a name, the configuration file section must be exactly named as the property.

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
...
    using System.Configuration;
    using System.Runtime.Serialization;
    using System.Xml;
...
 
[DataContract(Namespace = "")]
public class TracelightConfigurationSectionHandler :
ITracelightConfigurationSectionHandler
   {
         // From IConfigurationSectionHandler
         public object Create(object parent, object configContext, XmlNode section)
        {
            var xs = new DataContractSerializer(typeof(TracelightConfigurationSectionHandler ));
 
            XmlNodeReader xnr = new XmlNodeReader(section);
            try
            {
                var configSection = xs.ReadObject(xnr, false) as TracelightConfigurationSectionHandler;
 
                if (configSection != null)
                {
                    Language = configSection.Language;
                    SomeInput= configSection.SomeInput;
                }
 
                return this;
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                Exception iex = ex.InnerException;
                while (iex != null)
                {
                    s += "; " + iex.Message;
                    iex = iex.InnerException;
                }
 
                throw new ConfigurationErrorsException(
                    "Unable to deserialize an object of type \'" + GetType().FullName +
                    "\' from  the <" + section.Name + "> configuration section: " +
                    s,
                    ex,
                    section);
            }
 
 
 
 
        }
 
        // Automatic property for the language
        [DataMember(Name = "language", Order = 1)]
        public LanguageEnumeration Language 
        {
            get; private set;
        }
 
        // Automatic property for the input, which can be omitted.
        [DataMember(Name = "input", Order = 2, IsRequired = false)]
        public string SomeInput
        {
            get; private set;
        }
 
   }

And how looks the App.config file?

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="tracelightsection" type="Fully.Qualified.Namespace.TracelightConfigurationSectionHandler, MyAssemblyNameWithoutDllExtension"/>
  </configSections>
  <tracelightsection>
    <language>German</language>
    <input>SomeTextualInput</title>
  </tracelightsection>
</configuration>

And how can the data be read from the configuration file? That’s pretty easy…

var configSection = (ITracelightConfigurationSectionHandler)ConfigurationManager.GetSection("tracelightsection");

This works even with complex collections. All you need to now is how to handle the data with the DataContractSerializer. But this is fearly simple to learn.

Remarks:
When you see strange behaviour such as the data is not deserialized althoug set in the configuration file you need to specify the order property (especially if you are using non required properties or default values with EmitDefaultValue…).

Interesting thoughts about static methods on interfaces

Sonntag, den 30. November 2008

Jon Sket is arguing on his blog about having static methods in interfaces. I think his article is really good and worth reading. What do you think about this topic?

http://msmvps.com/blogs/jon_skeet/archive/2008/08/29/lessons-learned-from-protocol-buffers-part-4-static-interfaces.aspx

Extension Methoden unter Compact Framework 2.0

Sonntag, den 23. November 2008

Interessanter Artikel:

http://www.simonrhart.com/2008/11/extension-method-support-in-compact.html

Have fun

Vernichtende Aussage über Entwickler

Freitag, den 7. November 2008

Und leider könnte er recht haben…

http://blog.opennetcf.com/ctacke/PermaLink,guid,38c27aaf-38b7-4e48-8dac-929a523f9d25.aspx

Die Zukunft von C#

Donnerstag, den 6. November 2008

Ich muss sagen ich war immer etwas skeptisch über die Entwicklung von C# in Hinblick auf die Dynamic Language Runtime. Anders Hejlsberg zeigt aber gerade im Hinblick auf COM Interoperabilität und zum Beispiel die Integration von Javascript in C# Code die wirklichen Vorzüge der dynamischen Aspekte von C# 4.0. Ich kann nur sagen: That rocks!

Aber glatt umgehauen hat mich der Ausblick auf C# 5.0. Dort heisst das grosse Paradigma Compiler as a Service. Bis anhin war der C# Compiler in C++ geschrieben. Microsoft hat sich nun entschieden den Compiler völlig in Managed Code zu entwickeln. Dies bedeutet, dass es in Zukunft eine Compilerklasse geben wird, deren man zum Beispiel einfach C# Code als String übergeben kann der dann zur Laufzeit kompiliert und evaluiert wird. Anders zeigt dies mit einer ultimativen Konsolenapplikation in deren man Live Code eintippen kann der dann ausgeführt wird. So instanziert er Live direkt in der Konsole ein Windows Form und fügt Elemente drauf etc. Einfach krass!

Überzeugt euch selbst. Das Video ist etwas lang aber unglaublich spannend und gut erklärt:

http://channel9.msdn.com/pdc2008/TL16/

Wie wurden einige der Probleme gelöst

http://channel9.msdn.com/shows/Going+Deep/Inside-C-40-dynamic-type-optional-parameters-more-COM-friendly/

und das Design Team…

http://channel9.msdn.com/posts/Charles/C-40-Meet-the-Design-Team/

Cast<> und OfType<> Unterschied

Montag, den 3. November 2008

LINQ bietet extra für den Umgang mit nicht generischen Collections die beiden Extensionmethoden Cast<> und OfType<>. Mit denen ist es möglich den Inhalt einer nicht generischen Collection wie zum Beispiel ArrayList umzuwandeln. Nehmen wir folgendes Beispiel:

public class Person {   
   public string Surname  { get; set; }
   public string LastName { get; set; }
}
ArrayList list = new ArrayList {  
   { new Person { Surname = "Alfons", LastName = "TheFirst" },   
   { new Person { Surname = "Alfons", LastName = "TheSecond" }
};

Wie ihr sicherlich wisst bekommt man beim iterieren durch die ArrayList wie oben aufgezeigt immer eine Referenz auf ein System.Object. Mit den beiden LINQ Operatoren Cast<> und OfType<> kann man nun die Objektreferenzen in die konkrete Klasse Person “casten” und bekommt bei einem LINQ Query immer ein IEnumerable<Person> zurück. Dies würde folgendermassen aussehen:

// Query syntax
var persons = (from p in list.Cast<Person>()
               select p where p.LastName == "TheSecond");
// Method chaining
var persons = list.Cast<Person>().
                        Where(p => p.LastName == "TheSecond");

Doch was ist nun der Unterschied zwischen den beiden Operatoren? Der Unterschied ist eigentlich schnell erklärt. Der Cast<> Operator versucht jedes Element in der Collection zum entsprechenden Typen zu Casten. Ist der Cast nicht erfolgreich so wird eine Exception geworfen und die Ausführung des Queries beendet. Mit dem OfType<> Operator wird versucht das Element zu Casten und wenn es nicht erfolgreich ist, wird einfach das Element in der Collection ausgelassen.

Dies ist vor allem nützlich, da man bei nicht generischen Collections nicht garantieren kann, dass immer die gleichen Elemente in die Colllection abgefüllt werden. So wäre es durchaus zulässig, dass jemand in der obigen Arraylist noch

list.Add("Ätschbätsch");

hinzufügt. Nähme man dann den Cast<> Operator so wurde die Ausführung des Queries scheitern. Bei OfType<> würde das Element “Ätschbätsch” einfach nicht berücksichtigt.