Hosting/Debugging WCF Service with 32 Bit WCFServiceLibrary

These days I had the problem that I needed to host and debug 32Bit WCF Service in Visual Studio 2010, because my backend had to talk to a Access Database where no 64Bit Driver is available.

But always when I tried to do that, I got the following exception:
System.BadImageFormatException: Could not load file or assembly

After googling around the web I found out, that the WcfServiceHost in VS2010 is not able to accept 32 Bit DLLs. But I also found a clever solution how to fix it.

  1. Copy WcfSvcHost.exe from C:\program files (x86)\Microsoft Visual Studio 9.0\Common7\IDE to a local directory. Keep a backup copy of this file, of course.
  2. Start a Visual Studio 2010 Command Prompt (one of the links from the start menu -> Visaul Studio 2010)
  3. “cd” to the directory where your copy of WcfSvcHost is located.
  4. Execute the command “corflags /32BIT+ /FORCE WcfSvcHost.exe”
  5. Copy the exe back to where you found it.

That solution works very great and should solve your problem as it did solve my.

Thanks and respect to Marco Zhou and Gordon Watts who found out this solution:
http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/2e29a4aa-e587-43ef-bf50-329b7cd3eefb/

Help making Windows Phone 7 Emulator to be Virtual Machine enabled

Microsoft has setup a page on User Voice in order to improve development environment for Windows Phone 7 applications.

Because of my Windows Phone 7 Apps “TimePunch Mobile” and “My Colouring Book”, I’m already used to it. But it’s really annoying that the emulator can’t run within a Virtual Machine.

That’s why I need YOU and your UserVoice to make Microsoft move their ass and improve the emulator so that it can run within a VM.

Please vote for it on: http://wpdev.uservoice.com/forums/110705-app-platform/suggestions/2344692-enable-the-emulator-to-run-in-vm-s-virtual-machin

Using AutoMapper Config with ValueInjecter

For all who are interessted, I created a ValueInjecter extension in order to use your existing AutoMapper Mapping Configuration with ValueInjecter. I created this extension because I had to switch over to ValueInjecter, because I could not compile AutoMapper against Client Framework 4.0. And I didn’t wanted rewrite my Mapping Configuration.

It looks like the AutoMapper, but internally it uses ValueInjecter ;) Hope you enjoy the extension.

Example:

public class CalendarEvent
{
    public DateTime EventDate { get; set; }
    public string Title { get; set; }
}

public class CalendarEventForm
{
    public DateTime EventDate { get; set; }
    public int EventHour { get; set; }
    public int EventMinute { get; set; }
    public string Title { get; set; }

    // Additional Members to show further mapping possibilities
    public string BarToIgnore { get; set; }
    public bool AlwaysTrue { get; set; }
}

static void Main(string[] args)
{
    // You can use the AutoMapper extension for the ValueInjecter like you would user AutoMapper

    // Model
    var calendarEvent = new CalendarEvent
    {
        EventDate = new DateTime(2008, 12, 15, 20, 30, 0),
        Title = "Company Holiday Party"
    };

    // Configure AutoMapper
    Mapper.CreateMap<CalendarEvent, CalendarEventForm>()
        .ForMember(dest => dest.EventDate, opt => opt.MapFrom(src => src.EventDate.Date))
        .ForMember(dest => dest.EventHour, opt => opt.MapFrom(src => src.EventDate.Hour))
        .ForMember(dest => dest.EventMinute, opt => opt.MapFrom(src => src.EventDate.Minute))
        .ForMember(dest => dest.Title, opt => opt.MapFrom(src => src.Title))
        .ForMember(dest => dest.BarToIgnore, opt => opt.Ignore())
        .ForMember(dest => dest.AlwaysTrue, opt => opt.UseValue(true));

    Mapper.AssertConfigurationIsValid();

    // Perform mapping
    CalendarEventForm form = Mapper.Map<CalendarEvent, CalendarEventForm>(calendarEvent);

    // Assertions
    Debug.Assert(form.EventDate == new DateTime(2008, 12, 15));
    Debug.Assert(form.EventHour == 20);
    Debug.Assert(form.EventMinute == 30);
    Debug.Assert(form.Title == "Company Holiday Party");
    Debug.Assert(form.BarToIgnore == null);
    Debug.Assert(form.AlwaysTrue == true);
}

