Monday, April 30, 2012

Key Points of Some Best Practices for Silverlight


  • Don’t use unnecessary “xmlns” namespaces in the XAML file. This overburdens the load time of the Silverlight page (If you are using Resharper, you can do this very easily as it will change the color of the unnecessary items to Grey). 
  • Don’t add same namespaces multiple times in a single XAML page. It screws up the XAML code at the time of maintenance and also loads the assembly namespace multiple times causing various memory issues at runtime. 
  • Use proper name for your “xmlns” namespace prefix. For example: xmlns:commonControls is more meaningful than xmlns:cctrl. This avoids multiple declarations of namespaces in future. 
  • Try avoiding “xmlns” namespace prefix name as “local”. Instead use “localControls” or “localConverters” etc. as per your namespace name. Using “local” will not give you proper meaning. In the same assembly there may be two or more namespaces (e.g. Controls, Converters etc.). In such case, it will be helpful for you to use proper prefix name to distinguish between them in proper way. 
  • When adding a control that has no elements inside it, better to close it by self-closing tag “/>” instead of the hard closing tag (</TAG>). This gives more cleaner XAML code.  
  • Remove all unnecessary resource keys if they are not in use. These increases the memory uses and you may sometime encounter some animation issues due to this. If you need it at later point of time, you are always welcome to add it. 
  • Don’t use extra panels (e.g. Grid, StackPanel, Canvas etc.) unless it is required. 
  • Always try to use Grid as your panel first and if you require other panels, use them. Grid has the flexible UI layout and thus resizing your application will have a great effect. 
  • Never try to give a name to all of your controls inside your Silverlight page as it takes unnecessary object creation at the time of load. Name only those elements which you want to use from your code behind and/or from your xaml. If you are using MVVM pattern, you can remove the naming of your controls in almost all the cases. 
  • Use the Visibility property of the controls instead of the Opacity property to hide the content. Opacity to zero makes the control to hide but takes space in both memory and the UI. Other side, the Visibility property collapses the control from the UI, thus making spaces for the other controls in the same place. 
  • Use proper formatting of your XAML code. This gives better look of code and also easy to maintain in future. 
  • Use comments in XAML whenever require. This is useful when you revisit the code after a long time or some other person comes to work with your XAML file. 
  • Try to use StaticResource instead of DynamicResource as it increases the performance and also it throws exceptions at development time. Hence, easier to identify the root cause. 
  • Remove unnecessary styles & storyboard animations if they are not require at all. 
  • Try to add your styles in a separate file if you want to share them across your application. If they are specific to a single page then add them in the page resource.

XAML guidelines and best practices

Everyone has their own opinion on how source code should be structured and formatted.  What really matters when it comes to code is not saving the CPU a couple cycles, rather enabling others to read and understand what you’ve written.  This comes from Martin Fowler’s classic book Refactoring:
There is another user of your source code.  Someone will try to read your code in a few month’s’ time to make some changes.  We easily forget that extra user of the code, yet that user is actually the most important.  Who cares if the computer takes a few more cycles to compile something?  It does matter if it takes a programmer a week to make a change that would have taken only an hour if she had understood your code.
When it comes to XAML, there aren’t too many opinions/articles talking about best practices (compared to other languages/markup).  In fact, the definitive guide for XAML guidelines is Jaime Rodriguez’s (site) best practice web cast series and the resulting whitepaper (pdf).
Jaime’s whitepaper is a must read for anyone in the Silverlight space. 
Since my blog is less formal than a whitepaper, I’m able to give a stronger opinion on what I think are the best practices for XAML.  So, without further ado here are my thoughts on XAML:

Formatting

First and foremost, I think formatting is the number one concern. 
  • Attributes should be on a separate line,
  • x:Name should come first,
  • and related attributes (such as HorizontalAlignment and VerticalAlignment) should be grouped.
