DCSIMG
Ariel's Remote Data Center

April on Israel Dot Net Developers User Group

Posted Apr 17 2012, 01:39 AM by Ariel Ben Horesh  

This week we are helding our annual monthly session. It’s a bit odd, but Erez Pedro and myself are going to be the speakers Smile.

The session name is “Developers Are from Mars, Designers Are from Venus” it has 2 parts, one by Erez an amazing designer and UX expert targeted to designers and myself targeting developers. Our goal is the same, narrow the gap between the two group especially when doing XAML work.

If you are a developer, I’m going to talk about the MVVM pattern, and it this session focus, why is it good for designers. I’m going to show common challenges such as ViewModel Data, Visual State Manager, etc.

After that we are going to talk about the tool, Blend, and talk about what to expect as a developer with blend output.

in our final part we are going to discuss tips and performance issues worth to remember.

Does that sound good to you? Interesting? boring? it’s not too late change my agenda, so let me know Smile.

Here is the full description:

Developers Are from Mars, Designers Are from Venus

Today every application big or small needs to compete on a highly demanding field of the User experience. Touch based devices; crisp beautiful displays all effects the complexity of those User Interfaces. Furthermore it is now common to witness how UX/UI people are participating on every aspect of the development phase.

In this session we will try to mitigate the challenges of developers and designers working side by side, by showing methods and best practices especially when using XAML based technologies.

On Wednesday 18st  April 2012

17:30 - 18:00   Assembly
18:00 - 19:15   Designers: How to work with developers
Erez Pedro

19:15 - 19:30   Break
19:30 – 20:30 Developers: How to work with designers
Ariel Ben Horesh

About the speakers:

Erez is a senior UX architect with a unique perspective of user experience that combines knowledge and expertise covering all aspects of the user experience design. He utilizes a variety of user centric analysis & design methodologies to design experiences that optimize users’ situation awareness and usability. This expertise is the outcome of 15 years of UX design experience including work in North America and many years in Israel. Erez is an expert in: Human factors, interaction and information design, as well as in implementation and development of rich client technology. He is experienced in WPF & Silverlight client technologies.

Ariel Ben-Horesh is a software architect and expert in Microsoft technologies. Ariel is a Co-Founder of CodeValue. Ariel is an expert in modern UI software design, using WPF or Silverlight with Prism.  Ariel serves as a Senior Consultant and trainer at CodeValue. He is currently consulting in various enterprises in Israel and worldwide, architecting and developing RIA and Smart Client-based solutions.

Register Here: http://idndug-apr-2012.eventbrite.com/

Finally big kudos to our sponsors Telerik

telerikLogo-web-174x69px_thumb3

And JetBrains.

and our new addition Pluralsight

Thank you for you support!

CodeRetreat – You can do it too

Posted Mar 20 2012, 06:20 PM by Ariel Ben Horesh  

 

Last Friday we had held CodeValue 1st CodeRetreat, for the unaware, CodeRetreat was created by Corey Haines (which had become a frequent visitor in this blog Smile).

It is safe to assume that most of you have never heard of CodeRetreat, it is a day which you concentrate on skills that usually you are neglecting or putting aside because it slows you down when you just want o get things done. Don’t misunderstand me, I’m the first to tell you that usually that exactly what you need to do. That why the whole purpose of this day is to sharpen skills that when you code you real stuff it will be less an hinder, it will be much more on the flow of your development, and by that I mean testing, design, etc.

In that day you focus on paring with other people, focus on perfect design and code. During the day the facilitators might throw in some challenges so you can thing out of the box for a few moments. More information on CodeRetreat on this site http://coderetreat.com/.

Sounds good you may wonder, but where do I participate in such an event. Here you can checkout CodeRetreats near you.  Sadly in Israel while there were a few CodeRetreats done (also participated on the global day of CodeRetreat, where CodeRetreats where held around 1oo countries around the world) there are no much of facilitators in Israel. Corey had facilitated a few in his last visit to Israel, but that it. Shay Friedman and myself decided not to wait to no one and went over the format and facilitated our first event to CodeValue employees. I hope we would be able to held a public event soon enough, if you are interested please contact me.

The Day was a blast, honestly it is always fun to gather a bunch of super smart people and just pair with them, Shay and myself were a bit surprised by the level and threw at the participants every challenge we knew Smile. Another word of advice if you want to facilitate such an event to your company like we do, feel free to contact us and we will help you from out really vast experience – It is really simple and don’t worry about making a mess, you need to do a lot of damage to make this day unenjoyably. So you can do it too.

If you are still not convinced hear me out, I believe that such events are defining your organization culture (organization can be your team, your department and your company), if you would like a culture where people actually work together and trust each other, actually know of the other team mates abilities and how they think, if you would like a culture where people aspire to learn and learn from each other with no shame, if you would like a culture where people hone their skills all the time and are just happy to improve as professionals developers. When I set out into a new way and started up CodeValue with my friends, this is exactly the culture I wanted in this place, while each of my colleagues is a really gifted developer, there is a huge difference between a group of individuals and a team of people all trusting and helping each other.

And while I could do that on a very limited way at the previous places I worked before, CodeValue is a different story, no comparison at all, and this is why I’m so happy I went through that path.

March on Israel Dot Net Developers User Group

Posted Mar 20 2012, 03:26 PM by Ariel Ben Horesh  

Tomorrow you will get the chance of hearing everything you wanted to know about AOP, Aspect Oriented Programming.

Aspect Oriented Programming (AOP) helps us deal with application-wide concerns by adding a high level of reuse to the traditional OOP framework.

In the meeting Dror will explain what AOP is all about and how it can be implemented in .NET using simple methods and industrial grade frameworks to improve the developer's everyday work by using aspects.

- What is AOP and how it improve (instead of replace) the existing code

- Using high order functions to implement AOP

- .NET AOP solutions – from simple hacks to full-fledged frameworks

- Real world use cases where AOP really shines

Thank you Dror for taking the time and investing back to the community.

Register Here: http://idndug-mar-2012.eventbrite.com/

Now, I want to say big special thank you for Telerik

telerikLogo-web-174x69px_thumb3

And JetBrains.

That for the first time will be supporting our group with various licenses worth thousands of dollars.

Don’t forget to register, and see you there.

Ariel

Pimp my Visual Studio 2010

Posted Feb 29 2012, 10:20 PM by Ariel Ben Horesh  

People often asks me which customizations do I use in my Visual Studio.

I think it’s fit that on the day Visual Studio 11 Beta is out I will be sharing my experience with VS2010.

For long time I was captured in a misconception, you shouldn’t customize your IDE, otherwise how do other people are going to be comfortable when you need them to to sit on your chair.

In some ways that habit is hard to quell, proof of that is that I still pretty much use the default VS color scheme (and Yes I’m aware there are better out there), but it’s not that I love white so much, when I used Delphi I stuck to the classic Yellow on Blue color scheme (image below for the young people here Smile)

