2012
05.10

This example show how to send object through JSON message and then bind it to class. DefaultModelBinder did not bind abstract class objects (throwing MissingMethodException: Cannot create an abstract class). My solution extends DefaultModelBinder to support abstract classes. It is done by creating object of concrete type and then casting it to abstract class. Concrete type is recognized by obtaining request field named: Type. For example if model type is abstract Content, following JSON request: { Name: ‘Hello World’, Type:’HelloContent’ } will create HelloContent class, assign Name field and cast it to Content class.

The following class is responsible for above behavior.

public class EnhancedDefaultModelBinder : DefaultModelBinder
{
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
        Type type = modelType;
        if (modelType.IsGenericType)
        {
            Type genericTypeDefinition = modelType.GetGenericTypeDefinition();
            if (genericTypeDefinition == typeof(IDictionary))
            {
                type = typeof(Dictionary).MakeGenericType(modelType.GetGenericArguments());
            }
            else if (((genericTypeDefinition == typeof(IEnumerable<>)) || (genericTypeDefinition == typeof(ICollection<>))) || (genericTypeDefinition == typeof(IList<>)))
            {
                type = typeof(List<>).MakeGenericType(modelType.GetGenericArguments());
            }
            return Activator.CreateInstance(type);
        }
        else if(modelType.IsAbstract)
        {
            string concreteTypeName = bindingContext.ModelName + ".Type";
            var concreteTypeResult = bindingContext.ValueProvider.GetValue(concreteTypeName);

            if (concreteTypeResult == null)
                throw new Exception("Concrete type for abstract class not specified");

            type = Assembly.GetExecutingAssembly().GetTypes().SingleOrDefault(t => t.IsSubclassOf(modelType) && t.Name == concreteTypeResult.AttemptedValue);

            if (type == null)
                throw new Exception(String.Format("Concrete model type {0} not found", concreteTypeResult.AttemptedValue));

            var instance = Activator.CreateInstance(type);
            bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => instance, type);
            return instance;
        }
        else
        {
            return Activator.CreateInstance(modelType);
        }
    }
}

In example project is shown how to bind complex models that can contain multiple abstract classes and collection of those objects. The class hierarchy of project is shown below.


Here is project code available for download.

2012
05.10

My answer is Singular. Now you may think it is werid to name a collection in singular way.  This looks odd but it really help when you use ORM such as Entity Framework to map objects.

2012
03.02

Error: Visual Studio don’t recognize types. The syntax coloring is not working. Can’t execute Go To Definition.
Fix: Build -> Clean Solution

2012
02.21

For fast coding and clarity purposes C# contains some helpers. This example introduces four ways to perform subscribe to events: by adding new delegate pointing to method, doing the same but with Method group, by creating anonymous delegate or with lambda expressions.

class MessageService
{
    public event EventHandler ReceivedMessage;

    void OnReceivedMessage()
    {
        if (ReceivedMessage != null)
            ReceivedMessage(this, EventArgs.Empty);
    }

    public void Receive()
    {
        OnReceivedMessage();
    }
}

class Program
{
    private static MessageService service = new MessageService();

    static void Main(string[] args)
    {
        service.ReceivedMessage += new EventHandler(service_ReceivedMessage);
        service.ReceivedMessage += service_ReceivedMessage2;
        service.ReceivedMessage += delegate(object s, EventArgs e)
        {
            Console.WriteLine("[Delegate] Received");
        };
        service.ReceivedMessage += (s, e) => Console.WriteLine("[Lambda] Received");

        Console.WriteLine("Press any key to send message!");
        Console.ReadKey();

        service.Receive();

        Console.ReadKey();
    }

    static void service_ReceivedMessage(object sender, EventArgs e)
    {
        Console.WriteLine("[Method] Received");
    }

    static void service_ReceivedMessage2(object sender, EventArgs e)
    {
        Console.WriteLine("[Method group] Received");
    }
}
Press any key to send message!
[Method] Received
[Method group] Received
[Delegate] Received
[Lambda] Received
2012
01.26

To return IEnumerable you can do it without making any class. Just yield return a value. This way you do not even have to create any class.

public static IEnumerable<string> GetItems()
{
	for(int i=0; i<10; i++)
		yield return "Item "+i;
}
2012
01.17

In many languages Delegates (pointers to function) can only point to single method. In C# we can make delegate to point multiple methods. When invoking such delegete, all metods that are assigned will be executed.

using System;

namespace Trace
{
    static class Foo
    {
        public static void Trace1(string a)
        {
            Console.WriteLine(a + "1");
        }
        public static void Trace2(string a)
        {
            Console.WriteLine(a + "2");
        }
        public static void Trace3(string a)
        {
            Console.WriteLine(a + "3");
        }
        public static void Trace4(string a)
        {
            Console.WriteLine(a + "4");
        }
    }

    public class Program
    {
        delegate void Write(string message);

        static void Main(string[] args)
        {
            Write w = new Write(Foo.Trace1);
            w += Foo.Trace1;
            w += Foo.Trace2;
            w += Foo.Trace2;
            w += Foo.Trace4;
            w += Foo.Trace3;
            w("a");

            Console.ReadKey();
        }
    }
}

 

a1
a1
a2
a2
a4
a3
2011
10.23

Example shows how to implement extension methods, and how to make those flexible to can accept any Action delegate.

using System;
using System.Net;
using System.Diagnostics;

namespace ExtensionMethods
{
    class Program
    {
        static void Main(string[] args)
        {
            Action download = () => new WebClient().DownloadString("http://microsoft.com/");
            var time1 = download.GetExecutionTime();
            Console.WriteLine(time1.Milliseconds);

            Action<string> downloadWithOneParam = (url) => new WebClient().DownloadString(url);
            var time2 = downloadWithOneParam.Partial<string>("http://micrisoft.com/").GetExecutionTime();
            Console.WriteLine(time2.Milliseconds);

            Console.ReadKey();
        }
    }

    static class Extensions
    {
        public static TimeSpan GetExecutionTime(this Action action)
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();

            Stopwatch watch = new Stopwatch();
            watch.Start();
            action();
            watch.Stop();
            return watch.Elapsed;
        }

        public static Action Partial<TParam1>(this Action<TParam1> func, TParam1 param)
        {
            return () => func(param);
        }
    }
}

2011
10.09

Silverlight canvas events like:

  • MouseMove
  • MouseLeftButtonClick
  • etc.

not working, or working only on others elements?
There is a quick fix to this problem, just set the Canvas.Background to some value. For example it could be transparent value like: #00000000.

2011
10.09

WCF service application using PollingDuplexHttpBinding, and Silverlight duplex client on .Net 4.0 C#. Project consist also ClientAccessPolicy.xml propagation.

PollingDuplex

2011
06.20

Authentication

Enter login: MaciejLisCK
Enter password: **********

Authorization

MaciejLisCK not authorized to delete database
MaciejLisCK authorized to post a message