Take the below code blocks, Figure-1 and Figure-2, show the difference between having all the attributes on the same line versus on different lines.  In my opinion, Figure-2 is much easier to digest than Figure-1.  By having the x:Name first, you can quickly identify what the element is.  Once you find the object you are looking for, you can then quickly identify related objects since they are grouped together (such as RadiusX and RadiusY, Width and Height, and HorizontalAlignment and VerticalAlignment).
The biggest complaint about Figure-2 is “wasted space”.  The code inflates from 8 lines to 30; however, to Martin Fowler’s point, it’s not about you or the computer, it’s about other people being able to read and quickly assimilate to your code.
Figure-1
  
Figure-2 

Naming conventions

Name everything

Try to specify an x:Name attribute for every element in XAML.  If nothing else, this will make you think if you really need the object.  For example, at times it’s tempting to embed a panel within a panel to achieve a specific layout.  In many instances I have caught myself doing this, mainly out of laziness.  After refactoring I find that if I tweaked a margin or used a different kind of panel, there would have been no need for the extra panel.  Forcing an x:Name on an object really makes you think of the purpose of that element.

Describe elements

Instead of pre or post-fixing element names, give them a descriptive name.  Instead of:
  • btnSubmit use SubmitButton,
  • grdContent use ContentPanel,
  • stkPnlNav use NavigationPanel.
Programmers like using the pre-fix because you can quickly see all of the same type when using intellisense, and you can easily identify the type of an element.  Admittedly, I come from this camp; however it’s time to change.  A couple reasons for the change: 1.) designers will increasing be  working in Blend and they are not going to be geeks like most of us and pre-fix with the type 2.)descriptive names are much easier to read and understand the cryptic typed names (think stkPnl=StackPanel or me=MediaElement).
Lastly, give all panels the same post-fix because you never know if you will have to change the type of a panel.  I assure you, it’s an enormous pain, and large risk, to change the x:Name in a project.  For example imagine having to change “BufferGrid” to “BufferCanvas” to “BufferStackPanel”.  Not only do you have to change the XAML, you have to ensure all instances in the code are changed too.  Better to go with the generic “BufferPanel” and be done with it.

Disclaimer

Best practices should be followed to the T; however, there are times when we’re in a crunch and the guidelines fall the way side.  Best practices are designed to eliminate maintenance time and promote consistency.  I am certainly guilty of not following the above guidelines, however it’s my goal to follow these consistently as possible.

Silverlight Startup Best Practices

Introduction
Startup is important because it is the first interaction that your user has with your application.  You get one chance to impress, and failure to do so could mean the user closing and/or uninstalling your application permanently.  What follows is a set of tips and tricks you can use to supercharge the startup path of your Silverlight application. 
The Cardinal Rule
There is, essentially, a single cardinal rule.
     Do the absolute minimum required to display your main screen. 
Write this on a sticky note and hang it on your monitor.  This may seem like common sense (I like to think so), but I’ve analyzed many an application that violates this rule in more ways than one.  The less deterministic the code is that you’re executing, the more you’re asking for trouble.  To subdivide this rule into some specific examples:
  • Minimize your download size.
  • Never wait on network I/O before displaying your main screen.
  • Minimize disk I/O, delay-load any data or business logic that you can. 
Minimize your download size
Since your application has to be downloaded before it can start up, your download size directly affects startup time.  Consider dividing your application into multiple XAP files.  The first XAP should include only what is necessary to display your main screen and provide core functionality.  Tim Heuer has put together a great video on silverlight.net titled “Loading Dynamic XAPs and Assemblies” that explains this concept in detail.  Use this method to componentize and delay load parts of your application that pull in large dependencies and/or don’t absolutely needto be available when your application starts up. 
Another great tip on Silverlight XAP compression comes from David Anson.  A Silverlight XAP is just a renamed Zip file, but as of Silverlight 4 our XAP compression algorithm isn’t as efficient as it could be.  By simply re-zipping your XAP files using an optimal compression algorithm you can shave about 20% off your download size (as high as 70% in extreme cases).  Check out David’s post, “Smaller is better!” for the details and a useful script to help you automate the process.
Never wait on network I/O
No-doubt, this is one of the riskiest things you can do during startup.  Network I/O latency is non-deterministic; when you make a call to a web service or access data from a network share your request could return in 2 milliseconds, 2 seconds, 2 minutes, or it may never return at all!  If your application waits for this data to be retrieved before showing your UI, it may nevershow up.  At best, you are gambling on the speed of your network connection to determine your startup time.
Minimize disk I/O
When you increase the amount of data that you load from disk (whether raw data files or loading unnecessary assemblies) you increase the amount of time that you’re waiting for physical media.  It takes a substantial amount of time for your hard disk to seek to each new read location, and it takes time to read the data once you seek there.
Load Fewer Assemblies at Startup
One way to minimize disk I/O is to reduce the number of assemblies that your application loads.  In Silverlight, a new assembly is loaded the first time that the CLR just-in-time (JIT) compiles a method that accesses a type from it.  For example, if you took a simple “Hello World” Silverlight application and added a DataGrid to it, this would cause System.Windows.Controls.Data.dll (where DataGrid lives) to be loaded.  You can use the 
VMMap tool from Windows Sysinternals to discover which assemblies you are loading, and how much data from each one.  Assemblies can be found under the ‘Images’ category as seen in the screenshot below:

Since an assembly isn’t loaded until you pull in one of its types, there are two scenarios to keep in mind:
1.    Static members can cause dependencies to be loaded eagerly.  For example, if you have a static field of type DataGrid, System.Windows.Controls.Data.dll will be loaded at application startup during static initialization.  This can be avoided by leveraging System.Lazy<T>, see the MSDN documentation for details.  More information on lazy initialization can be foundhere.
  1. A method that conditionally loads a new dependency can be refactored so that the assembly is loaded when it’s actually needed.
    private void OnLoaded(object sender, RoutedEventArgs e)
    {
        
    bool b = true;
        
    if (b == true)
        {
            
    // Instead of this, refactor into a method, this will
            // prevent System.Windows.Controls.Data.dll where
            // DataGrid lives (and which is not one of the core
            // SL assemblies) from getting loaded.
            //   DataGrid myDataGrid = new DataGrid();
            //   LayoutRoot.Children.Add(myDataGrid);

            AddDataGrid();
        }
    }
//prevent in-lining if method implementation is too small.
[
MethodImpl(MethodImplOptions.NoInlining)]
public void AddDataGrid()
{
    
DataGrid myDataGrid = new DataGrid();
    LayoutRoot.Children.Add(myDataGrid);
}
Load Less Data
Avoid loading content/configuration data that isn’t needed to display your main screen.  An example could be an email client where a user’s messages are all serialized into a flat file.  You should wait to load your message data until after your main window has loaded, and you’ve had a chance to display a loading animation or otherwise show that your application is responsive.
Another example could be an application that has a rich extensibility and plugin model.  Make sure that you are loading and displaying the main shell of your application before you load each of your plugins.  A single misbehaving plugin could add lots of extra time to your startup sequence! 
Optimizing Templates and Styles
Having some Xaml parsed at startup to define the initial appearance of your application is unavoidable.  Because of this, be sure to optimize your initial Xaml design for startup time.  Here are a few things you should keep in mind when optimizing your Xaml.
  • Minimize your element count.  Every element that you add to the visual tree adds to the amount of time that it takes to parse.   When refactoring your Xaml, you may find yourself with elements left over in the visual tree that no longer contribute to function or appearance.  A good example of this could be a Grid with a single child and no meaningful properties set. These types of elements should be removed!
  • Remove dead XAML.  If a style or a part of your tree is no longer used, remove it!  Why pay for something that you’re never going to see or use?
  • Prefer Templates over UserControls.  UserControls need to be re-parsed per instantiation, templates are parsed only once.  This is especially important in say, a DataGrid cell template, where hundreds of cells are styled the same way.  If you style your cell using a UserControl, you are going to parse the same Xaml hundreds of times over; by using a template you ensure that this Xaml is only parsed once!
  • Don’t set properties to their default values, this includes things like setting Opacity=”1”, or setting RenderTransforms to non-parameterized values.  Some of our design tools have a nasty habit of doing this so you may need to police their output.  We’re working to make this better in the future. 