You can download the extension from: http://wordpress.ad-factum.de/AutoMapperConfig_UsingValueInjecter.zip

And if you like it, I really would appreciate an UpVote on StackOverflow ;)

WPF – NavigationService.GoBack() Mystery

I just had some fun with the WPF NavigationService. Let me explain.

I discovered in my windows app that all my previous pages are empty if I go back using the NavigationService.GoBack() command.

After googling around I found out that this is a wanted behaviour, as long as the page does not has the KeepAlive Property set to TRUE.

So for all who are also having fun with this small pitfall. Here’s the reference I found:
http://www.netframeworkdev.com/windows-presentation-foundation-wpf/navigationservicenavigate-vs-navigationservicegoback-76618.shtml

May the code be with you ;)
- Gerhard

Azure: From your PC to the cloud

In this post I want to write some tipps how to deploy your project to the cloud in a way that allows you to have a local test configuration and a production configuration.

FAQ: My code runs in local AppFabric, but it does not when I deploy it to Azure
I had the same problem with my project until I discovered the following thing:

  1. VS 2010 will only publish external DLLs,that are referenced by your Azure Role Project where the “Copy Local” Property is set to TRUE. This is especially dangerous when you use e.g. the EntityFramework that reside within the GAC and that is used by your DataAccess Layer. You will have to first reference the EntityFramework.dll with your Azure Role Project. And second, set the Property “Copy Local” to TRUE.

FAQ: How can I have a separate test and release configuration
This was long time not clear too me, but here’s the answer:

  1. Forget about your “web.config” file in order to store Application Settings. It’s true, that you can use it, but if you use it, you will loose the ability to change configuration on the fly without deploying the Azure Role again.
  2. It’s better to store the Application Settings within the “ServiceConfiguration.cscfg”. It’s more or less the same like using the AppSettings in your web.config. You can access these settings using:
       RoleEnvironment.GetConfigurationSettingValue("YOUR_SETTING");
  3. Store your development settings within that file.
  4. Create a second “ServiceConfiguration.cscfg” file and store it into a independent Directory named e.g. “Release Config”
  5. It’s better not to publish your Project directly with Visual Studio to the Cloud, but to publish it to a local Directory. That is because within that local directory you can replace the configuration with your “ServiceConfiguration.cscfg” file from the “Release Config” directory.
  6. After that you can upload your project within the Azure Management Portal.
  7. Tipp! Now you can change your configuration online in your Azure Management Portal, without re-deploying your Project to Azure.

FAQ: How to change connection string of your Entity Framework in Release deployment
The Entity Framework stores the connection string within the web.config!, which is (see above) not wanted.

  1. We have to teach Entity Framework not to use the connection from the web.config. Therefore it’s a good way to place a static constructor in the Entity Framework Context class and set a new DefaultConnectionFactory.
            
            static MySyncContext()
            {
                Database.DefaultConnectionFactory = new AzureConnectionFactory();
                Database.SetInitializer(new CreateDatabaseIfNotExists());
            }
    
  2. The AzureConnectionFactory will now use the connection string from our WebRole Configuration. Here’s the implementation:
            
        public class AzureConnectionFactory : IDbConnectionFactory
        {
            public DbConnection CreateConnection(string nameOrConnectionString)
            {
                var connectionString = RoleEnvironment.GetConfigurationSettingValue("DatabaseConnection");
                var sqlConnectionFactory = new SqlConnectionFactory();
                return sqlConnectionFactory.CreateConnection(connectionString);
            }
        }
    
  3. As you can see, the connection is used from file “ServiceConfiguration.cscfg” and setting “DatabaseConnection”.

