WCF callback deadlock–solution inside

by tim 31. May 2011 12:23

Past 2 days I was having issues with a WCF service of mine apparently causing a deadlock.

I was unable to find a working solution, until I hit this blog post

=> http://frosen.wordpress.com/2011/02/12/wcf-duplex-service-deadlock/

I did as suggested and added the following attribute to my callback class:

[CallbackBehavior(UseSynchronizationContext = false)]

And… The issue was resolved! Smile

Tags:

Aspects and on-hover descriptions

by tim 22. April 2011 00:14

I have found a way to add ‘descriptions’ to aspects, so that (after compilation) you hover on an aspect target, it’ll show custom messages, underneath the original ones.

Look at the screenshot to see it in action.

Example usage (at compile time validate of the aspect)

PostSharpDescription.Add<SomeTypeAspect>("All your types are belong to us", type);
PostSharpDescription.Add<SomeTypeAspect>("Last compile time: " + DateTime.Now, type);

If you’re interested in trying it out, contact me @ the PostSharp support forum or reply on my topic there => http://www.sharpcrafters.com/forum/Topic6365-19-1.aspx#bm6400

Enjoy!

Tags: ,

Coding

[WinForms] EventAggregator / ThreadOption.UIThread

by tim 31. March 2011 11:02

We usually use Prism / Unity / WPF at work, but for a WCF service that I’m working on currently, I wanted to have a quick ‘n dirty console written using WinForms.

I figured I could still use the EventAggregator exposed by my service to listen for events, and yes: it still works!

But…

I noticed that when I used ThreadOption.UIThread when subscribing an event, that it was never actually called when the event was published. So I did not have an easy way to manipulate UI controls.

Using Reflector, I digged around, and found that the solution was very simple : I just had to put this inside my Main() entrypoint:

Before any code:

var app = new System.Windows.Application();

At the end:

app.Shutdown(0); // 0 being the ‘exit code’

And voila: working event aggregator that can dispatch events to the WinForms UI thread!

How?

When you create a new System.Windows.Application instance, it stores the reference in a static, that is eventually used to dispatch events on the UI thread.

If you do no create a new System.Windows.Application instance, the event callback will just be swallowed, as Application.Current (a public static) will be null.

Tags: , , , ,

Coding

Async Aspect

by tim 24. March 2011 12:15

I wanted to make it easier to call methods in an async way, while still having some control on how it should run.

Introducing: The Async aspect, using the power of PostSharp.

Attach this to a method (returning a ‘void’) and every call will be ran inside another thread.

It has the following options:

  • Pooled
  • Background
  • Priority 
  • Name
  • DropExceptions

Read the comments for an explanation of these options.

    /// 
    /// Calls to Async marked methods, will be enqueued in the ThreadPool and will be ran
    /// in an async matter.
    /// 
    /// Can only be applied to methods that return a 'void' but not on constructors.
    /// 
    [Serializable]
    public sealed class AsyncAttribute : MethodInterceptionAspect
    {
        /// 
        /// When Pooled is set to false, the method will invoked in a seperate Thread, instead of being enqueued on the ThreadPool (default: false)
        /// 
        public bool Pooled = true;

        /// 
        /// When true, it will run the thread as a background thread (default: true)
        /// 
        public bool Background = true;

        /// 
        /// The priority to run the thread as (default: ThreadPriority.Normal)
        /// 
        public ThreadPriority Priority { get; set; }

		/// 
		/// When true, it will handle all exceptions (default: false)
		/// 
		public bool DropExceptions { get; set; }

    	public string Name = "Async Thread";

        /// 
        /// Called when invoking the marked method
        /// 
        public override void OnInvoke(MethodInterceptionArgs args)
        {
            // when not Pooled, make a seperate thread and launch it right away
            if (!Pooled)
            {
                var dedicatedThread = new Thread(
					() =>
						{
							try
							{
								args.Proceed();
							}catch
							{
								if (!DropExceptions)
									throw;
							}
						}) 
						{IsBackground = Background, Priority = Priority, Name = Name};
                dedicatedThread.Start();

                return;
            }

            // when not dedicated, enqueue the method invoke on the ThreadPool
            // will also set the Priority / IsBackground of the thread
            ThreadPool.QueueUserWorkItem(_ =>
                                             {
												 try
												 {
												 	Thread.CurrentThread.IsBackground = Background;
												 	Thread.CurrentThread.Priority = Priority;
												 	Thread.CurrentThread.Name = Name;
												 	args.Proceed();
												 }catch
												 {
												 	if (!DropExceptions)
												 		throw;
												 }
                                             });
        }

        /// 
        /// Verify the aspect usage
        /// 
        public override bool CompileTimeValidate(MethodBase method)
        {
            // method cant be null
            if (method == null) // should not occur imho
            {
                Message.Write(SeverityType.Error, "ASPECT_ASYNC_ERROR_0001", "The Async aspect can only be applied to methods.");

                return false;
            }

            // method must be upcastable to MethodInfo
            if (method as MethodInfo == null) // should be null when being used on return-type less methods (constructor / deconstructor)
            {
                Message.Write(SeverityType.Error, "ASYNC_ERROR_0002", "The Async aspect cannot be applied to a constructor/deconstructor.");

                return false;
            }

            // method may not return anything
            if ((method as MethodInfo).ReturnType != typeof(void))
            {
                Message.Write(SeverityType.Error, "ASYNC_ERROR_0003", "The Async aspect cannot be applied to methods returning a (non-void) value.");

                return false;
            }

            // show a warning if the method does not start or end with Async (case insensitive)
            if (!(method as MethodInfo).Name.StartsWith("Async", StringComparison.OrdinalIgnoreCase) && !(method as MethodInfo).Name.EndsWith("Async", StringComparison.OrdinalIgnoreCase))
            {
                Message.Write(SeverityType.Warning, "ASYNC_WARNING_0004", "Method marked with the Async aspect, should start or end with 'Async' in its name.");
            }

            return base.CompileTimeValidate(method);
        }
    }