Consider Using a Splash Screen
So you’ve implemented the rest of the startup best practices, but your application is still not quite snappy enough for you?  At this point you should consider using a splash screen.  By default, Silverlight applications use a default splash screen (the spinning orbs that I’m sure you’re familiar with).  By replacing the default splash screen you can greatly improve perceived performance and get your own custom branding in front of the user as soon as possible.  There is an MSDN article available here that explains the process of setting a custom splash screen.
 A custom splash screen in conjunction with the Xap chaining example in Tim’s “Loading Dynamic XAPs and Assemblies” video mentioned under the “Minimize your download size” section can go a long way toward providing a responsive user experience. 
Conclusion
Application startup can be a tricky thing to master, but once you’ve successfully driven your first real application to a fast startup the principles learned will serve you for years to come. We’ll be updating and correcting this page going forward, so add a bookmark and send the link out to other developers on your team.

Silverlight misconceptions, bad reviews, bad comparisons


Michael has posted a comment here and offered himself up to the gauntlet and apologized for his article.  Hewrites below:
Tim did me a favor with this article, and his comments on Connected Internet. I have left the article up on Connected, because frankly, I deserve the lumps I get over it.
Anyone who has spent more than 5 minutes talking with me, reading this blog, or listening to me on podcasts (Herding CodeThirsty DeveloperMisfit Geek) will know that I LOVE Microsoft.  I’m not ashamed to admit it and I’m not ashamed about my passion for the company or technology it produces.  I’m also not afraid to admit when and where we suck.  I don’t use every Microsoft product…if there are ones that I feel are better for how I use them, then I pick the better tools/technology.  There, bias stated.
I also think that I’m a fair person when it comes to comparisons and reviews and answering questions about competition, etc.  I welcome those conversations.  When I participate in them I do my best to be informed or point out where I’m not informed.  When not informed I try not to make definitive opinions until I have been informed by research or in trying it out for myself.
So you could imagine (like others) that I get frustrated when I see, hear, read things based on bad information, and what seems like no research has been done.  I’ve got thick skin, can usually comment and brush it off.  But today I read something that just triggered a twitch response in me that is making me reply.  It isn’t because of this post only, but because others have written articles on Silverlight that have used the same ill-informed bias.  The one that got me today was from Michael Lankton written for Connected Internet titled 10 Reasons Why Flash is Better than Silverlight.  Michael’s bio talks about him being an AV enthusiast and a corrections officer.  It briefly talks about him having ‘some coder and sysadmin in his history’ – here’s the full bio:
About the Author: Michael was a bass player in a hardcore punk band in the 80's and spent the 90's building and riding custom Harleys. As strange a combination as it may seem, Mike also has some coder and sysadmin in his history as well. At 43 Mike's now a husband and dad, and works as a Corrections Officer in a maximum security lockdown unit by day, and is admin at AV Enthusiast and contributor to Connected Internet when time allows. Mike is also passionate about food and travel.
So, bravo for Connected Internet for picking someone acutely aware of the landscape of the RIA space to do this comparison.  Oh wait.
A few people have commented on the post and JC being first had a lot of good points, refuting most of the bad information but Michael hasn’t corrected anything (despite saying so).  I’ve posted a comment offering to provide accurate information for him (and I’ll extend to anyone) in doing an evaluation.  You should be informed about the capabilities before doing things like this.  In that spirit, since there are some common misconceptions noted in Michael’s post that are incorrect, I had a moment of thought to note them (which others have already added their comments as well).
Michael’s intro paragraph says “you have better options for embedding video and audio content into a web page” than Flash or Silverlight.  Really?  Is this the wondrous HTML5 you speak of?  That isn’t complete, only supported in certain versions of browsers and requires likely a different encoding of the media than you already have?  Yeah, thought so.  Let’s be honest.  Flash and Silverlight are *the* ways to leverage media in mainstream applications today.  Are there alternatives?  Sure.  Are they more pervasive?  No.  On to the article after this little intro correction now.
1. Platform compatibility. 
MYTH: Michael notes the platform where we are supported and on Mac says “only just recently too.” 
FACT: Silverlight has been supported on Mac platforms since it’s incarnation.  The current managed code versions are supported on Intel-based Macs only.  A simple check of the system requirements would have found this.
In the comments Michael states that what he meant by this is that .NET is required.  We’ll get to that in point 9.
MYTH: Windows servers are required for Silverlight.
FACT: You could serve up Silverlight from your Samba share if you want.  Silverlight is a client technology…we don’t care what is on the server.  The only thing we require (for security) is that the XAP must be served with the right content MIME type (application/x-silverlight-app).  That’s it.  And every web server out there can have this MIME type.
2. Market penetration.
Our latest install statistics we see from our downloads, etc. as announced at MIX09 put us around 1/3 market penetration.  This is continuing to grow.  I honestly don’t have daily visibility to this number to give you current stats.  Michael makes a note “Not sure about that, as some independent studies show it as low as 6%” – um, cite the study?  If not, that’s a blatant assumption.  Heck even the much disputed riastats.com shows penetration at 34%.  Again, cite the source, or move along.  I even cite riastats.com here, although that’s not the benchmark that Microsoft uses…but at least I’m citing where I pull the number from (the 34% number, not the 1/3).
3. 64-bit web browser support. 
It’s funny that in the comments Michael says to a commenter not to talk about beta technologies, yet in this point here that’s all the evidence he has: An alpha of Flash for 64-bit.  Silverlight doesn’t have a 64-bit plugin.  Neither does Flash.  Enough said.
4. Supported image formats.
I couldn’t find a definitive source on what image formats Flash officially supports with no extensibility, but I think it is JPG, PNG and GIF (someone cite a source if you have better data).  True, Silverlight doesn’t support GIF.  I’m not upset about it.  Guess what though…we havean extensible platform and if you absolutely need to support your GIFs from 1997, you can.
5. Package Delivery.
MYTH: Silverlight files are loose and uncompressed.
FACT: Silverlight files are packaged into a XAP file which is a standard compressed/archive format.
In fact, just rename to .zip and use your favorite tool to see the contents.  If you think your favorite tool can get even better compression…feel free to recompress again.  We think we have decent improved compression. 
Oh and we also support cached assemblies, partitioning applications, and other techniques to minimize the size of your application base file.  This point tells me he’s evaluating on Silverlight 1.0 (which didn’t leverage the XAP package and was in fact loose files – which could be gzip/deflate compressed by the server btw).
6. Audio.
MYTH: Silverlight does not support APIs for generating and controlling audio.
FACT: Silverlight has a MediaElement control for controlling audio/video, MediaStreamSource API for providing your own decode/logic and APIs for RAW audio, video stream. 
Again, do your research.  Samples available for this here (extensible media format support sample) and here.
7.  Portability.
I’m not sure his description of Flash’s abilities here are even accurate.  I *think* he may be talking about just running a SWF file using the standalone Flash player, but I wonder if he also means AIR here as well.  I’m just not sure (and he doesn’t indicate).  Silverlight has the capability to run out-of-browser.  Is it a full-trust application like AIR?  No.  But again, he doesn’t clarify here what he’s referring to.  Sure Flash has a standalone player, but I can’t remember the last time I played only a SWF.  If referring to AIR, there are some comparisons that could be drawn, but bottom line is you can run Silverlight applications out of the browser.
8.  Accessibility.
MYTH: Silverlight is not an accessible technology.
FACT: Silverlight can be developed with accessibility in mind.
Michael points out “changing color schemes” and I think is referring to high-contrast mode.  Yes we have that.  But we also have caption support for media files and have the ability to integrate with other accessible technologies.  Here’s some resources:
  • Accessible Media Project (full open source implementation of an accessible media player).  Note: that this is built upon *existing* APIs that are built-in to the product.
  • Accessibility in Silverlight with Mark Rideout here and here.
  • Buttercup Reader – an implementation of an accessible application in Silverlight.
