Join us at Thynk Software

DISCLAIMER: This is classified as an old boring recruitment post but hey it’s one I need to call out… I just founded a new company, Thynk Software and I need smart guys that can help me grow and execute projects.

Thynk Software is currently looking for software developers to help out in the product delivery space. Currently we have a pipeline of Windows 8 apps and also Web application (based on Azure). Most of the work can be done remotely (with some travel to the home office which would be covered by Thynk). If like us you are passionate about developing on these technologies please contact us (mgrech@thynksoftware.com).

Would love to hear from you. I am sure that together we can figure out a way to work together !

Thynk Logo

WPF Radio Buttons… “Once it is checked it just won’t uncheck”

Today I was doing some Sunday morning coding (why read newspaper when you can code right? ) and stumbled upon an issue with Radio buttons in WPF… Basically if you have a set of Radio buttons with the same group name, once you check one of the radio buttons you cannot uncheck it.. This was causing me grief since I wanted to enable the user to be able to uncheck it back…

This might seem quite simple to solve but I wanted to write this post to show how WPF Dependency property system is superior from any other XAML platform …

So first off, I don’t want to create a sub class for the radio button to have this behavior and I would also like that i can re-use this behavior for other Radio buttons… The first thing that pops to mind is, “let’s create an attached property”. However with an attached property on it’s own we cannot do much… the idea of using an attached property works well if you can hook to an event and react accordingly adding the behavior that you want. However in this case what is happening is that the radio button is automatically suppressing the checked and unchecked events if a Radio button in a group is checked …

FrameworkMetaData to the rescue …

One thing that is not heard of much however it is there and a very important part of the WPF DependencyProperty System is CoerceValueCallback. With CoerceValueCallback you can validate the value of a property before it is set.. Example let’s say the Minimum and Maximum properties of a slider control, the Minimum property can have a CoerceValueCallback that validates that the Minimum value is never set more than the maximum..

In this case we can use the CoerceValueCallback to auto set IsChecked to false if the previous value of the Checkbox is set to true. The only issue now is that FrameworkMetaData get’s attached per Control Type, thus if I use the FrameworkMetaData it will be applied to all radio buttons in my solution… well for that we can use Attached properties… we can have an attached property and when set on a radio button we will enable this behavior if not then we don’t do anything …

FrameworkMetadata

 

and here is the attached property

attachedProperty

 

And that’s it…

Silverlight, WinRT, WinPhone, they are really good XAML platforms, however for me WPF is just great for devs.. it gives the dev the power and flexibility needed to build clean and large scale solutions… Aaa well, maybe it’s passion from my first love Avalon speaking now… the good old day !

If you want the actual code so that you don’t need to re-code it, you can find it here 

 

 

 

 

HTML5 CSS3 Javascript vs XAML .net and Silverlight

Introduction >> The clash of the Titans is on

Developers right this second are at some bar / restaurant / lounge / god knows where else being “social” i.e. having geeky discussions about technology, what language/platform is best to use or even better “what’s coolest right now” Smile

I am one of those developers and I must say, when it comes to such discussions I am always biased towards XAML technologies. Yet recently I started diving in what I used to call the “darker side” i.e. HTML5, JS and CSS3 (the “dark side” is reserved for things like Java Smile ). It’s been years (6 to be exact) since I was doing some HTML and Co and I must say; I am really impressed. HTML5 just takes everything to a whole new level BUT what impresses me most is JS and CSS3.

JS because the browsers are natively exposing APIs such as GeoLocation, Canvas drawing, local storage and also indexed DB (and more APIs). BESIDES THAT, what sells JS for me, is the new libraries developers are building such as JQuery and Knockout.js. Working with javascript today is just loads and loads of fun !!

CSS3 because WOW its frekin cool!! The new box modelling with the Flexible box model, the gardients, the transforms, the transitions and I can go on and on…

