DCSIMG
Ariel's Remote Data Center

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

Porting Windows Phone 7’s Panorama Control to Silverlight 4

Posted Oct 21 2010, 11:52 AM by Ariel Ben Horesh  

One of the first things that really caught my eyes in WP7 is the nice looking Panorama control.

You may checkout its functionality here:

Windows Phone 7 Panorama Control display.

I was rather disappointed that this control is available out-of-the-box for WP7 only.

But let’s not let that small fact break our spirit!

I’ve downloaded the soon to be deprecated Panorama and Pivot controls code from this codeplex site : http://phone.codeplex.com/ (and this is where I must insert a big “Thank” for Stephane for his great work).

While most of the Silverlight API is pretty much the same as WP7, one of the most major differences is around Touch API.

To make things more obscure SL4 appears to support Touch Manipulation API, so Stephane’s code actually compiles in Silverlight regarding this aspect, but don’t expect it to work. It is explained in this MSDN Page about Multitouch Input.

Again, this will not stop us. Further investigation reveals this sample: Microsoft Surface Manipulations and Inertia Sample for Microsoft Silverlight.

I’ve incorporated that sample code and replaced the WP7 manipulation code with it implementation.

Converting the manipulation code was pretty much straight forward and nothing fancy or especially interesting to talk more about it.

During the porting I’ve ignored usages for specific WP7 resources; example: PhoneForegroundBrush. With a little more effort one can port those resources as well.

While finishing the panorama code, I’ve noticed that Stephane also implemented a Pivot control, so I’ve decided that this port wouldn’t be complete without porting the Pivot control as well, which was similar in many ways to the panorama control changes.

Windows Phone 7 Pivot Control display.

A small disclaimer It is not bullet proof or 100% replica of the Windows Phone controls so use it on your own risk Smile

You can find the code here.

Ariel

Managing Silverlight resources contained in external assemblies

Posted Oct 19 2010, 01:35 PM by Ariel Ben Horesh  

A year ago, I’ve written a post about Managing WPF resources contained in external assemblies.

I am using this pattern in every Prism application I’m developing, the main reason for this is  that I like having each

module responsible for his own resources, especially it contains DataTemplates which couple Views to ViewModels.

In each of my module entry classes (which inherit from IModule) I usually add a method which is used on the Initialize phase.

The problem is that the code that has being used by WPF is very different from the code you need to use in Silverlight.

So here you go:

private static void RegisterResources()
{
    ResourceDictionary dictionary = new ResourceDictionary();
    StreamResourceInfo resourceInfo = 
    Application.GetResourceStream
    (new Uri("[ASSEMBLY NAME];component/[SUBFOLDER IF ANY]/{DICTIONARY NAME].xaml", 
    UriKind.Relative));
    StreamReader resourceReader = new StreamReader(resourceInfo.Stream);
    string xaml = resourceReader.ReadToEnd();
    ResourceDictionary resourceTheme = XamlReader.Load(xaml) as ResourceDictionary;
    Application.Current.Resources.MergedDictionaries.Add(resourceTheme);
}

Note: the strange Uri syntax, every [] is a place holder for you to put in your specific information.

Ariel

New Beginnings

Posted Aug 21 2010, 11:17 PM by Ariel Ben Horesh  

It is about 3 years since I’ve posted this post, which in it, I’ve announced joining Sela.3 Years. Wow, amazing how time flies by.

I had good times, and bad times at Sela. This blog accurately reflects it, when I felt not so good my writing muse was blocked.

Now I hope things will change as I announce that I am leaving Sela. I’m leaving many people that I’ve enjoyed their companionship and I honestly admire their expertise. Most of all I will remember our yearly field trips to USA in order to participate at PDCs. Those were good times.

During my time at Sela I’ve exposed myself to situations that are way out of my comfort zone, including speaking at conferences, going to customers to consult on stuff I’ve learned the day before, pushing myself to be expert on WPF, Silverlight, WCF, WF, Team System, Scrum. Those were a drivers for real growth. I can now reflect back and conclude that with most customers I’ve succeeded not only to make a difference technically but also to gain their friendship, in that case I’ve took advantage of one of Sela best offers, the ability to participate on many projects, on many domains during a short period of time.

I would like to thank everyone on Sela, that I’ve had interaction with, to all without regards of importance.

A word on the future. I’ve a dream, working with my friends, enjoying my time, using my creativity. Finally I’ve decided to fulfill this dream.

CodeValue-Logo_03

I would like to present you CodeValue, my new venture, which consist of truly the best, both personally and technically people. While most of the things we are doing is still under secrecy, we are going to offer various services, such as pulling out extremely difficult projects, or impressive demos which contains revolutionary concepts. We will also offer consultancies, so don’t hesitate on contacting me, though this blog or through our web site.

Members of the new company are well esteemed leaders of the Israeli developers community: Alon Fliess, Eran Stiller, Shay Friedman, Amir Zucker, Eli Arbel, Josh Reuven, Bernie Almosni, and more.

Drop by at our site at www.codevalue.net, make sure you visit our awesome Pivot view of our aggregated blogs, a real knowledge power.

Make sure you start following our @CodeValue twitter account and rest of the team: @arielbh, @alon_fliess, @ironshay, @eranstiller, @bernieal.

Also visit our Facebook page.

Good luck to us all.

Ariel

PDC09 : Hanging out with Microsofties, or why PDC09 is different from every conference I’ve attended

Posted Nov 18 2009, 06:26 AM by Ariel Ben Horesh  

So far I am expriencing PDC09 much differently than any other conference I’ve ever participated.

First, Thanks to Glenn Block I have a role to play, yesterday I hanged out with Glenn at the speakers lounge meeting people I’ve reading theire blogs for so long time, people such as Nikhil Kothari, Matthew Podwysocki and many more.

Second, Last PDC my laptop had died 2 days before flying over. This year I feel I am blogging and twittering for every second breath. Feel Free to follow me (twitter.com/ArielBH).

Third I’ve met with some great people today, Ian and Mike from the WPF team, Paul from the VS team, Marc from the DPE team, all this guys are Microsofties (I can also add Glenn to this excellent list). We had great conversations, and ideas, I’ve learned stuff on the internals of WPF and VS through funny stories that you can get expose too through happy conversation.

So content wise, nothing new under the sun at PDC, but for me, I am enjoying every minute of it.

Ariel

PDC09 : Advanced WPF Application Performance Tuning and Analysis

Posted Nov 18 2009, 05:54 AM by Ariel Ben Horesh  

http://microsoftpdc.com/Sessions/CL11

In this presentation, a WPF Facebook like application was presented. Unfortunately the application has issues. during the session we have walked some classic scenarios and some are a bit far fetched (at least from my experience).

If you are a WPF developer, see the video, this session should go through video really good, because you will be able to see all the small mouse gestures the presenters are doing  with each application they have used to analyze the problem.

To get things in order, the session dealt with those issues:

  1. Memory usage : In this app scenario images being used and not released because some stupid reference. Not really wpf related, but the excuse was that usually designers are oblivious such as this, and might provide you styles containing many elements and unnecessary resources.
  2. Cold Start : locate heavy IO pulling during application, notice for rough assemblies loading up that you don’t really need.
  3. Warm Start : Look for complicated layouts being rendered, maybe can you can render a few items at the time especially if they are shown in the UI.
  4. Rendering : Check out for unnecessary rendering being done through resizing and animations.

When the session slide deck would be published I’ll update here with specific tools names you can use.

 

Ariel

More Posts Next page »