But nothing is more important than your own productivity. That exactly what I tried to do, reduce friction and enhance my productivity as much as possible.

Note about Resharper, I use this tool a lot, if you care about productivity, you should use it, if your company doesn’t have a license, convince them, it pays back it’s value after a week.

1,2,3 there’s no mouse.

How one becomes more productive, he leaves the mouse alone. Every time your hand leaves the keyboard and go to the mouse is a moment lost, aggregating those moments pile up to be a huge time waster.

First, Remove all toolbars, yes, you heard me, remove all of them. You don’t really need them. I admit that beside the buttons there are some advantages to them when displaying current state, but all in all it’s just not worth it, think of it, how many of the buttons showing up on your visual studio toolbars you really use all the time, 20%? While you are at it counting, take a mental note, do they have a shortcut mapped (most likely they do) open up an excel spreadsheet and write it down for you, it is going to be you friend for next 2-3 weeks, a cheat sheet, every time you forget a keyboard shortcut, look and next time use the mapping. Repeat.

Another mental note, every time you use the mouse to do something, ask yourself, can I do it better? if yes add it to the excel and next time try to use the keyboard to do so.

After a while you begin noticing that there are operations you use all the time, for example for me it was creating a folder in a project, or opening Windows Explorer from a selected item in the solution explorer, that when it’s starting to get fun as there is no keyboard shortcut mapped to it. But this is not what is going to stop us? Open up Visual Studio Tools –> Options and there Keyboard you can pretty much map any command available to Visual Studio.