So yea I must admit, web development (presentation layer) of today is becoming loads of fun! Backend for Web with MVC its also frekin cool! so I guess the questions that readers of my blog / people who know me would ask “Is Marlon turning his back on XAML?” The answer is simple and its NO, my car number plate still says WPF so I guess I cannot change everything now Smile Joking aside, I see both technologies as super awesome and both of them have a different realms (to a certain extend). “to a certain extend” for the reason that WinRT will also support HTML5 JS and CSS3 as a first class citizen just like it will for XAML and C# / C++.

Does this mean we should say bye bye to XAML and just focus on HTML5 and Co?? If it can do web + desktop why bother looking at XAML??

Ok so lets be a bit metaphoric about this and let’s compare technologies with cars. There are many different brands, there is Audi, there is Honda and you can go on and on… They all take you from place A – B. How they take you is a bit different, some are super confortable, some are fast. Some are perfect for one thing some are perfect for another! You buy a car that fits your needs and the same can be said to technology you decide to use. There are those scenarios, for example when you are moving house, where you do not have the luxury to use your “preferred car” because hey; if its a sports car, it will be no good when you are moving, so in such a case you are coerced to use a specific type. Such an example for developers is the web / mobile phones … Yet again just like in real life there are many different trucks for moving Smile there is HTML5, and then there are the plugins (Flash, Silverlight) …

Which one should you go for? HTML5 or Plugins?

Looking at web tech today I would say go for HTML5. It will work on devices such as phones, if done properly it will be super fast. On the other hand I would strongly suggest you consider SL / Flash if your users cannot install/already have a browser that supports HTML5. In that case then yea I would not go for the HTML < 5 because you’re in for nightmares! Maybe mix and match! Some things are better done with plugins some other with HTML. Do not be afraid to try both worlds, it will not hurt.

What about WPF??

WPF will still have a place but I guess we will slowly see it being used lesser and lesser, reason being with WinRT you are not using WPF you are using WinRT, yes its XAML but NO it is not WPF. There are cases such as VS and similar heavy weight products that would require something like WPF. Trading applications and internal banking applications is another example for WPF apps. But yea if you are building a simple app, going forward one would be better off with something Metro style i.e. WinRT based. So should WPF developers say “cr*p I wasted a lot of time learning something I will not use anymore”?? Whoever says that is really talking bull***t! WPF thought us a lot, WPF gave us so many concepts and ideas… WPF will always continue living in other technologies… Its concepts that really are hard to learn not how to use a framework, example DataTemplates, ControlTemplates, Binding and many other concepts … For me WPF showed me what an awesome API should look like! Besides that you learnt XAML that is something that is not a waste of time since XAML is here to stay !

Final verdict – Who will be the last technology standing?

None probably Smile technology evolves … sorry my fellow geeks, I like you used to treat a technology stack (and must admit still do sometimes) as my one and true love and I could not use another technology without feeling that I am being MARLONCHANGE… well its not the case, when it comes to technology you can mix and match as much as you want and no you will not be called a “Cheater” Smile

Take it from me, if you did not have a look at HTML5 and co, maybe its time for you to do so. Maybe you will not use it but I am sure you’ll get something out of it. I am learning so much, getting so many new ideas (that yea I can even apply for WPF) from doing some HTML5 and Co.

Hope I did not bore you to death with this post but I felt I needed to share this with you guys! I’ll be posting more on HTML5 and Co this year but yea of course I will also do the same for XAML and Co.

Long live XAML

Long live HTML5 (and co)

>> No source code to download just thoughts …

Timeouts for long running operations…

Today I stumbled upon a timeout issue while building a web application and felt like I need to share this for those that like me wasted/are wasting hours trying to figure out why you are getting a timeout.

Here is a diagram that show the structure of the request response stack I have.

image

The reason why I went for an AsyncController is that the long running operation is not CPU-bound processing thus the thread that would be waiting for the response would be wasting its time waiting. More info on why and how to use Async Controllers in MVC3 can be found here.