If I find some other interessting topics, I’m going to append them to the post.
Cheers
- Gerhard

kick it on DotNetKicks.com

Was wäre, wenn Freiberufler wirklich frei wären?

Sind Sie auch Freiberufler? Dann eine Frage: Können Sie wirklich frei über Ihre Arbeitszeit, Anwesenheit usw. entscheiden? Wohl eher nicht.

Es muss jedoch erlaubt sein darüber nachzudenken und zu philosophieren. Deswegen ist dieser Post auch in Deutsch – und nicht wie sonst in Englisch. Oder sagen wir es mit einem Filmzitat – “Ein Gedanke ist wie ein Virus, resistent, hochansteckend und die kleinste Saat eines Gedanken kann wachsen. Er kann dich aufbauen oder zerstören.”

Stellen Sie sich vor, sie könnten wirklich frei darüber entscheiden, wo und wann Sie arbeiten. Was würde das bedeuten?

Voraussetzung
Die Technik muss stimmen, das ist klar. Die interessantere Frage ist jedoch, wie der Arbeitsablauf aussehen könnte. Betriebswirtschaftlich betrachtet, ist ein Freiberufler ein Einzelunternehmer, der für einen Kunden eine Dienstleistung erbringt. D.h. als Minimalvoraussetzung für die Dienstleistung, muss der Freiberufler wissen, was er in einem bestimmten Zeitraum (nennen wir diesen Zeitraum einen Sprint) zu tun hat.

Der Ablauf
Diese Festlegung könnte in einem gemeinsamen Meeting am Wochenanfang zusammen mit dem technischen Projektleiter getroffen werden. D.h. der Freiberufler comittet sich auf einen bestimmten Funktionsumfang, den er in der kommenden Woche implementieren möchte.

Die Arbeitsorganisation
Ab hier hat der Freiberufler die volle Kontrolle. Er kann beim Auftraggeber arbeiten, oder auch zu Hause, in der Bar oder beim Mexikaner – Morgens, Abends oder wenn andere schlafen. Einzig und alleine entscheident ist, dass der zugesagte Funktionsumfang beim nächsten Sprint Meeting implementiert ist.

Abstimmungsbedarf und Meetings
Natürlich gibt es manchmal auch Abstimmungsbedarf. Das ist klar. Aber hier sollte sich der Freiberufler selbstständig und eigenverantwortlich an die Ansprechpartner wenden können und sollen, die er für seinen Arbeitsauftrag benötigt. Das tut er im Normall beim Kunden vor Ort sowieso schon.

Wird umgekehrt der Freiberufler für ein Meeting benötigt, dann sollte in Abstimmung mit dem Freiberufler ein Termin für das Meeting gefunden werden. Auch das sollte nicht unmöglich sein.

Die Arbeitskontrolle
Im Normalfall sollte die Kontrolle des Arbeitsergebnisses ausreichen. D.h. wenn ein Freiberufler über Wochen sein Arbeitsziel verfehlt, dann kann er sich selbst nicht einschätzen, oder er arbeitet einfach nicht.

Trotzdem gibt es natürlich Randbedingungen, wie z.B. die Stunden die in Rechnung gestellt werden können. Hier existieren jedoch sehr gute Tools, wie TimePunch, die dem Projektleiter wenn nötig täglich den Stand über die aktuelle Arbeitszeit vermitteln.

Heiße Phasen
Als heiße Phasen möchte ich die Wochen bezeichnen, in denen ein Release ansteht, oder Tester die App auf Herz und Nieren prüfen. Ist hier eine Anwesenheit wirklich erforderlich? Nein – was erforderlich ist, ist eine Erreichbarkeit und eine gesunde Priorisierung der Bugtickets. Nicht jedes Ticket hat IMHO Prio1 und muss sofort gefixt werden. Sollte es aber dennoch notwendig sein, dann ist es ausschlieslich die Erreichbarkeit die zählt. Denn das Ticket wird nicht durch die pure physische Anwesenheit gefixt.