Tags: , ,

Coding

Reflecting self in constructor : bad m’kay..

by tim 21. March 2011 17:27

Today, after wasting hours on this, I found out why when using a PropertyInfo.SetValue caused a ‘null’ exception even though all looked fine.

The issue was that I tried to set properties of ‘self’ within the constructor.

Since the object does not really exist until the constructor is finished, the null exception actually refered to 'this’ being null!

A new thing learned Smile

Tags: ,

Coding

Simple aspect : NotNull

by tim 15. March 2011 12:01

Ever wanted to enforce properties to not accept null as an answer?

Then decorate them using this simple PostSharp attribute!

[Serializable]
	public class NotNullAttribute : LocationInterceptionAspect
	{
		public override void OnSetValue(LocationInterceptionArgs value)
		{
			if (Equals(value.Value, null))
				throw new ArgumentNullException("value");

			base.OnSetValue(value);
		}
	

Tags: , ,

Coding

A StopWatch extension to time code execution

by tim 14. March 2011 14:58

I found a nice extension method for the StopWatch class, that makes it damn easy to benchmark bits of codes.

public static class StopwatchExtensions
{
    public static long Time(this Stopwatch sw, Action action, int iterations)
    {
        sw.Reset();
        sw.Start();
        for (int i = 0; i < iterations; i++)
        {
            action();
        }
        sw.Stop();

        return sw.ElapsedMilliseconds;
    }
}
Source: http://stackoverflow.com/questions/232848/wrapping-stopwatch-timing-with-a-delegate-or-lambda

Tags: , ,

Coding

converting java to csharp – mission complete

by tim 14. March 2011 09:01

This weekend I’ve been working on converting the decompiled sources of the minecraft server (thx MCP team for the tools) from java to csharp.

It is now done and this is an overview of the things that I actually ‘used’ to perform the conversion:

  • minecraft sourcecode, decompiled/deobfuscated by MCP
  • Visual Studio 2005’s java conversion utility => Used some tiny bits of the converted result
  • IKVMC’d minecraft_server.jar => minecraft_server.exe
  • Reflector to peek at some tiny bits, to see how IKVM did the conversion from java => .NET
  • 2 workdays of coding time 

The end result is a working mc server, but I did make an error somewhere.

Some shadows seem darker as they should be (they’re calculated by the server) so I assume I broke some loop somewhere.

You can find the code at https://github.com/geckosoft/Crafty/tree/master

Take notice that I gave all rights to ‘Mojang’ considering its their converted code, so if they want it down, I will take it down.

I’ll most like not proceed working on this code (maybe just fix that lighting bug?) since I reached my goal, to port a java app to .NET.

But a new Crafty server is in the making, and this one will be build from scratch, but might contain some logic from the ‘old’ Crafty, as otherwise it would be hard to generate equal worlds as the official mc server does.

Tags:

A Simple Aspect for NHibernate and the virtual keyword

by tim 11. March 2011 14:42

While googling around for other nice PostSharp aspects I ran into this article.
=> http://www.codeproject.com/KB/dotnet/Unsealer.aspx

This aspect automaticly marks all members virtual, even when the keyword is not used in the code.

Someone refered to another aspect, that does another task : it checks if all public members are indeed marked as virtual.
=> http://davybrion.com/blog/2008/05/nhibernate-and-virtual-methodsproperties/

Sadly enough the website seems to be down at the moment, but I managed to retrieve the aspect using the Google Cache.

See the recovered info + code here
=> http://mylemans.com/page/NHibernate-and-virtual-methodsproperties-Compile-time-validation.aspx

Tags: , , ,

learned something new today – events can be made virtual

by tim 11. March 2011 11:24

I tried to use the PostSharp Aspect from Jensen ( http://www.jsomers.be/story/2011/03/01/inotifypropertychanged-support-read-only-properties ) and ran into an issue when an PropertyChanged event was already defined.

In attempt to fix it, I tried to make the event declaration ‘virtual’ but expected it to fail : it did not!

Everything is working as expected now! So lesson learned : “event declarations CAN be made virtual” Glimlach

Tags: , , ,

Coding

About the author

Tim is a C# developer, learning new things on the go.

Month List

Powered by BlogEngine.NET 2.0.0.36 - Eco Theme by n3o Web Designers