All is fine and good until my I hit a request that took more than 1 minute, and then the nightmare of timeouts begun… So first thing I did is make sure I make the timeout for the WCF service longer. You can do this by setting the sendTimeout and the receiveTimeout of the binding in the binding configuration.

image

Don’t forget to do the same thing on the client side otherwise you’ll get in trouble (the config is the same as the server, and if you are using VS to generate the config then this will be done for you when you refresh the ServiceReference).

At this stage I said, wuhooo, it’s all done… but nope… it was still timing out … I was confused and puzzled… WHY WHY WHY!!!!!

Well AsyncController also have a timeout (or 90seconds as per MSDN doc), you also need to set the timeout to the async controller action in order for this to work. You do this by setting the AsyncTimeout attribute on the action that you want to extend its timeout.

image

With this in place all started working… but yea the errors don’t really help !

Hope this helps…

Parsing HTML in C#

Today I stumbled upon a bizarre problem, I wanted to parse an HTML for a site to find out if the site contains any RSS feeds. After some research I found out that finding the RSS feed for a site is not that hard, you have to look for an element that looks like this

image

“Easy task”, I said, me Mr.Optimistic; “I will just load it up in XElement and using Linq to XML to get the data I want”. BUT guess what the web is filled with crazy HTML that a standard .NET parser such as XElement just gives up on and blows up in flames.

After some heavy head banging to walls and ceilings, I found the solution, HtmlAgilityPack. This open source project lets you load HTML even if it is not in a good shape. With some options HTMLAgilityPack will fix these errors and then you can query the HTML to get elements and their attributes as you please.

Here is the code I used to load the HTML and find the data I need

image

Kudos to the guys from HTMLAgilityPack!!!

More MEFedMVVM NavigationExtensions love

One of my colleagues (he is Danish and he is stinky) who has been using MEFedMVVM NavigationExtensions asked to add functionality so that you can Navigate to a View from code.

I wanted to be careful adding this feature to make sure the ViewModel stays clean. So lets see what we need to do this

Lets first rewind and look at the current MEFedMVVM NavigationExtensions… It has 3 Attached properties

The properties are

- NavigateTo – which is the uri for the view
- NavigationHost – which is the UI element to host the view rendering
- NavigationParameter – which is a parameter to be passed

There is a lot of UI specific stuff in the above so we need to be careful not to make the ViewModel dirty. The ViewModel needs some kind of “UI service “ so that it can ask this service to navigate to a view and pass a parameter (something like the IVisualStateManager of MEFedMVVM); something like this >> Navigate(string viewName, object parameter) . It also need to pass the host so that the NavigationExtensions know where to render this view.

Here is what we came up with ..

As you know (or maybe not, in that case please read this) MEFedMVVM has support for UI Services, if your service implement IContextAware, MEFedMVVM will inject your service with the View instance that asked for the ViewModel to be injected. We leverage this and have an INavigationInvokerFactory. The INavigationInvokerFactory exposes a method that takes a string which should be the name of the host element. Internally the INavigationInvokerFactory will call the FindName(“[your parameter]”) on the element that was sent by MEFedMVVM IContextAware. The CreateNavigationInvoker method will return an INavigationInvoker which can be used to Navigate to a view.

image

From here you now have an INavigationInvoker and all you have to do is call the Navigate method passing the uri for the View you want to render and the parameter you want to pass

image

And that’s all folks… Enjoy Smile

MEFedMVVM NavigationExtension

Introduction

Most of the MEFedMVVM features so far were all around discoverability of ViewModels, yet when building MVVM application sometimes you want to also have a mechanism to discover and launch views. If we look at web development its all about resources sitting on a server and you can launch/load a specific resource via a URI (Unique Resource Identifier). This mechanism proved to be a very easy and scalable way of locating views and within a Web Page you can link to other pages very easily. When building WPF applications that are purely content based such a mechanism would really come in handy, and if you think about it MEFedMVVM is all about discoverability so why not support this scenario.