Urlaub und freie Tage
Auch das ist immer wieder ein beliebtes Thema. Natürlich benötigt der Projektleiter ein gewisses Maß an Planungssicherheit – zumindest bei den Release Zyklen. Hier sollte gelten: Urlaube müssen so angekündigt sein, dass ein Umplanen des Urlaubs für den Projektleiter möglich ist. Als Definition: Urlaub ist, wenn man für einen Sprint nicht verfügbar ist.

Bei den freien Tagen sieht es aber anders aus. Diese liegen alle innerhalb eines Sprints und sind somit eigenverantwortlich vom Freiberufler zu planen. Denn nur der Freiberufler kann einschätzen, ob er den zugesagten Funktionsumfang in der Zeit implementieren kann oder nicht. Der Abstimmungsbedarf entfällt daher komplett.

Zum Ende
Mit diesem Post möchte ich gerne eine Diskussion anregen. Schreibt mir Eure Kommentare. Stimmt mir zu, oder schreibt Eure Bedenken. Was auch immer – es ist willkommen. (Außer Spam und Flames /)

Mein Ziel: Wenn ich in 10 Jahren diesen Blogeintrag lese, möchte ich gerne so arbeiten können.

Generate Thumbnails using GeneratedImage Handler and ASP.NET MVC

What I want to show in this post is, how easy it is to create dynamically images for ASP.NET MVC.

The example will show how to create thumbnails from images. This is important, if you want to create an image viewer and you need to have all images in one size in order to view them properly in a grid. Images therefore needs to be resized appropriate.

The first thing you need for that is the Microsoft.Web.GeneratedImage.DLL (http://aspnet.codeplex.com/releases/view/16449) which you need to include in your project.

After that you can derive a new Image Handler from the ImageHandler class, by adding a new Item “GenericHandler” to your solution. This class must be placed in a directory where it can be accessed directly by the webuser. Therefore create new directory called “Handler”.

    public class MyImageHandler : ImageHandler
    {
        public MyImageHandler ()
        {
            EnableServerCache = true;
            EnableClientCache = true;
            ClientCacheExpiration = new TimeSpan(356, 0, 0, 0);
        }

        public override ImageInfo GenerateImage(NameValueCollection parameters)
        {
             // Type code here
        }
    }

I also added a new Helper Method in that handler in order to create the code for viewing the images in a more easy way.


        public static string CreateImage(string pic, int size)
        {
            return "<a href=\"/Handler/MyImageHandler.ashx?pic=" + pic + "\">" +
                   "<img src=\"/Handler/MyImageHandler.ashx?pic=" + pic + "&size=" + size + "\"/>" +
                   "</a>";
        }

As you can see, the image handler takes two attributes, the picture itself and the size to which the image shall be resized.
Within the View you can output a resized image in the following way.

        <div class="picture">
            <%= MyImageHandler.CreateImage(Model.Picture, Model.Size) %>
        </div>

After having this preparations done, the only thing that is missing is the code for the Image Handler itself.
And boom – here it is.

        public override ImageInfo GenerateImage(NameValueCollection parameters)
        {
            // Validate the parameters
            var pic = parameters.Get("Pic");
            if (string.IsNullOrEmpty(pic))
                return null;

            // Check, if there is a Size Parameter
            var sizeStr = parameters.Get("Size");
            int? size = null;
            if (!string.IsNullOrEmpty(sizeStr))
                size = int.Parse(sizeStr);

            // Download the image file
            string file = ROOT + pic;
            var image = Image.FromFile(file);

            // return the image imediatly.
            if (size == null)
                return new ImageInfo(image);

            // Maybe resize, if a size has been set
            var bmp = new Bitmap(size.Value, size.Value);
            Graphics graphic = Graphics.FromImage(bmp);
            graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphic.FillRectangle(Brushes.White, 0, 0, size.Value, size.Value);

            // Calculate the new size and copy the image
            float ratio = (float)image.Width / (float)image.Height;
            if (image.Width>image.Height)
            {
                float newHeight = size.Value/ratio;
                graphic.DrawImage(image, 0, (float)((size.Value - newHeight) / 2.0), size.Value, newHeight);
            }
            else
            {
                float newWidth = size.Value*ratio;
                graphic.DrawImage(image, (float)((size.Value - newWidth) / 2.0), 0, newWidth, size.Value);
            }

            // ok. now return it
            graphic.Dispose();
            return new ImageInfo(bmp);
        }

Hope you enjoyed it.
Cheers
- Gerhard

Posted in .NET, C#. 1 Comment »

The mammoth task of making a single-threaded UI, getting multi-threaded.

At the moment I’m working on a single-threaded WinForm UI that will have to consume WCF Services over the Internet. The problem of such a change is, that the UI is getting really languorous due to the service response times. That’s why I’m going to rewrite it for multi-threading.

At this blog-post I want to describe the problems I have to face, and the way I solved it.

1.) Invocation
All times you change or query a UI control within a thread, you’ll get an InvocationException due to the fact, that you are’nt allowed to do this within a thread. Instead of duplicating the code (like described in http://is.gd/c2zoY) I wrote a delegate which does this for me.

        public static void InvokeIfRequired(this Control window, Action method)
        {
            if (!window.InvokeRequired)
                method();
            else
                window.Invoke(new MethodInvoker(() => method()));
        }

That helped me to write code like:

        // Example
        this.InvokeIfRequired(() =>
        {
                cmdAddProject.Visible = context.AllowedToCreateInstantProjects;
                cmdEditProject.Visible = context.HasTheRightToFullAccess;
                cboProjects.Focus();
        });

2.) STA Threads and Too many Threads
The problem of Multi-Threading in UI is, that worker threads are always MTA Threads. But some UI interaction requires to use STA Threads. Another problem is, that if you call nested methods, you don’t want to open a new thread, if you’re already in a worker thread.