Here are my custom mappings, feel free to change them to whatever feels comfortable to you.

  • Build current selected Project – CTRL + SHIFT + X (I wanted something near to CTRL + SHIFT + B, but CTRL + SHIFT + C is already being used (it iterate through the clipboard ring, you should know that!)).
  • Add Reference – CTRL N + CTRL + R.
  • Open in Windows Explorer – CTRL + P, CTRL + P
  • Create new Folder – CTRL + N, CTLR + N
  • Increase Line Indent - CTRL+ K ,CTRL + ]
  • Decrease Line indent - CTRL+ K , CTRL + [
  • Resharper Find Usage – CTRL + R, CTLR + F

Those are few examples to get you running.

Immediate window is your friend as well (CTRL + D,CTRL + I), opens it up or focus it, type “>” and than you can call every command of VS. I use it a lot to close all windows. I just type “>CloseAll” I will get intellisense as I start typing and bam, didn’t use the mouse Smile.

 

Real Estate, that’s the secret

Do you know that most users have the Toolbox pane open all the time? why because it’s the default, do you use really use it? do you really use it so it should be open all the time?

Start by removing every pane that you don’t use frequently, Class Viewer, Toolbox, Server Explorer, etc.

Do you see how my VS looks like, notice something interesting it mostly an editor, that what we need to do, crank up code, align things symmetrically, remove distractions.

VSForBlog

More VS tweaks

It’s no secret that VS is an hungry resources beast, I managed to improve performance by making some small tweaks.

  • Disable the Navigation Bar – It’s a nice feature, but it require the mouse to browse through, I prefer using resharper ALT + \ and type the member I’m looking for. It’s saves you both time and real estate.
  • Disable TrackChanges – it’s a feature that shows you a color near every line you have changed. It’s nice, but I want speed, it is considered a feature that damages performance.
  • If you are a WPF/SL developer, heed my word, disable the Visual Editor, open in full XAML View option is not enough. right click on a xaml file “Open With…” choose an Source Code (Text) Editor, make it the default, don’t you worry you still have intellisense, in the rare cases I need to actually see the xaml I write, I just open it up in Blend. Editor in the background is responsible for many of VS crashes and slowness.
  • If you ever found yourself waiting for “Loading toolbox content from package. It’s a known bug. just remove that Guid from the registry. Do not be passive, hunt everything that goes in your way to be more productive.

Last note about Visual Studio 11

I admit my first reactions to the images coming out from the VS blog were negative, but I am willing to give it a fair chance before I draw a verdict, one thing for certain, the principles described in this post will remain relevant to the next version as well, perhaps even increasing in importance.

I will be fun to revisit this post after a while with VS11.

Do you have a killer feature you believe should be added to this list? Share it on the comments.

February on Israel Dot Net Developers User Group

Posted Feb 20 2012, 07:48 PM by Ariel Ben Horesh  

Hey all,

A few weeks ago I had the pleasure to meet Corey Haines, an amazing man, full of vision and the abilites to fulfill them, when asked how one becomes a better programmer, he said to me, go to every User group you can find, in any language, in any field.

Listen to Corey, don’t miss this opportunity to gather with your fellow programmers and enjoy their company, you might learn a few things and meet new friends. It might going to be what it takes to move you forward.

Now, enough chit chat, this month meeting will be held in two days, and this time we are going to have two exciting sessions:

Windows 8 - Understanding Metro UX

The Metro UI is a new User Interface designed for Windows 8. But there's more than beautiful fonts and sleek graphics to the Metro UX. Aimed for both PCs and tablets, Windows is undergoing the biggest user experience overhaul since Windows 95. It will change the way users interact with it, and it will change the way we developers think about it. In this session we'll explore the Metro UX and its implications, and take a glimpse at the underlying technological concepts.

Visual Studio Debugging Tricks - in BugAid and Beyond

While most Visual Studio .NET developers use various tools to improve their productivity when writing and refactoring code, there is a noticeable lack of useful tools in the realm of debugging. In this session, we'll explore a new tool called "BugAid for Visual Studio" that enhances the debugging experience by letting you visualize, search and compare live objects data when debugging a C# application. We'll also look at some of the more advanced features of the Visual Studio debugger itself.
On Wednesday 22nd February 2012

17:30 - 18:00   Assembly
18:00 - 19:15   Windows 8 - Understanding Metro UX
Elad Katz

19:15 - 19:30   Break
19:30 – 20:30  Visual Studio Debugging Tricks - in BugAid and Beyond
Omer Raviv

About the speakers: 
Elad Katz
is a senior .NET architect at the Sela Group. He specializes in ASP.NET MVC, HTML5 and WPF/SL, with more than 10 years of experience in the industry in various .NET technologies.

Omer Raviv is a co-founder of BugAid Software, an entrepreneur, and a passionate C# software developer.

Thank you Omer and Elad for taking the time and investing back to the community.

Register Here: http://idndug-feb-2012.eventbrite.com/

Now, I want to say big special thank you for Telerik

telerikLogo-web-174x69px

And JetBrains.

That for the first time will be supporting our group with various licenses worth thousands of dollars.

Don’t forget to register, and see you there.

Ariel

How to implement communication between Silverlight and the HTML host.

Posted Jan 29 2012, 11:41 AM by Ariel Ben Horesh  

A question about intercommunication between Silverlight and the HTML host has been asked in the Israeli MSDN forum.

Since I’ve already implemented it once in a project, I believe I can extract the great info already exist in the MSDN documentation to a more direct how-to.

Let’s begin.

  1. Create a class called JavaScriptBridge
  2. Each method that you would like to be exposed to the HTML host, thus be possible to get called by JavaScript you adorn with [ScriptableMember] attribute.
  3. [ScriptableMember()]
    public void DoSomething(int a, int b)
    {

    }

  4. Inside the App.xaml.cs, on the Application_startup event handler, register the an instance of the bridge
  5.         private void Application_Startup(object sender, StartupEventArgs e)
    {
    this.RootVisual = new MainPage();
    JavaScriptBridge javaScriptBridge = new JavaScriptBridge();

    HtmlPage.RegisterScriptableObject("bridge", javaScriptBridge);


    }

  6. We are done with Silverlight side, now we move on to the HTML host, locate the aspx file (usually) that contains the Silverlight object. In this page you will notice that it is represented as an <object> tag. Insert an event handler for the onLoad event of the object.
    <param name="onLoad" value="pluginLoaded" />
  7. Also add an input button for testing the interface.
      <input id="Button1" type="button" value="Test" 
    onclick="test()" />
  8. Implement both event handlers:
         var silverlight = null;
    function pluginLoaded(sender, args) {
    silverlight = sender.getHost();
    }

    function test() {
    if (silverlight != null) {
    silverlight.Content.bridge.DoSomething(10, 10);
    }
    }
  9. Hopefully, now we look back and appreciate how easy it is to mix those two worlds Smile

Ariel

Under new management

Posted Jan 18 2012, 07:12 PM by Ariel Ben Horesh  

I’m happy to announce that I am to join forces with Shai Bar-Lev and help manage the INDNUG – Israel Dot Net Developers User Group.

Today is my debut appearance at the group meeting, for those of you who don’t know this group roots are from a long time groups such as VB .NET user group. This group covers quite a wide range of areas, so it can appeal to any .NET developer out there.

For exmple today, is a talk about SQL Server 2012 for .NET developers by Shy Engelberg

IMG_0491

Now dear followers, I encourage your to contact me in any way possible, via this blog, twitter (@arielbh) and tell me, what do you want to see in this group, or whether who do you want to hear talking about juicy subject.

Ariel

“Hacking” through Prism regions (or when to cross the lines with Prism)

Posted Jul 19 2011, 05:51 PM by Ariel Ben Horesh  

If you’ve been following this blog long enough, you should know I’m an avid prism fan. Most of my projects I am making use of Prism or Composite Application Guidance. This is not a post for learning Prism, but to provide a solution, not so straight-forward for a rather straight-forward problem.

I must add that that rarely I had had been pushed to extreme solutions such as I show you here. For most scenarios you are pretty much good with the default behaviors.

In my scenario I’ve been using a control as a region. This control requires that when adding views to it, it must be done with RegisterViewWithRegion extension method. The concept is simple in contrast to the “regular” AddToRegion method. RegisterViewWithRegion doesn’t requires the region to be initialized, yet. When the region becomes available than those views who had been registered will be called via delegates and added to the now ready region.

A regular usage of RegisterViewWithRegion is as follows:

public void AddView(object view)
{
    RegionManager.RegisterViewWithRegion(RegionNames.MainRegion, () => view);
}

A common scenario is to allow clients to "readd” a view, but instead of duplicating it, just put into focus, or in Prism concepts, activate the view. This is were things get messy. For an example let’s simplify it a bit and for the following wrong code snippet let’s just do nothing when the view already exist.

public void AddView(object view)
{
    if (!RegionManager.Regions[RegionNames.MainRegion].Views.Contains(view))
    {
        RegionManager.RegisterViewWithRegion(RegionNames.MainRegion, () => view);
    }
}

Why is this code bad? if have a reason to use RegisterViewWithRegion, most likely it fail to check if the view exist if the region is not ready yet. So we need to move this check into the action delegate, to be called only when the region is ready.

public void AddView(object view)
   {

       RegionManager.RegisterViewWithRegion(RegionNames.MainRegion, 
           () =>
           {
             if (!RegionManager.Regions[RegionNames.MainRegion].Views.Contains(view))
             {
                 return view;
             }
             return null;
           });
   }

Last code looks formidable but there is a catch, when we returning null, it is actually adding a null view to the region. In my scenario it’s really an undesired side effect of the whole situation. It is worth mentioning that a RegionAdapter doesn’t solve this issue completely, when you react to a view being added you can decide to not do  anything but than the underlying control is out of sync with the views collection as the views collection will keep those nulls as views. While it might serve for some purposes, I haven’t thought it is clean enough. Also it kept me checking for nulls every time I iterate over the region views.

So luckily, the prism source code is open for grab, though I wanted to avoid altering the source code by all means, I’ve followed the key players involved when you register a view with RegisterViewWithRegion.

To make a long story short one need to dwell into Region Behaviors, in specific responsible for the scenario above is the AutoPopulateRegionBehavior. Soon enough I could identify the culprit:

public virtual void OnViewRegistered(object sender, ViewRegisteredEventArgs e)
       {
           if (e == null) throw new System.ArgumentNullException("e");

           if (e.RegionName == this.Region.Name)
           {
               AddViewIntoRegion(e.GetView());
           }
       }

When we call e.GetView() it will call our delegate, if GetView returns null than it will add a null, no brainer. Fortunately the Prism team did a good job, and provided us a mean to change those behaviors on many levels, by making this virtual I could’ve created my own version of AutoPopulateRegionBehavior that avoided adding nulls. I inherited from it and overridden this method.

Last piece of the puzzle is the making the configuration  of the behavior factory to use my version instead of the one coming from the box. This is done actually rather easily by overriding the bootstrapper ConfigureDefaultRegionBehaviors method.

What I ended up doing but didn’t like so much is copy pasting the original implementation of ConfigureDefaultRegionBehaviors  and changing it to use my own AutoPopulateRegionBehavior because the Factory didn’t give me a way to replace an existing behavior. Perhaps the Prism team can make this available in the next version.

Ariel

Wrapping up MIX11 (Part 2)

Posted Apr 20 2011, 10:17 PM by Ariel Ben Horesh  

In Part 1, I’ve placed down the background for this post series, I’ve written down my feelings towards the session at MIX, but what about the Keynotes?

Keynotes

In this MIX we had 2 keynotes, one was concentrated around IE10 and HTML5, the other was about Windows Phone 7, Silverlight and Kinect.

It’s very easy to compare them, the first one was non-imaginative, bothersome and at times offending, while the other one was direct, happy and fun.

Before really trashing the first keynote, I want to say that it did have some very interesting news, showing a windows version running on ARM processor, why is that important I think I will get into this at our third part of this series. The sad thing about it, when I was watching it I was not impressed, Steven Sinofsky just showed me the My Computer properties of a computer, it just didn’t had any WOW effect, and while I was engulfed in negativity I had almost missed it’s true meaning.

I also liked Orchard, from the stuff I’ve seen in the keynote it looks promising but in order for it to become a WordPress competitor as it is technically aspires too, Microsoft lacks a very important thing, Hosting, and it is quite surprising, with all those Azure nodes running around that I’m not sure are 100% occupied all day long 24-7. I mean if WordPress can offer free hosting for blogs, so can Microsoft. Actually I’m expecting much more than Microsoft, a free hosting for Orchard blogs is a minimum, but imagine you are writing an app with WebMatrix and you got to the last step, which is publish, what do you get now? a list of available hosts service which do cost money. For WebMatrix’s targeted audience which are mostly, avid amateurs, it is actually a showstopper, well even though it is not really tons of money, it makes one stop and question himself, am I serious with it so I should invest money in it. Hello, if WebMatrix or even Visual Studio (express) is free, why can’t I put my little tiny, WebMatrix app out there. More than that from a business perspective it makes sense, offer free host for little sites, support SQL CE but when one need to scale up either on size or capabilities than please show him the way towards a better hosts that offer more functionality, hell even offer Azure, and why not, why can’t it be the infrastructure for such endeavor. Not only it will not kill competition but make the eco-system even better.

So that was actually my positive feedback, I have also some negative feedback. I don’t know how to say it, I’m tired of the IE vs Chrome showdowns, not just tired, even offended, it’s just like mocking our intelligence, do they really think we are that dumb? It reminds me that once upon a time when Bing was out of the door and suddenly there was a competition to Google’s Search engine, presenters in Microsoft Israel’s events where encouraged to use Bing instead of Google, it was artificial and awkward for some presenters (“In case you wanted to further explore it, Google it, errr Bing it I mean” followed by embarrassed chuckles). I was “really” surprised that IE had kicked the crap out Chrome, really I was sure that in it’s own conference Microsoft is gonna show us IE being humiliated. So if results are expected from the start, the only interesting thing left is to watch what rigged environment or in what specific tests those planning this Keynote have chosen to show us. I haven’t been to any Google’s conference but I’m pretty sure without even knowing that they don’t act the same, and why should they? if you are certain of your own product’s supremacy you don’t need to stoop so low. Not to mention that those tests were not really fair, from several reasons: first it is not surprising that you take GPU accelerated browser and compare it with one which is not configured to use the GPU by default (at least for now). Second you are comparing your next version browser which will only see daylight in a few more months with today’s competitors, Perhaps compare IE10 with FireFox vNext or Chrome 1000 or whatever version they will reach in a few more months, but you can’t. So I’ve a perfect solution for you, why not compare IE10 against IE9. It actually make sense, show us how better you make you own products evolve, this display of confidence, and it is perfectly reasonable IE10 will be better than IE9 there is nothing wrong with this message. Another think I can make jokes on Chrome rapid release cycles but you can’t, I actually think that by using this approach the Chrome Team have better granularity for adding more support from the HTML5 spec as it shapes in front of our eyes. You can also make jokes on the revisions of parts of the HTML5 spec (or Sockets in that case) but truly, it is not smart, that the way it goes, stay in the game and be agile.

One last message, I hope someone in the IE team listens, I going to say more in the next part, but for now, IE team hear me out, Lose your dependency on the Windows platform. Yes you heard me right, Am I nuts? Have you ever met a guy who said to you, I must use IE so I’m going to prefer a Windows license over other OS?

Staying available only for Windows is getting down with the ship. Perhaps during The First Browser war it made sense, but today it is much more heterogeneous than it was back than. I guess this dependency was the reason Netscape was obliterated, but times has change. Just count the MacBooks around you, all this market is non-existent for IE. I guess at first it’s going to be like having a good look in the mirror after a long time and discovering you have gained weight and dear god aged. MacBooks now are a fashion statement, many people immigrate from Windows for MacBooks, those that still used IE back than, will just go over to the competitors and tell you a secret, even when they will be on Windows, they will not fast be coming back. Because those browsers are all damn good, and as IE showed us back than most users stays with the default if it is good enough, only when IE started to suck people moved to other Browsers on Windows, so I’m used to Chrome, guess what I am going to use on my new Windows machine, and why not I’ve my bookmarks synched automatically for me, it is quick and I like the UI.

So IE lose your fixations, love. Ariel

The second keynote was much better. Scott Guthrie did a hell of a job, when they are putting some miserable guys talking about their apps and almost shitting themselves, you can really admire how good he is when on stage. Memorable moment was when Scott showed an “hidden” feature of the MIX app for Windows Phone 7 where there is a 3D model of himself. And while touching himself Scott undeliberately(?) zoomed in to his figure crutch, he sounded so embarrassed, if it was acting, I’m applauding for making himself look so embarrassed, and if he was embarrassed than I’m applauding for him being so genuine, either way Scott is winning. Even the Blue Angels scene while weird (Front end homepage with HTML5 video and then drills down Silverlight) was enjoyable and perhaps that was the thing, I even showed my non-tech girl a few highlights from that keynote, and what not to like? the Kinect stuff were inspiring (World-WIde-Telescope) and funny (Wall Panic 3000). Another thing worth noting is the direct line Joe approached the audience while explaining, no apologizing, about all the wackiness of the Windows Phone 7 Update story, well when I was still negativity I thought this will not happen to Apple, after that I come to appreciate it very much, and also the new features look awesome, I waiting for the time when I can put my hand on a WP7 piece.

Stay tuned for Part 3.

Ariel

Wrapping up MIX11 (Part 1)

Posted Apr 20 2011, 10:03 PM by Ariel Ben Horesh  

As the dust settled over MIX11 and Las Vegas stopped wasting money out of hard earned lines of code being typed by dozens of developers, I think it is safe enough we can start drawing conclusions.

While on the surface everything is shiny and Mix with its’ extravagant location and many spoils that really keep you entertained and wishing it will never end, and really, “Free” food and drinks, Occasional prizes and giveways that keep you going forward with technology (PDC09’s Notebook, PDC10’ Phones and this year Mix Kinect), Sessions all day to peek your intellectual interest, Parties at night (well at least till 1AM), and the best part, meeting with People that usually you are miles away,and now understanding that if they are nice on twitter than they are as nice on reality, you just can’t fake it for so long. So a conference such as MIX is actually a huge tweetup. I’ve spent all my phone’s battery to refresh my twitter stream relentlessly. During keynotes it was in full harness when the attention of everyone is on the same thing and the side chatter of twitter was am unlimited well of impressions, comments, witty remarks, sarcastic remarks, that often of not were as interesting as the real thing going on in stage.

While the official announcements of MIX had yielded low bounty, I found myself beginning to wander about what was NOT said and where this train is really headed.

A domestic flight Back from Vegas to Philly where I had only twitter access free wifi had resulted with me firing speculations and ideas all over the place,some were silly, or absurd, but who knows it Vegas I might have hit a jackpot or two Smile.

For those I’ve flooded their Feed Stream I apologize, but I’m going to repeat some of those absurd ideas here.

Sessions

But before jumping into my own conclusions, you might wonder, where are my sessions impressions and summaries? I did promise to live blog on twitter.

First my algorithm of picking sessions is favoring high session level and disfavoring areas I already consider myself proficient. Second, I’ve almost didn’t attend WP7 sessions, while the emulator is good and it is getting better, it still less appealing to me when I don’t have a real phone at hand.

But don’t you want to announce that RIA services is available to JavaScript clients (and btw, not WPF), just spread this great piece of news with the world? No. It’s Booooring. You can go and read dozens of those blog posts till you have your fill, or much better download them and watch them for yourself. As it appear I just couldn’t see all. No more than you can. I’m going to watch most of them though, because the most important messages were either subtle or unspoken at all. I want to make sure I’ve not missed something important to my analysis.

But still. how were the sessions you did attend ? They were OK. Just OK?. Yes. Why?

In almost every session I’ve been attending it contained major flows, such as level was not right, Pace was too slow, too much less-important content, too much slides, Code in slides lose its effectiveness unless you show me it running in Visual Studio or your favorite IDE, and it’s not a contradiction with too much information, this is exactly the information I want, I want to see you use it in Visual Studio, because this is what I’m going to do tomorrow, I’m going to open up Visual Studio and try the Canvas element of HTML5. If you don’t show me how to get there, than I’m back to square one. On the other hand some where demoing too complicated code, @damianEdwards had implemented a Comet, parking requests with HTTP Handlers to be used with jQuery, ambitious but the message got lost with all the unnecessary details of writing it. Forgive me for saying but if I need now to implement 3D for my next silverlight project I’m going to vaguely remember the 3d engine execution flow, no more, and I understand the guy presenting this session, that engine his is baby, he loves it and proud of it, and thinks it is important, well for an 1 hour session it is not.

Some sessions were not executed good enough or weren’t as tight as you might expect from this high-end conference. In this regard I’ve passed down popular sessions such the HaHa shows (Hanselman and Haack) and my dear friend @lbugnion with his MVVMlight talk, sessions that are usually so well executed that could have lifted my overall impression, but I’ve left them to viewed later on Video.

So, not a single session you liked?

I’ve liked the Knockout.JS session by Steven Sanderson, which unfortunately I don’t have his twitter handle, not sure that he got one. It was well executed, clear and concise, Pace was perfect; not too fast you can’t follow, not to slow you got bored, it was packed with goodies and the message was clear. it also showed you the outer scope, I can now go and open my visual studio and by following this session I will know what to do, because it is there, than I can just go and explore it further. I am urging you to go and see it for your self, it is just 25 minutes. Hold on. 25 minutes you say? Yes. it was a mini-session. Perhaps that was the key. Steve planned for a 25 minutes session, he knew the message got to be clear, he knew he had limited time to show what is important, and top that all he didn’t just show fragmented pieces of functionality, you could just saw the whole full picture and how everything connects and relates, but this I credit Steve for executing this so well. And while Knockout.JS is his baby and probably contains some neat stuff in its internal he resisted the temptation to explain how it works, it just showed it working, with Visual Studio at hand and code, just the way I like it.

While my friend Shay Friedman (@ironshay) disagrees with me on this point, I think that keeping sessions short helps in keeping on the presenter mind that he needs to deliver fewer messages and make those few perfect, also while Steve performed extraordinary, it encourages me you don’t have to be Hanselman or Guthrie or even the colorful Word Bell to do a top-notch session. You have to be good enough and with a good enough content than I’m satisfied.

Another clear advantage is that you can support much more variation in content when you got much more shorter sessions, sure it is a roller caster of information, but this is what’s fun, falling a sleep in low pace talks is not my way of fun.

And if you by chance worried about speakers, the Open-Call for 3rd party speakers had showed that there are plenty of amazing talks to be heard out there.

There are still room for longer sessions, I don’t want to deprive you with annual excellent and fun Hanselman’s session, so I am thinking out loud, keep one slot of long session and one slot of Keynote/long sessions (usually) and keep the rest shorter. You like it? Tweet about it? Comment about it. Who knows perhaps we can evolve a better format (or worse, who knows till we try).

Focus Groups

During the last day of MIX I’ve attended a Windows Phone 7 focus group, I was hesitant to participate, I didn’t know if I had so much input to give, and I was actually right, compared to the guys sitting with me around the table which they were flowing with amazing feedback and information. I know my ways around Windows Phone so I can develop an app today but as it appears most problems are are not the SDK, or other Silverlight related features but mostly the Marketplace story, localizations and Hardware features oddities suchas the Back and Search buttons.

I’ve learned about what really going on in that Windows Phone development scene than any session I could have participated, people were discussing every painful curve of the road between development to actually publishing the app the customer. Discussing ideas with the members of the development teams in such an informal way is always my preferred way, hack that why I love twitter so much.

I must congratulate the WP7 team for being transparent, open and responsive for sometimes painful criticism and frustration by the developers themselves. I urge other teams to forge their own focus groups in future conferences.

There is more!

but not now, I need to battle jetlag, writing this post till 3AM local time is not a good way to undo jetlag.

Stay tuned for Part 2.

Ariel

Announcing UI-Binders

Posted Jan 31 2011, 04:54 PM by Ariel Ben Horesh  

I’m happy to announce the creation of a new community: UI-Binders.

Its purpose to maintain a place where WPF/SL developers and HTML5/CSS/JS developers can share ideas, patterns, and actually discuss with each other best practices in a new era where HTML abilities are increasingly competitive versus traditional Addins platforms such as Adobe Flash and Microsoft Silverlight.

Furthermore frameworks such as KnockoutJS and backbone.js are implementing the MVVM pattern in JavaScript, once mostly used in WPF/SL. This is a great example how an Idea coming from WPF/SL found his way to the HTML5 audience.

In contrary of what I’ve mentioned in the first paragraph Scope of the group is not limited for WPF/SL vs HTML/CSS/JS. discussions on all flavors of UI such as IPhone UI, Andoird UI are welcome, but to keep things in focus for now it is a bit left unsaid.

So without further due, I am inviting you to join and participate in the group.

http://groups.google.com/group/ui-binders

Ariel

Teched Israel 2010–1st Day Summary and… Revealing Cloudoscope!

Posted Nov 29 2010, 02:11 AM by Ariel Ben Horesh  

blogger_sign-Blue

It’s 01:30AM, just in time to summarize the 1st day of Teched 2010.

Actually I have arrived rather late as I came here by car and as we like to say at CodeValue “We are enjoying the way to our goals” so we bide our time and stopped to observe the amazing scenery of southern Israel.

But driving wasn’t the only thing we did today.

I’m proud to present you Cloudoscope, our innovative product for the cloud.

CodeValue’s CTO Alon Fliess wrote a quick summary on it, go over it and than register to our beta partners program which will enable you to get early versions of our product and help us refine it’s future features and roadmap.

I will be happy to hear your questions and comments so feel free to contact me, via this post comment, blog contact, our my twitter (@arielbh).

Back to Teched, I’ve participated on the keynote, which included many of Microsofts Ranana best people on board showing us things as trivial the new messenger, new collaboration features in office and XNA programming which targets XBOX, Desktop and Mobile.

One Microsoft representative discussed future trends and again emphasized on Gartner report which states that on the following years 80% of the top 1000 companies in the world will find themselves on the cloud. It is a very promising and fertile land for our products on the cloud, I believe we at CodeValue are on the right track. I’ll disregard the Music parts of the keynote and even the Kinect show off. Both were irrelevant. Nobody mentioned the fact the both XBOX and Kinect are unavailable to purchase from Microsoft Israel (but this is an old promise unfulfilled). I was rather disappointed not to see any developers tools: where is WebMatrix, where is SwitchLightl, where is HTML5?  Where is Silverlight? The Keynote failed to mention most initiatives made by Microsoft Redmond. Bassicly Teched does take IT higher, but what about developers?

Soon after the keynote, all attendees when to another hanger and met Microsoft Partners and heard their offerings. I was able to talk to many of you, explaining you about Cloudoscope, or just catching up with old friends.

A few of us found ourselves finishing the evening gulping beer on a local bar. Anyway I turned this around I had a lot of fun and I felt myself surrounded by friends (Mainly because of my CodeValue peers, Uri Goldstien, Uri Lavie and Vlad).

Tomorrow I will be getting my self on few of the sessions (mainly cloud), also hoping to get some interviews for our CodeRadio podcast. hmm, maybe eat something so I won’t die out of hunger.

CloudValue

Ariel

טקהד 2010 הנה אני בא

Posted Nov 28 2010, 12:28 AM by Ariel Ben Horesh  

First I will want to apologize for my readers that this next post will be in Hebrew. We will return to our regular broadcasting just after this one Smile.

מחר, יום ראשון, אני אהיה בדרכי לטקהד הרביעי שלי בסך הכל. זה בעצם מאפשר לי להרגע ולהרהר בדרך שעשיתי מהטקהד הראשון שלי בשנת 2000.

הייתי אז חייל, די צעיר, שירתתי במדור שפיתח בדלפי, אם היו דיבורים על דוט-נט אז הם היו כמו ענני סערה באופק.  היו כאלה שאמרו שדוט-נט יהיה הסוף של דלפי, ובראייה לאחור הם צדקו.

במדור, קיבלנו כמות נכבדה של הזמנות לטקהד, אף אחד לא ידע מה זה הכנס הזה. הבכירים במדור לא היו מעוניינים וכך יצא שדווקא חבר’ה צעירים ואני בתוכם זכו להגיע לכנס.

הגענו כמו חפ”שים אמיתיים באוטובוס לילה סיוטי ולנו בבית החייל (למעשה לא היה מקום בבית החייל, אז מצאנו לנו מקום מקביל). לא היה לנו מושג למה לחכות. מליאת הכניסה הייתה בראשותו של ראפאל, שלצערו הדימויים שלו כשלו, עד אשר קיבל עזרה מהקהל. לאחר כמה הרצאות שבהם בפעם הראשונה נחשפתי לדוט-נט, התכוננו להרמת קוקטייל – היינו כל כך בשוק שאחד מחבריי אמר לי אני רעב בוא נלך לאכול משהו בטיילת, שום קוקטייל לא ישביע אותי. הסכמתי ללכת איתו לקנטקי פרייד צי’קן – אחד המגעילים – למזלי לא הייתי רעב. כמות האוכל שהייתה במסיבת קוקטייל לא ביישה מפעל הזנה למדינת עולם שלישי. מתחמים של אוכל סיני, יפני, איטלקי, ומסביב עשרות רקדנים על קביים ובתחפושות של גו’קים. כמובן שהמשך הטקהד הבטיח וקיים המון אוכל, המון הרצאות מצוינות, טקהד זה היה הדבר הכי פורמלי של לימודי דוט-נט לאורך כל חקריירה שלי.

אחרי שחזרנו לצבא, נדרשו ימים עד שהצלחנו לרדת אל לקרקע – היינו בשוק מהעושר הזה שההייטק יכול להציע והניגודיות עם הצבא הייתה מורגשת.

גם את הטקהד השני שלי הגעתי בתור חייל. אבל קצת יותר בקלאסה, כבר הרבה יותר בכיר, הפעם ברכב צבאי, לקחנו חדר במלון זול אבל נורמלי. לעומת הפעם הקודמת הציפיות היו גבוהות, דיברו על דוט נט 3.0. לא נרשמה אכזבה יוצאת דופן אך גם לא אותה תחושת אופוריה כמו אחרי הטקהד הראשון.

אל הטקהד השלישי, הגעתי כבר כעובד של חברת סלע, וכבלןגר מצטיין, הפעם הגעתי בטיסה וישנתי בחדר מקומבן. לרוע מזלי הטקהד התקיים מספר ימים אחרי שחזרתי מהודו, והייתי חולה מת. הייתי מאוכזב מרמת ההרצאות, זאת הייתה הפעם הראשונה שבה הרגשתי, שכבר מאוד קשה לחדש לי, מי שמחובר באופן יום יומי לנעשה בחדרי חדרים ברדמונד, קשה להרשים אותו עם התכנים. מבחינה חברתית, הטקהד היה שונה מאוד מקודמיו, במקום להיות מוקף בחברים, הייתי מוקף בעמיתים, אבל לפחות יצא לי להכיר הרבה מחבריי לבלוגיאדה.

כמיטב המסורת אל הטקהד הרביעי אני מגיע כשותף בחברה חדשה, CodeValue אני מצפה בכיליון עיניים לפגוש אותכם ולראיין אותכם לפודסקט שלי ושל שי פרידמן (CodeRadio) וגם לספר לכם על המוצר פורץ הדרך שאנחנו שוקדים בימים אלה בחברה.

blogger_sign-Blue

אריאל

How to Develop MVVM Silverlight applications with Prism

Posted Oct 24 2010, 01:55 AM by Ariel Ben Horesh  

I’ve got some criticism from Alex Golesh in a comment on one of my latest Posts (Managing Silverlight resources contained in external assemblies), First I would like to thank him for taking his time and writing this comment, I would like to reply him with this post.

First let’s see Alex’s Comment:

I have to comment it, because the code lead to bad practice...

First, it heavily assumes you have all you assemblies in single XAP package - which is a bad practice for "heavy" Silverlight applications and especially real MVVM based applications.

Second, XamlReader will throw an exception if you resource (XAML) have a refernces to external resource dictionaries.

Last, but not least, this code will not work in SL3 and Silverlight for Windows Phone 7.

Regards,

Alex

Alex’s first point is what really made me write this following post, but I will get to it later. His second point is just plain wrong, I’ve created a small sample proving it, it is not very interesting sample as it self in my opinion but I just don’t want you, dear reader, to refrain from this solution on basis of Alex’s false assumption. You can download it here.

About Alex’s last point, It might be that it will not work in SL3, I’ve not tried to test it on that SL version,  Even how I wouldn’t recommend you developing RIA in SL3. About Windows Phone, I reckon that on the Phone platform a different approach is needed to be used, the code to manage resources is used when writing decoupled modules should be tuned to the platform specific needs. Anyway it is out of scope from this post, I will leave it for future post.

Now, let’s talk about Alex’s first point, it really boiled my blood Smile, an assumption so wrong, I’ve not heard for a long time, the whole purpose of that post was to allow you writing separate modules (which every module comes as his own XAP package) by keeping resources separate as well in order to refrain from tight coupling it in the first place. Now what really made me laugh is that each resource dictionary usually contains DataTemplates which pair a view and its ViewModel, an essential phase for maintaining MVVM Open-mouthed smile.

In Alex’s defense, he could have never known the full picture, how does that one piece of the puzzle fits in a larger picture.

That large picture is what I mean to present here. 

Let’s get started with Developing MVVM Silverlight App

First of all, I will be using Prism 2.2, as I’m writing this post, it is a the release version of Prism.

I will be following Prism’s guidance, as I truly believe in it and my experience with it from the day it was born has been very successful. I’ve started developing Prism with WPF and when I’ve made a switch in Silverlight I’ve tried to maintain the same methods of implementation. I will be covering some of Prism  main features in this post so a knowledge in Prism is very useful.

You better download the sample now, as I will be explaining it, and it might be easier for you to follow with that code in front of you. You can download it here.

The solution contains:

  1. 3rd Party folder: we will keep compiled assemblies such as Prism’s assemblies, other controls vendors assemblies.
  2. Client folder: we will keep projects related to our client, such as Modules and Common projects referenced by all modules.
  3. Silverlight Main Project: It contains the Shell view, we will inject views into it.
  4. ASP.Net Main Host: For this sample purpose it will be the default generated host you got from the Visual Studio Wizard.

Let’s investigate the Common project: This project is referenced by all modules, and must not reference any other project. I kept it as minimal as possible so it will contains only essential items for this sample to function.

Let’s see my version of ViewModelBase, it appears everybody got one Smile.

public class ViewModelBase<T> : ViewModelBase
{
    public new virtual T Model
    {
        get { return (T)base.Model; }
        set { base.Model = value; }
    }

    protected override void ModelChanged()
    {
        OnPropertyChanged(() => Model);
    }
}

I find it convenient that when I am binding a ViewModel to a View, I always got a Model property to use, making it reoccurring pattern to follow, and  it will not constrain you in any way, we will see it in use soon.

public class TemplateContentControl : ContentControl
{
    protected override void OnContentChanged(object oldContent, object newContent)
    {
        base.OnContentChanged(oldContent, newContent);
        if (newContent is UIElement) return;

        string key = newContent.GetType().Name;
        
        ContentTemplate = (DataTemplate)Application.Current.Resources[key];
    }
}

This is an interesting piece of code, it’s main purpose is to replicate WPF’s DataTemplate DataType ability. When we add a ViewModel to the SL’ visual tree, this control is going to grab the relevant DataTemplate.

public class RegionNames
  {
      public const string MainRegion = "MainRegion";
      public const string LowerRegion = "LowerRegion";
  }

Regions are a fundamental feature of Prism. which allow you to specify a place-holder inside a view, and let another view get placed in that place-holder without really knowing where is that place-holder location on the screen and in it’s project, thus decoupling a view from it container.

In this specific sample I’ve also located here the Model of the application, usually it deserve a separate project, but in order to keep things more simple I’ve placed it in here.

We have finished browsing through the Common project, now let’s move forward to talk about Modules.

Modules are pieces of application functionality that are suppose to behave autonomously. How do you define Modules in your app, it is actually a difficult question to answer. It really does depend on various architectural considerations.

In this sample app we will maintain 2 separate modules, communicating between modules is an important matter that I will have to leave for future post.s To keep this sample simple, the 2 modules do not interact with each other.

In Silverlight scenario each Module is in fact a Silverlight Application template (and not a Silverlight class library), after it’s creation you can delete all the files being generated. Make certain that in your ASP.net Host, it expects it’s XAP from the Silverlight Applications Tab.

image

Each module follow a certain skeleton structure:

  1. [Name]Module.cs : an entry point which we will be called when our modules are loaded.
  2. Views : a folder which will hold all relevant views of a Module.
  3. ViewModels: a folder which will hold all relevant ViewModel of a module. every View got a ViewModel (but not every ViewModel got a view).
  4. Resources: a folder to hold a specific resources needed by that (and only that) module such as images and Resource Dictionaries. Atleast one ResourceDictionary I recommend to maintain.

Let’s see the entry point of a module.

public class PatientsModule : IModule
{
    private readonly IUnityContainer _container;
    private readonly IRegionManager _regionManager;

    public PatientsModule(IUnityContainer container, IRegionManager regionManager)
    {
        _container = container;
        _regionManager = regionManager;
    }

    public void Initialize()
    {
        RegisterResources();
  _regionManager.AddToRegion(RegionNames.LowerRegion, _container.Resolve<PatientsViewModel>());
} private static void RegisterResources() { Assembly assembly = Assembly.GetExecutingAssembly(); string assemblyName = assembly.FullName; string[] nameParts = assemblyName.Split(','); var dictionary = new ResourceDictionary(); StreamResourceInfo resourceInfo =
        Application.GetResourceStream(new Uri(
        nameParts[0] + ";component/Resources/ModuleResources.xaml", UriKind.Relative));
        var resourceReader = new StreamReader(resourceInfo.Stream);
        string xaml = resourceReader.ReadToEnd();
        var resourceTheme = XamlReader.Load(xaml) as ResourceDictionary;
        Application.Current.Resources.MergedDictionaries.Add(resourceTheme);
    }
}

First you will notice it contains the piece of code that started the whole issue (Smile) but now in context. Note that it got a few basic stuff injected to it such as Unity (IoC Container) and RegionManager.

The initialize is in fact the method that will get called once a module is loaded. In this case create a new instance of a specific ViewModel (using Unity’s Reslove) and using the RegionManager we inject it to the MainRegion place-holder. Complicated? perhaps but it will grow on you once you get use to it Smile.

Note that by passing to the RegionManager a non-visual object we are depending on DataTemplates to tell Silverlight how to render that kind of an object. This is where our Resource Dictionaries and TemplateContentControl come into place.

Let’s see an example of a ViewModel.

public class PatientsViewModel : ViewModelBase<IEnumerable<Patient>>
    {
        public PatientsViewModel()
        {
            Model = new List<Patient>
                        {
                            new Patient {FullName = "Margol Raz"},
                            new Patient {FullName = "Jim Brown"},
                            new Patient {FullName = "Lazy Fox"}
                        };
        }
    }

Note that by deriving from ViewModeBase we got a Model property of type IEnumerable<Patient> we can make use. For the sake of a simplicity I’m just filling it up with some data. Usually you get it from a service or other means of persistency.

Now let’s check out a View

    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="100"/>
        </Grid.RowDefinitions>
        <ListBox ItemsSource="{Binding Model}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock FontSize="16" Text="{Binding FullName}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>            
    </Grid>    

We can clearly see we databind to the Model property of the ViewModel.

We have gone over some very important aspects but how the ViewModel get hold of it’s View? It all depend on the ResourceDictionary.

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml 
    xmlns:Views="clr-namespace:Patients.Client.Modules.Patients.Views;assembly=Patients.Client.Modules.Patients">
    
    <DataTemplate x:Key="PatientsViewModel">
        <Views:PatientsView/>
    </DataTemplate>
</ResourceDictionary>

A very important points to remember here:

  • It is important to keep the key of the resource the same type name of the ViewModel otherwise the TempalteContentControl will not be able to locate it.
  • You must specify the full namespace of the views even though it is in the same project (working around a possible bug).
  • The most important thing to remember his the that Silverlight (and WPF in that prespective) will push the ViewModel to the DataContext of the View, this is how DataTemplates are functioning, and this is why DataBinding are easy as a breeze in MVVM and in my purposed way of implementing it.

Our 2nd Module is very similar and will not cover it in here. It is just to prove Alex we still keep are apps in good code practice Smile.

Our last project we will go over together is the Shell project. It contains a Bootstrapper class that is doing the Prism heavy lifting in the startup of the application, reading the configuration file, loading up the modules, setting up Unity Container and RegionManager, etc.

<Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="50*"/>
            <RowDefinition Height="50*"/>
        </Grid.RowDefinitions>
        <com:TemplateContentControl Regions:RegionManager.RegionName="MainRegion" />
        <com:TemplateContentControl Grid.Row="1" Regions:RegionManager.RegionName="LowerRegion" />
    </Grid>

This is our Shell, all it contains is the placeholders for the modules to inject their ViewModels. note the usage of TemplateContentControl.

Conclusion

We have covered a lot of stuff today.

We have gone through creating a small sample in MVVM, Prism and I hope now it will be up to the high standards of the Silverlight Community.

Ariel

Open-Generics Support in MEF– Building a simple sample

Posted Oct 22 2010, 06:39 PM by Ariel Ben Horesh  

A year ago, A controversy arisen in the community when it was discovered that MEF is not going to support Open-Generics out of the box. (Here, Here and finally Here)

For those of you who don’t know what is Open-Generics. Consider the following scenario with Unity (which do support Open-Generics):

internal class UnityRunner
{
    IUnityContainer container = new UnityContainer();
    public UnityRunner()
    {
        container.RegisterType(typeof (IRepository<>), typeof (Repository<>));

        Repository = container.Resolve<IRepository<Customer>>();
    }
    public void Run()
    {
        Repository.Save(new Customer());
    }

    public IRepository<Customer> Repository { get; set; }
}
Let’s go over that code, and understand how it is relevant to our case. In the UnityRunner constructor we are registering a Repository<> to IRepository<> which means that when we resolve in the next line IRepository<Customer> we are using the same registration to every concrete type. Consider the alternative, otherwise for every concrete type in your domain you had to register it’s own repository. Open-Generics approach saves us from that tidbit.

If you had the patience to go over the links in the beginning of this post, you will know Glenn (@gblock) had contributed a piece of code to MefContrib that does supports this scenario. Unfortunately Glenn’s post is out of date, and there is no other reference to this issue beside that fact.

But why now? all that fuss? Prism 4 is soon out of the door, and it basically confronting you with a choice to take: You can use either MEF or Unity to fulfill Prism’s need in modules discovery and dependencies management. As we have explained earlier, one of Unity’s advantages over MEF is this Open-Generics issue.

Let’s see what we need to do in order to support it in MEF.

First you need to go over the nice-looking site of MefContrib and download the latest build. MefContrib consist of several assemblies that enhance, add or improve MEF. We need to reference either MefContrib.Hosting.Interception or MefContrib.Hosting.Interception.Silverlight (Guess when Smile)

internal class MefRunner
    {
        public MefRunner()
        {
            var typeCatalog = new TypeCatalog(typeof(MefRunner), typeof(RepositoryTypeLocator));

            var interceptingCatalog = new InterceptingCatalog(typeCatalog, new GenericExportHandler());

            var container = new CompositionContainer(interceptingCatalog);
            container.ComposeParts(this);

        }
        public void Run()
        {
            Repository.Save(new Customer());
        }
        [Import]
        public IRepository<Customer> Repository { get; set; }
    }

This code is doing the same thing as the Unit example before.

The most apparent change from a classic MEF example is the usage of the InterceptingCatalog (which in fact comes from the MefContrib assembly). InterceptingCatalog is a decorating catalog that sits on top of other catalogs such as TypeCatalog, DirectoryCatalog, AssemblyCatalog, etc. The InterceptingCatalog is going to grab unfulfilled matching that the regular MEF couldn’t make and will take over the process.

How does MEF knows where to find the IRepository?

public class RepositoryTypeLocator : GenericContractTypeMapping
{
    public RepositoryTypeLocator()
        : base(typeof(IRepository<>), typeof(Repository<>))
    {
    }
}

The RepositoryTypeLocator type is derived from GenericContractTypeMapping which is adorned with InheritedExportAttribute. That why we don’t need to give it an Export attribute but nonetheless it is going to participate in the composition. Note that this class is replacing the RegisterType in Unity.

Another change that for now you need to do is adorn IRepository with Export:

[InheritedExport]
internal interface IRepository<T>
{
    void Save(T obj);
}

That it. You are now ready to go.

In Silverlight it is pretty much the same thing. One change in the code you do need to do.

private IRepository<Customer> _repository;

[Import]
public IRepository<Customer> Repository
{
    get { return _repository; }
    set { _repository = value; }
}

Yes, you need to change Property implementation from auto and the old one. the code before uses reflection to fulfill the match, without explicit setter it will raise an exception.  

Grab the samples here.

So, Keep your Generics and hearts open and you will have joy in your code Smile

Ariel

More Posts Next page »