Since this is not really part of the core MEFedMVVM I created an extension that you can use to accomplish this, MEFedMVVM NavigationExtension.

MEFedMVVM.NavigationExtension support both WPF and Silverlight 4.

 

Enter MEFedMVVM Navigation Extensions

The idea is to be able to specify to a View that it can be located by a unique identifier (a string) and then you can have someway of launching that view and render it in some container/host. Something like this

image

And you make the view discoverable by decorating it with this attribute

image

As you can see in the figure above, there are 3 magic attached properties that are attached to the “Invoker”

  • NavigationExtensions.NavigateTo
    • Specify the unique identifier (string) to locate the view. I use a URI format but you can use whatever you like as long as its unique
  • NavigationExtensions.NavigationHost
    • Specify where you want the View to be rendered
  • NavigationExtensions.NavigationParameter
    • Specify a Parameter to be passed to the ViewModel of the View. The reason why the parameter is passed to its ViewModel is because if you are doing MVVM then your View has no need for parameters, its the ViewModel that needs the parameter(after all the ViewModel controls the logic). We will see how you can still cheat and do whatever you like at the end of the day, the parameter can be passed to the View.

So one might wonder how will my ViewModel receive the parameter. This is done by your ViewModel being set as DataContext of the View (if you are using MEFedMVVM to link the View to the ViewModel this happens automatically) and also your ViewModel has to implement the INavigationInfoSubscriber interface. This interface defines 1 method OnNavigationChanged which will pass along the parameter and also give you an instance of the INavigationManager responsible for starting the Navigation.

image

 

Recap

So till now we can

  1. Make a View discoverable by specifying a Unique Identifier
  2. Specify an Invoker and give it enough information on what to render and where to render it
  3. And also specify a parameter to be passed

This pretty much covers the bare basics, let’s get a better understanding of what is a Host and what is an Invoker before we deep dive in more complex scenarios.

 

Host and Invoker Deep Dive

When building the NavigationExtensions I wanted to make sure that you can create your own handlers both for Hosts and Invokers, and what is the best way to do so if not with MEF Smile

There are 2 base classes you need to write in order to create your own handlers.

  • ControlNavigationHost
    • This is to create your own hosting control. Out of the box you get one which is ContentControlNavigationHost (it handles any ContentControl)
  • ControlNavigationHandler
    • This is to create your own invoker for a control. Out of the box you get one which is the ButtonNavigationHandler (it handles any ButtonBase)

The ControlNavigationHost has 4 methods that you need to implement (all method implementation would be usually one liners)

image

In order to make your own ControlNavigationHost discoverable by the NavigationExtensions simple Export it like this

image

The ControlNavigationHandler has 3 methods you need to implement

image

In the implementation you simple have to register to the Event you want and then call the OnEventFired protected method of the base class. here is an example

image

And again to make the handler discoverable you Export it like so

image

Please note: that its up to you how you want the creation policy to be (i.e. If MEF should create a new instance of the NavigationHandler or not but in this case you should always make it NonShared so that for each invoker in your application you have a different ControlNavigationHandler instance)

Apps are usually more complicated, so let’s dive into more complicated scenarios

Before we start going through these scenarios let’s have a look at some interfaces and classes that MEFedMVVM exposes for you to consume/implement

INavigationManager 

image

INavigationManagerProvider

Implement this interface on a class that will be passed as NavigationParameter and you will get injected with a INavigationManager responsible for that Navigation

image

INavigationInfoSubscriber

Implement this interface in your ViewModel to get passed the NavigationParameter.

image

NavigationCommand<T>

A NavigationCommand is just a DelegateCommand<T> BUT it implements the INavigationManagerProvider interface. When used as a NavigationParameter it will hold the instance of the INavigationManager so that you can do things such as Closing a navigation. We will see the NavigationCommand<T> being used in the first scenario below.

 