2a) STA Threads:
I don’t know a solution other than to create your own thread.

2b) Too many threads:
I assume: When we are in a separated thread, we don’t need to create a new thread. That’s the point. That’s why I’m using a [ThreadStatic] field to flag a thread as a worker thread.

        [ThreadStatic] private static bool isInSeparatedThread;

        ///  Executes a Call within a queued worker process
        public static void ThreadedCall(this IWin32Window window, Action method)
        {
            var ctrl = window as Control;
            bool createdState = ctrl == null || ctrl.Created;

            // Do not force a new thread when a the caller already in a new thread
            // or the control has not even been created.
            if (!isInSeparatedThread && createdState)
            {
                var thread = new Thread(() =>
                {
                    isInSeparatedThread = true;
                    method();
                });
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
            }
            else
            {
                // A Thread already started
                method();
            }
        }

That helped me to write code like:

            this.ThreadedCall(() =>
                {
                    ...
                    ...  // Although, if ThreadedCall is executed again, no new thread will be created.
                    ...
                });

3.) Exception Handling
And last but not least, error handling is a problem, because every thread needs to be encapsulated by a TRY/CATCH Block in order to handle exceptions properly. I managed this by writing the following extension method.

        [ThreadStatic] private static bool isInSafeCall;

        ///
        /// Executes the Action Method in a safe way, in that exceptions are handled.
        ///
        public static void SafeCall(this IWin32Window window, Action method)
        {
            // If the call has already been assured, so only executed the method inside
            if (isInSafeCall)
            {
                method();
                return;
            }

            try
            {
                isInSafeCall = true;
                method();
            }
            catch (Exception exception)
            {
                ApplicationHelper.ShowException(window, null, exception);
            }
            finally
            {
                isInSafeCall = false;
            }
        }

That helped me to write code like:

            this.SafeCall(delegate
            {
                using (var listDialog = new ProjectListDialog(Connection))
                    listDialog.ShowDialog(this);

                RefreshContent();
            });