9.  Client-server communication.
MYTH: You must use .NET server technologies for service communication on Silverlight.
FACT: Silverlight can communicate with ASP.NET web services, WCF, SOAP services and REST APIs.  ASP.NET on the server is not required for client-server communication.
Michael’s assertion here is simply incorrect.  Silverlight has a network stack available to developers to communicate with servers/services of all kinds and also includes a Socket implementation if you so desire.  This is just completely false what Michael notes here.
There are some technologies we are developing (.NET RIA Services) that do require .NET on the server and provide a better experience for developers using Microsoft technologies front-to-back.  This, however, is not a requirement of Silverlight.  Use your Ruby REST api if you’d like.
10.  3D rendering.
I’m definitely not an expert in 3D.  I have to admit I don’t know the capabilities of Flash in this regard.  Silverlight does, however, support perspective 3D (taking a 2D object and putting it in 3D space).  Do we have full on support for 3D meshes, etc.  No, we don’t right now.  I *think* (again, Flashers correct me if I’m wrong) that Flash’s implementation is similar based on some quick search research.  I’m willing to admit I’m wrong here on their implementation.
We do have several ways to extend 3D type models though:
  • Kit3D – an open source 3D graphics engine for Silverlight.
  • Balder – a managed game engine with 2D and 3D support.
  • Zam3D – a commercial product for exporting 3D environments to XAML