Scenario 1

Let’s say you have a dialog that shows some settings and when you are done you want to get those settings back to the original ViewModel that “started” the navigation to the Settings screen. Here are a couple of screen shots for such a scenario.

image

In order to do this we need the MainViewModel to expose a NavigationCommand<T>

image

and the Execute handler for this would be something like this

image

We will revisit the code inside the Execute Handler in a bit**…

Now we can specify that the NavigationParameter is this command so that the SettingsViewModel can execute this command when it is done and give us the ApplicationSettings object instance.

image

The Settings ViewModel implements the INavigationInfoSubscriber thus it will get injected with the NavigationCommand that we are passing to it via the NavigationParameter attached property

image

Once the Settings ViewModel calls the Execute on the _onSettingChangedCommand it will invoke the method inside the MainViewModel (OnSettingChangedExecuted) passing the new ApplicationSettings.

**One thing to note is that the MainViewModel is also calling CloseNavigation on the NavigationManager of the NavigationCommand. This is so that as soon as its done applying the new settings the Settings screen disappears.

Download the sample and play around with it to get a better feel of how this all works together (its under Samples/TestNavigation)

Scenario 2

Let’s say you have a sort of Wizard Step by Step UI.

image

In this case we want to chain the Navigation so that the CreateUserProfileViewModel send the UserProfile not to the MainViewModel (the ViewModel that started the Navigation) but to the ViewModel next in the chain i.e. the RenderUserProfileViewModel.

In order to do so both “Invokers” (i.e. the button for the CreateUserProfile and the button for the RenderUserProfile) must have the same navigation “invoker”. You do so by explicitly setting the NavigationHander attached property (this is an attached property that exposes the Navigation handler for an “invoker”).

image

Ok so now we have both “invokers” using the same NavigationHandler; because of this we can register to the NavigatingAway event of the INavigationManager inside the CreateProfileViewModel and pass the data we want to the RenderUserProfileViewModel (which is the NewNavigationInfoSubsciber in the NavigationEventArgs passed by the event)

image

So basically the CreateUserProfileViewModel (Step 1) could pass along data to RenderUserProfileViewModel (Step 2) and you can continue chaining like this one step after another.

NOTE: For Silverlight you instead of using the NavigationExtensions.NavigationHandler use the NavigationExtensions.ChainToElement and specify the other button (this is because there are issues around binding to custom attached properties in SL). This approach can also be used in WPF.

image

 

Download the sample and play around with it to get a better feel of how this all works together (its under Samples/TestNavigation)

Conclusion

One thing I love about this Extension is that it enables you to use View-First approach to MVVM in nearly any scenario. Yes granted sometimes its better to have ViewModel-First approach but in my experience if you can always work using View-First life becomes much more easy because your code is more loosely coupled. In fact this is one of the things I love about MVC and Web in general… Controllers never reference each other, A View has a controller and thats it. In MVVM we tend to complicate things by having Parent ViewModels that have Child ViewModels yada yada yada… just my 2 cents…

This is all still work in progress, it needs more testing from my end to make sure there are no side effects such as memory leaks etc yet feel free to poke around and play around with it. As always feedback/bug reports are very welcome.

Download the code from http://mefedmvvm.codeplex.com/SourceControl/list/changesets

Mole a debug tool that rocks your world!

If you never tried it, then my question is how do you live with yourself Smile Mole is an awesome debug visualizer which you can use inspect any .Net object while you are debugging.

Mole also have some really cool WPF only features such as Visual tree and Logical tree visualization. You can search for a specific object in the object graph… I am not gonna say much more because all this info is already on the Mole site. Go and have a go with it….

Once you go Mole you never go back Smile

http://www.molosoft.com/

Mole 2010 by Molosoft

