Jaime Rodriguez
On Windows Store apps, Windows Phone, HTML and XAML

  • Jaime Rodriguez

    tweaking your wpf code to run in Expression Blend...


    beta 1 of Expression Blend ( aka Expression Interactive Designer, codename Sparkle)  went out  a month ago...     I hope you are using it now..  I have used it for a while beforexe it went out, it has been very useful for creating animations, templates, styles, etc.. 

    If you have tried to use Blend with existing ( arguably very large) projects coded prior to Blend, you might have seen 'errors' or even crashes when opening your project in blend;  don't give up yet! imho blend is not too unstable, once you understand their design-time rules..    (read below to learn some of these)..

    Blend is a WPF application and as such it runs all user interface in a single AppDomain;  there fore when you design your app in blend, it tries to load [and run] your code in their executable... so be careful what you feed it :( ...   

    How and why does it run your code?
    There are two instantiation patterns i see in expresssion:

    • Blend will instantiate the base type of the root element on the design surface.. so for your Window, or UserControl or similar, it is mostly OK..
    • If you have a UserControl (UC) or Custom control you are droppping into a root document ( the root element described above)..  then Blend instantiates YOUR control, and at the minimum runs your constructor ....  
      • if inside your constructor you have code that subscribes to any other events, like   Initialized,  Loaded, or CompositionTarget.Rendering  then you are already telling the UI to call you back for this events [so yet more code to run] ...  if any of your code throws an exception, Blend will throw an error...

    Here is an example:  comments in D00BE8

    <!--  This is what I referred to above as "root element", here it instantiates Window class instead of  your Window1 class, so not your code -->
    Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ExpresssionTests="clr-namespace:ExpresssionTests" x:Class="ExpresssionTests.Window1" Title="ExpresssionTests" Height="377" Width="362">
    <!-- Here because you are inside the document (in this case window, it will instantiate your control directly, running the constructor for UserControl1, myTextBox and MyPanel  it does not matter if they are user controls or custom controls  -->
    ExpresssionTests:UserControl1 Margin="32,51,161,0" VerticalAlignment="Top" Height="108"/>
    ExpresssionTests:MyTextBox Margin="32,21,0,0" VerticalAlignment="Top" Height="26" Text="MyTextBox" TextWrapping="Wrap" HorizontalAlignment="Left" Width="113"/>
    ExpresssionTests:MyPanel Margin="42,0,161,58" VerticalAlignment="Bottom" Height="92"/>

    So, it calls your constructor (and executes your code).. why should you care? Your app works great when launched stand-alone (or debugger in VS).. 

    For a lot of your code, this will be fine...   for that slight percentage that it is not find, there are a few possible bad outcomes from it running your code:

    • Your code does some thing that throws an unhandled exception and crashes Blend..
    • Your code does some thing that throws an exception and blend handles it, but you get a generic error like "Can not create instance of UserControl1"
    • Your code might appear to be running OK in blend but it is consuming resources it should not ( e.g. if you are designing a Video Player, and in your player, you are telling it to "autoplay" when loaded,  so now you have a video playing at design-time.. [this is not only annoying but consuming resources, so your system slows down :( ]

    "Jaime, did you not read that 'my code works fine, I don't expect crashes.' "
    Hear ya, but there are a few valid scenarios where your perfect code behaves different when run from within blend.. here are a few commone ones:

    • Your application is data-driven and your control assumes the context and data models is available at design-time, but it is not ...  or your app tries to connect to its datasource and it fails ..
    • Your application uses the pack syntax ... [ I will come back to this]
    • Your code tries to access the global Application class or it's MainWindow (but since you are running in Blend, you get Blend's Application class)..

    "OK, I get it, how can I get around this?.."

    Blend and Cider team added a System.ComponentModel.DesignerProperties class to WPF so you can query if you are in 'design mode'.. 
    You can call System.ComponentModel.DesignerProperties.GetIsInDesignMode( DependencyObject element )  with any valid DependencyObject -translated pretty much any visual- , and find out if you are in the designer; 

     if you don't have a DependencyObject ( e.g. if you are in your business object and don't want to couple if with UI) then
    ((bool)DependencyPropertyDescriptor.FromProperty(DesignerProperties.IsInDesignModeProperty, typeof(DependencyObject)).Metadata.DefaultValue)  
     can do the trick to tell you if you are in design-mode.. even when you don't have a visual * ..

    <sideline> Jim Nakashima and Brian Pepin are good sources for info in this design mode property </sideline>

    "This sounds messy!  I don't want to be crowding code with design-time checks ... what should I do?"
    At first, I thought that too ... but it is really not too bad.. in fact, now I would argue it has made my code slightly better: I used to have projects where there was a bit more code than needed in the constructor.. [this code should have been in the Initialized or Loaded events] ... so you just need to refactor your code a little bit..  you can then use the design-time check to possibly not wire these other while in design-time...

    Another lazy workaround I used for those more complex projects with lots of transitions where I did need code in the constructor or had too much code and did not want to compromise run-time code readability w/ design-time checks was a put a very big  try { } catch in the  constructor or event being called...   in the catch, I check if I am in design time and just not bubble ( re-throw ) the exception ....  not ideal but it does the trick.. e.g.

    /// Lots of code would go here...  as long as it gets caught below Expression will be fine.. 
                catch (Exception ex)
    // I like to log them so that  I can clean up once a week..
    // This will no longer be necessary soon... Blend  will start letting you see the stack traces in the next public build  
    // it also re-throws if this is run-time

    "... the explanation is fine, but I can't even open my project in Blend... I don't think it is getting far enough to run any code.. " ... 
    Almost every time I think this, I look and it is getting far enough,  here is what happens:  Blend opens the solution and then it starts opening the windows I had opened last time in the designer, and crashes while executing my code..  Here are a few tips on opening projects:

    1. You can pass your full project path to blend from command-line ...  when you do this, blend simply opens the project/solution.. It does not automatically open any of your Windows (or scenes) in the designer  ... you will just need to double click in the window/control and it will then open it in the designer [possibly reproducing the crash] ...

      c:\Program Files\Microsoft Expression\Blend Beta 1\Blend.exe "c:\mypath\myproj.csproj"

    2. If you open blend from command line, you can pass the /exceptionlog parameter and if it crashes, it will show you the exception's call stack ...  so you know where to look. This is of course useful even if your project is not crashing when opening.. it will log the exception when ever it happens..

    c:\Program Files\Microsoft Expression\Blend Beta 1\Blend.exe /logException   
    Then you open your project and run as usual ...

    "OK., I am getting it .. any more tips?"
    Yes, but getting late and I am going to bed :( so here is the last one..   as mentioned Blend is a WPF app and it loads your code in it.. so  if you are getting design time errors and want to troubleshoot you can open good old Visual Studio, open your project in both VS and blend, and from VS attach to blend and debug, stepping through it, etc...  pretty useful for complex stuff .. 

    1. Open your project in Blend
    2. Open your project in VS ..
    3. From VS attach to Expression Blend ... (Attach Process, proc name is blend.exe ) ...
    4. [Optional] In VS, tell it to break on any thrown Exceptions.. 
      1. via  the Menus: Debug -> Exceptions
      2. Check the "thrown" box i nthe Common Language  Runtine exceptions
    5. [Optional] if don't want to stop at all exceptions, then put a breakpoint in your code..
    6. Now, in Blend close & open the scene (window, user control) you want to debug.
    7. If you are not getting it to hit your breakpoint, some times I have to do a Rebuild all in blend... before it catches on ..

    One last remark... 
    if you are a designer, or new to Blend and reading this, don't freak yet...   for designers, most of this stuff above happens when devs start putting code in places they might not need to so you are likely not to run into it...  for new projects also, it might not be an issue.. it is  those large projects that have 10s of thousands of lines of code in hand-coded XAML and or C# code...   Also, note that a lot of the troubleshooting tips above get much easier in later versions of Blend (I think beta2)... I mostly wanted you to get the behavior and how blend loads your code.. so you understand what up...

    I will try to come back w/ a blend tips & tricks ...   In the mean time, there is a small project with some sample code to illustrate points above here..   Do a search for //TODO: interesting  comments .... you can check them out, run the code, etc...   if you run it simultaneously w/ dbgview, you should be able to see the Debug.WriteLine ()s  that tell you a little of what's going on ...

     Good luck ...

    * [disclaimer, I should credit some one for the tip on using IsInDesignMode dep property with out a dep object, but can't recall who it was that shared this.. my guess would have been Unni or John Gossman. Sorry!  Do check their blogs though :)




  • Jaime Rodriguez

    WPF data grid..


    Xceed announced today their FREE  datagrid for WPF ...      Check it out here http://xceed.com/Grid_WPF_Demo.html

    It looks neat..  groping, sorting, styling,  editing , data binding, etc.. (disclaimer: only ran xbap, I did not download and play with it yet ... I did like the demo itself ).. 

    Did I mention it is FREE!! 

    WPF is really gaining a lot of momentum lately, dont you think?

  • Jaime Rodriguez

    Adam Nathan's "Windows Presentation Foundation Unleashed" book


    I was at the local bookstore this weekend ... and stumbled across Adam's WPF unleashed book ... this triggered a memory that a few weeks ago Yosi Taguri had told me to "make sure my presentation for TechReady covers every thing in Adam's Chapter 3" .. I grabbed the book and  browsed through it...   wow! What a jewel..

    The book is concise, insightful, yet it is also very approachable.  My favorite so far is these 'notes'  that are spread all over the book labeled under "digging deeper" or "FAQ" ... these are just right on [as is the rest of the book]...

    For tonight, I am really looking forward to the 3D chapter  -- writen by Daniel Lehenbauer .--- the dev lead for wpf 3d --- ..  This might even trump the only one show that I regularly watch  on TV: "24" ... 

    The book is a must have!!  Put it right next to Charles Petzold's .. :)

    PS -- There happens to be a free copy of Chapter 3 online via Tim's blog...  but don't make the mistake of reading just chapter 3 ...  


  • Jaime Rodriguez

    using wpf/e to create interactive web charts ...


    First CTP of Windows Presentation Foundation Everywhere (WPF/E) was released last december, Joe Stegman blogged about the goals for WPF/E: ".. leverage your existing skills and web assets to create better web experiences."

    Immediately the community created some really cool demos around media & content .. ( amongst my favorites are the channeld 9 video player and this video player )... 
    Of course, with my enterprise/lob bias, I went a different route.. trying to solve an old, recurring pain: creating rich, interactive graphics for data viz ...  A few people have asked about this lately, so here are some my insights from a merely a day or so playing with this before the holidays..

    For overall results, I do feel WPLF/E helps to create a better experience, the charts are animated, I can interact with these with out having to round trip to server, etc.... I was very happy..
    [Disclaimer:I did not spend a lot of time creating full, or good looking charts, but here are some of the ones I created. I have others, like bar, leaving that for a later exercise with aspx integration].


    If you have WPF/E installed you can see them live: pie chart  and line chart..

    If you parse the results w/ a technical focus, here are my impressions:

    What does WPF/E bring to this scenario that we did not have before (with HTML)?

    • WPF/E is cross-platform/crross browser    ( so improvement over VML and similar ) that I have tried)
    • WPF/E is very light weight ( 1 MB download, improvement over say Java, activex, etc)
    • WPF/E brings vector graphics, good mouse support, a few higher level primitives ( Rectangle, Line, etc.)...   Because of the flexibility of Paths, you can pretty easily draw any thing in 2D..
    • WPFE also brings a great animation engine to enhance the charts w/ feedback and interactivity..  [this is usually a hard thing to code on your own]
    • An unexpected surprise, was how much I liked the integration/interaction with Javascript..  being scriptable gives me a lot of flexibility to create stuff on the fly or serverside from ASP .NET or PHP ...  With WPF/E you have an open white-box for you to use.    

    [ I am not a charting expert at all, but wrote a few in my life and I always though the rendering + the animations where the hardest part; and WPF/E stacked quite well there]

    On skills reuse  (or the WPF in WPF/E) :

    • I can leverage all my XAML skills for the charting..   I can also reuse XAML assets ( say gradients, vector-based drawings, animations, etc.) .. This is nice, but it does not get you to single code-base between WPF and WPF/E ..   Mike harsh, has discussed they are looking into adding more WPF features into WPF/E, amongst it CLR integration; this could increase my code reuse significantly ( guessing to 80% or higher?)...  that sounds much better, but won't get you to 100% unless you are careful and code for 'common denominator'. Today WPF/E is missing some WPF features (e.g. Styles, Resources) that you would definitely want to use if you were writing WPF, you can get around these in WPF/E by creating slightly more verbose apps,  but there is obviously a little work needed to get around it...
    • The charting scenario as I scope it is great for ASPX or PHP websites that deal with data today.  You can reuse all your back-end code and easily create server-side controls that can generate enough XAML + script to get the front-end working..    I did not go there yet, but Shawn Burke has a sample already and this is something aspx devs do all the time, so proven practice..

    On performance/stability of the platform:
    I must admit I did not poke into perf in depth, but so far I was impressed when I saw the shawn's video demo .. wow, these many videos playing simultaneously ... :) 
    On my line chart, I had 600 points .. I did two 'cursors' an ellipse the follows the mouse on the Left hand side, and a bar on the RHS ...the mouse is quite responsive..
    I am one of those persons that things for pure visualization [not analysis] you can only look at a finite number of data points, so I am pretty confident WPF/E will meet perf the web chart perf requirements; if it does not, you might want to do server-side charts, as you likely have too much data].

    I was also quite pleased with the platform's stability - the error handling could be better and after this post ( this time I will try to do it soon) I can put a list of the issues I ran into (both bugs and/or featurs not yet complete that can throw you for a loop )...  but over all, for being the first CTP, I thought the platform did quite well...

    Again on WPF/E..
    I was chatting w/ Carter Maslan recently on WPF/E end-user benefits and I summarized it as "WPF/E, like AJAX, lowers the developer entry point to create better experiences and to reuse existing assets (e.g. video content) " .. I think with my brief charting experiment I was sold on that ...  I hope to see a few intranet/enterprise websites leveraging these new technology to improve their end-users visualization, decision making and producitivity ...   Try putting these in sidebar too ... these charts work fine there in sidebar..

    PS -- apologies to all my control vendor friends who write hugely complex and professional looking charts for calling the samples above charts; it is the potential that I want to communicate, not my couple of hours of bad javascript hucking;

  • Jaime Rodriguez

    Choosing a smart client technology..


    Help us out ..      Kevin Moore (wpf) , Scott Morrison (crossbow ) and I were guessing some of the criteria that you use to select a platform ..  we are making two assumptions:   1)  you want a windows smart client .. 2) and you are considering managed code ( so windows forms or wpf mostly)

    Here is where we are landing ( and criteria range or explanation ) ...

    • Platform  ( supported OSes )
    • Richness ( battle ship gray to bling )
    • Tools  ( from notepad to  drag-drop-databinding-codegen-magic-wand )
    • Controls   ( from button  to datagrids, is datagrid the richest control that is fair )
    • Ecosystem  ( measure of existance for: books, community, control vendors?)
    • Frameworks  existence of app blocks to accelerate app dev ( like MDI, CAB, Spring)
    • Future investments for the platform ... (e.g. how much will it change and why?? )
    • Existing investments ( your skills, your code )

    some that are not making the cut are:  deployment (seems the same), platform lifespan ( seems the same too.. both will ship in Orcas so both have 10+ years to go..)

    Some of what I am wondering: 

    • What are we missing??
      • Localization ... is it that relevant...   At MS it is... but outside?  
      • Help system ..
      • Extensibility? Customization?
      • What else??
    • Are the scales above fair or too broad?  I am mosty concerned on richness... was thinking of splitting it to
      • Basic UI services (layout, controls, customization, )
      • app services ( databinding , performance, back-end integration ) .... 
      • Technolgies integrated ( e.g. support for text, 3d, etc.)
      • But when I partition like this seems too granular .. and wpf focused.. 

    Thoughts?? I will  let you know where we land ... this is for a deck next wednesday ... and we are all too swamped (so none has a lot of think time), drop me an email with what we are missing ... else we might miss it for next week )..


Page 1 of 1 (5 items)