4.) Single Method Calls
I forgot something. Sometimes it’s necessary to ensure, that a code block is only called one time by a thread. Yeah, I know. You can use lock(), but I don’t want that other threads are waiting to execute the code. Think about failing connections. You don’t want to inform the user for every thread, that the connection has been broken. That’s why I implemented a Singleton extension method, that ensures, that a code part is only called one time.

        ///
        /// Declares that a method is only called once.
        /// Second call's from other threads to the method will return immidiatly.
        ///
        public static void Singleton(this IWin32Window window, AutoResetEvent locking, Action method)
        {
            // Return immidiatly, if the event could not aquired.
            if (!locking.WaitOne(0))
                return;

            try
            {
                method();
            }
            finally
            {
                locking.Set();
            }
        }

That helped me to write code like:

        private readonly static AutoResetEvent ShowExceptionLock = new AutoResetEvent(true);

        public static void ShowException(this IWin32Window parentWindow, Exception exception)
        {
            parentWindow.Singleton(ShowExceptionLock, () =>
                {
                    MessageBoxIcon icon = MessageBoxIcon.Exclamation;
                    parentWindow.Show(parentWindow, message, ProductLabel, MessageBoxButtons.OK, icon);
                });
        }

5). Combination:
And I combined some methods to create new functionality that I use many times.
For example that one:

        ///  Executes a Safe Call within a new Thread
        public static void ThreadedSafeCall(this IWin32Window window, Action method)
        {
            window.ThreadedCall(
                ()=> window.SafeCall(method)
            );
        }

6). Download:
If you like it, you can download the complete helper class and tell me your thoughts about it.

Cheers
- Gerhard

Download: Threading.cs

kick it on DotNetKicks.com

Asynchronous WinForm UI

When you’re trying to create a WinForm Application that is working asynchronously, you’ll probably in a common failure:

System.InvalidOperationException occurred
Message="Cross-thread operation not valid: Control 'MainForm' accessed from a thread other than the thread it was created on."
Source="System.Windows.Forms"

You’ll get this failure, because it’s not allowed to update a UI control from another thread than the thread that has created the control.

A fluent way around this is to use the MethodInvoker class.
Let’s asume that you have a statement like the following one:

appForm.Text = appInfo;

Using the MethodInvoker class would look like:

appForm.Invoke(new MethodInvoker(() => { appForm.Text = appInfo; }));

That’s still a one-liner;-) And with that small hint, you’ll get around such annoying exceptions.
Hope you enoy it.

Cheers
- Gerhard

PS: Here’s also a great article about the MethodInvoker.

kick it on DotNetKicks.com

Give me a Mock ;)

Last days I stumpled upon a great Mockup Tool that creates really stunning results in a few minutes.

Our .NET User Group in Frankfurt invited me to a workshop where a new Mockup Tool called “Balsamiq” should be shown to the developers. Unfortunatly I wasn’t able to come due to my daughters birthyday. But the mail our User Group leader wrote let my interest awake for that tool. So I decided to test it by my own, and I was luckily suprised by the ease of creating UI mockups.

Have a look at the following mockup that I created with Balsamiq within a few minutes, and than have a look at the original screen.

TpClient Mockup TpClient Original

I think you can’t deny the affinity of both screens-) Ok. The Mockup was made out of an existing application, but that was only because of my testing purpose.

In my testing I only found one thing that anoyes a little. It was that I accidently changed the size of the wrong UI element sometimes. But I found a way to fix that issue. You simple have to pin new UI elements in Balsamiq when you’re fine with it. With that feature you can prevent moving or resizing elements you don’t want to change.

So give that tool a chance. For me, I’m pretty sure that I will use it in my next project.

Cheers
- Gerhard

BTW: Here’s the link to Balsamiq (http://www.balsamiq.com)

kick it on DotNetKicks.com

Follow

Get every new post delivered to your Inbox.