MEFedMVVM with PRISM 4

Today I was looking at PRISM 4 and how it uses MEF as its DI Container and I thought, wouldn’t it be cool if you could use the 2 together?

Update: Please also check out this post to see how you can use the same composition container for both PRISM and MEFedMVVM so that stuff like IRegionManager, IEventAggregator etc can be injected also in MEFed ViewModels

http://mefedmvvm.codeplex.com/workitem/15391

Why would it be cool?

PRISM brings to the table

- Region Manager
- Modules infrastructure
- Many other utilities and services that you can consume

MEFedMVVM brings to the table

- ViewModel injection in XAML
- Design Time vs Runtime services (so that you can inject design time services when in blend)
- ContextAware services such as IVisualStateManager

Having the 2 working together would be awesome. The question is can they work together?

…teasing… suspense … ok enough Smile

The answer is yes and very easily…

How to do it

In PRISM you need to create a bootstrapper that will basically compose your application. MEFedMVVM also has a sort of Bootstrapper where you can specify how you want to compose the MEF composition. So as such all you need to do is to have your PRISM bootstrapper also tell MEFedMVVM how to do the composition.

Let’s start by creating a PRISM bootstrapper

We need a class that inherits from MefBootstrapper and we will need to override a couple of methods. Here is the code to do this

public class Bootstrapper : MefBootstrapper

{

    protected override void ConfigureAggregateCatalog()

    {

        this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(Bootstrapper).Assembly));

    }


    protected override void InitializeShell()

    {

        base.InitializeShell();


        Application.Current.MainWindow = (Shell)this.Shell;

        Application.Current.MainWindow.Show();

    }


    #region Overrides of Bootstrapper


    protected override DependencyObject CreateShell()

    {

        return this.Container.GetExportedValue<Shell>();

    }


    #endregion

}

Now lets enable MEFedMVVM

In order to do this we will simple need to implement the IComposer interface from MEFedMVVM and then return the AggregateCatalog property (that is given to us by PRISM)

#region Implementation of IComposer (For MEFedMVVM)


public ComposablePartCatalog InitializeContainer()

{

    //return the same catalog as the PRISM one

    return this.AggregateCatalog;

}


public IEnumerable<ExportProvider> GetCustomExportProviders()

{

    //In case you want some custom export providers

    return null;

}


#endregion

In this case we will return null as the GetCustomExportProviders. This is a feature used if you have some custom ExportProvider you want MEFedMVVM to use.

The last step (which is the actual line of code to enable MEFedMVVM) is where we tell the MEFedMVVM LocatorBootstrapper to use this class as runtime composer.

protected override DependencyObject CreateShell()

{

    //init MEFedMVVM composed

    MEFedMVVM.ViewModelLocator.LocatorBootstrapper.ApplyComposer(this);


    return this.Container.GetExportedValue<Shell>();

}

As you can see I have put that line of code in the CreateShell method so that the Composer is applied as early as possible so that all views can use MEFedMVVM.

 

Now you can start using MEFedMVVM as you would in a normal project… For example in the Shell you can say

<Window x:Class="MEFedMVVMAndPRISM.Shell"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="Shell" Height="300" Width="300"

        xmlns:mefed="http:\\www.codeplex.com\MEFedMVVM"

        mefed:ViewModelLocator.NonSharedViewModel="ShellViewModel">

and the ShellViewModel would be

[ExportViewModel("ShellViewModel")]

public class ShellViewModel

{

    public string Text { get; set; }


    public ShellViewModel()

    {

        Text = "Hello from the ViewModel";

    }

}

Of course here I am not really leveraging MEFedMVVM capabilities, yet the purpose of this post is not to show those capabilities but to show how you can use PRISM and MEFedMVVM together and take what is best from both. To read more on MEFedMVVM visit the codeplex site.

I create a small sample project to showcase both PRISM and MEFedMVVM working together.

Download sample

Capture