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

Windows 8 thoughts after a day at BUILD 2011

First impression can only be described with one “word”; WOW!!!

So Microsoft unveiled how they are planning to change the world. Why such a big statement? Am I exaggerating? I believe I am not. We live in a world of desktops and laptops today; yea we see some tablets that introduce touch but is it mainstream? are there a replacement to your desktop/laptop? I guess the answer is, No it is not, in order to do such a radical change you need to “push” hardware manufactures into producing these devices mainstream. mmm I wonder who could be that company that can have such an influence? By committing to touch and in fact developing Windows as a touch-first operating system, Microsoft will drive hardware manufactures to give us the touch devices and change how we interact with software today. And yes this is what has been announced at BUILD.

What does touch mean to us? We need to change our way of looking at software, it will not be OK to just have buttons and textboxes; it will not be ok to press a button and your app stalls. Touch is a much more direct way for a user to interact with your application and if one disregards this then that application is destined for failure. I really enjoyed the keynote session from Jensen Harris. He talked about the user experience and how us developers have to embrace the new ideas and concepts coming with Metro style apps. He talked about how Windows 8 is alive, how Windows 8 is personal. These 2 factors create (and yes you might think I am crazy but still I will say it) an intimate relation between you and your device. Windows 8 gives you that “home” \ “friend” sort of feel.

Jensen also made a very good point about apps. Without apps what is Windows 8? without apps there would be no tiles, no tiles empty OS. Even when you look at Metro style apps, you can see how Windows is all about apps… Apps are now chrome-less, your app uses the stage that Windows 8 provides; your app is now the centre of attraction. Windows 8 will also introduce an App Store, this will make your application easier to be discovered and installed by users. App store is probably one of the biggest opportunities for us developers because it gives us a reach of millions of people that will be running Windows 8.

Ok so lets see at what we have till now… We have | 1. a new OS | 2. which is touch first | 3. and will bring new hardware | 4. and amazing new apps

This is all awesome, but let’s not miss the number 1. Its a new OS and with Windows 8 besides many new features (and yes there are many), new concepts are born. Features are very important but concepts are what really change how Windows 8 differentiate itself from other OSs.

One of the concepts Windows 8 brings is Contracts. These are different ways how you application can contribute to Windows; its a way how Windows opens up and let third party applications interact with each other. Some examples of contracts are the Picker contract, Search contract and Share contract.

Picker Contract is a way how you can register your app with Windows and start exposing your data to other applications to consume.

If your application implements the Picker contract whenever an open file dialog is started the user can choose files from your application just like it can choose a file from the hard disk. So for example facebook could have an app that implements the Picker contract and any other application / the user can pick a file from facebook just like it can pick a file from the file system.

Search Contract is a way how you can expose your data via the Search charm (charms are the right hand menu items in windows). If you implement the Search Contract then whenever the user executes a search from the search charm your app will be invoked to contribute to the search results. Think of this as 1 standard way how the user can search.

Share Contract is a way how you can share a piece of information from your application to another application. The application exposing the info would be the source and the application consuming the info would be the target. Imagine the share contract (which is a charm just like search contract) as a sophisticated clipboard. So for example let’s say you are in Paint and you draw something, if paint implements the source share contract it can expose the image you drew. The user can then click the Share charm and all apps that implement the target Share contract can use that data. Just like the screen shot below.

My personal favourites are the share and the picker because those 2 just add so much to Windows applications…. With these charms we can have applications that reuse each other and that can efficiently interact which each other seamlessly.

Besides these there are tons and tones of other features, not to mention tiles, notifications, surprisingly enough keyboard shortcuts, and many more…

Last but not least what about us developers? What is this new Windows Runtime everyone is talking about?
Well in this blog post I will not do a deep dive but here is a summary. Windows Runtime (or as they call it WinRT). WinRT is the API for Windows Metro Style application (aka Immersive apps). WinRT will support

XAML UI definition
– with C# / VB.Net
– with C++

OR

HTML (with some custom attributes) UI definition
– with Javascript

WinRT

WinRT is written in native code but it exposes the API with metadata files (under C:\windows\system32\WinMetadata) which is very similar to MSIL (in fact you can open these files in ILDASM) so that it can project the APIs to the other languages i.e. JS, C# and C++. Each language has a different runtime so C# still has a CLR running and JS has a runtime that I forgot its name, I think its WinJS  Smile You can also expose libraries to WinRT so that they can be consumed by another language (there is a new output type just like Class library but called MD library). For example you write a library in C++ and it can be consumed by C# or vice versa (or even JS). There are some rules for doing this such as collections must be of type IList<T> (in C#) etc…

WinRT is all about performance and making apps “fast and fluid”. In fact most of the WinRT API are expose Async. WinRT does not use GDI, it only uses DirectX for rendering.

All in all WinRT is something impressive, its what we UI developers where waiting for to build the next generation of applications… I will deep dive in WinRT very soon so stay tuned Smile

Conclusion

So what is really coming at out?? its not just another version of Windows, Its new hardware, New way of interacting with devices, a whole new set of amazing apps. For me, yes, that is enough to say, Windows 8 changes everything!

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

ICommand discovery with MEF

Sometimes you are in ViewModel X and you want to execute a command on ViewModel Y. You do not want to link the 2 because of some constrains that that might impose. How can you leverage MEFs capabilities to overcome such a situation?

Easy have the ViewModel Y expose the command as a property just like you would have it for binding from the View, but also add an Export attribute on the property and give it a name

image

 

Now from ViewModel X simple imports the ICommand by specifying that same name (yes you can have the string as a constant, also I would advice to use constants to avoid conflicts in strings)

image

 

MEF will automatically get the command from ViewModel Y into ViewModel X for you. This works very nicely with MEFedMVVM since MEFedMVVM resolves all ViewModels via MEF thus you do not need to do anything to resolve the ViewModel or anything. You simply decorate the properties for Export and Import and viola you can start drinking beer Smile

Happy coding Smile