As for game development.  Sigh.  Yes it can be done.  In fact how about a platform that lets you reuse technology to develop a game for desktop, browser, XBOX and Zune?  Check out Silver Arcade for some casual games that people are developing.  We’ve also got a thriving ecosystem around physics engines that are open source as well!  Casual games not your thing?  How about Quake in Silverlight?
Michael ends his article with these words (emphasis mine):
I have a platform to express my opinions, and they are generally backed up with solid experience or data to justify them. I am not always right, and I welcome anyone who disagrees with my thoughts on Microsoft’s Silverlight to begin that discussion in the comments section.
Michael – you have been engaged in the comment section and haven’t corrected where you are wrong.  Your opinion, this time, is not backed up with solid experience or data.  Period.

Wednesday, April 18, 2012

Basic Questions on Silverlight Technology

  1. What is Microsoft Silverlight?
  2. Why use Silverlight?
  3. Which platforms does Silverlight support?
  4. Which browsers does Silverlight support?
  5. What are the system requirements for Silverlight?
  6. What is Moonlight?
  7. What are the goals of Moonlight?
  8. Is Silverlight free?
  9. What is the difference between Silverlight 1.0 and 2?
  10. What is the Silverlight plug-in?
  11. What is Silverlight Runtime?
  12. What is Silverlight SDK?
  13. What are the tools required to develop Silverlight applications?
  14. Which tool to use - Expression Studio or Visual Studio?
  15. What are the Silverlight versions available so far?
  16. What is a .xap file?
  17. How does XAP work?
  18. How do I use a .xap file?
  19. Can we add a reference to a Class Library project in a Silverlight application project?
  20. What is a Silverlight.js file?
  21. What is the use of the ClientBin folder?
  22. How to change the default page of a Silverlight application?
  23. What is XAML?
  24. What is the AppManifest.xml file?
  25. What files are contained within a .xap file?
  26. What is app.xaml?
  27. What is the Silverlight official name?
  28. What are the main features and benefits of Silverlight?
  29. What is MainPage.xaml?
  30. Which language is Silverlight developed in?
  31. Can I consume WCF and ASP.NET Web Services in Silverlight?
  32. What are Deep Zoom and Deep Zoom Composer?
  33. What is the difference between WPF and Silverlight?
  34. What is the difference between Silverlight and Flash?
  35. What is the difference between Silverlight and ASP.NET AJAX?
  36. What are the different Layout controls available in Silverlight applications?
  37. Are XAML files compiled or built at runtime?
  38. What is the long-term goal or vision for Silverlight?
  39. Do I need to have the .NET Framework installed in order to use Silverlight?
  40. What are the other RIA technologies besides Silverlight?
  41. What is meant by RIA?
  42. What is .NET RIA Services?
  43. What are the design files and the code-behind files in Silverlight?
  44. Who is using Silverlight?
  45. What features are missing from Silverlight presentation markup that will be supported in WPF?
  46. Will I need more memory, a faster processor, or a better Graphics Processing Unit (GPU)?
  47. How does Silverlight make the Microsoft development system better?
  48. What is the relationship and difference between Silverlight and ASP.NET?
  49. When to use Silverlight, ASP.NET, or both?
  50. What are the new features of Silverlight 4?