The ramblings of web developer Beau Brownlee

Posts Tagged ‘ Silverlight ’

 
Thursday, April 7th, 2011

I just read this blog post written by Dean Wilson and it really got me thinking about the difference between those who play with technology and like to think that they actually know something about it and those who actually work with it in depth and understand the purpose of the technology. The problem with those who play and have opinions is that they only understand the purpose of the technology in their own sphere of life experiences. So, in answer to Dean Wilsons’ article I would like to explain (once again) why Silverlight exists and why it isn’t here to threaten HTML5.

The Purpose

The purpose of Silverlight is NOT ONLY VIDEO!!!! It is also to give developers capabilities that they do not have given the Javascript/HTML5/CSS environment, and yes, I mean desktop browser applications not just Microsoft Phone. Currently there are several things that Silverlight has that HTML5 doesn’t have and no one is talking about ever adding these capabilities which, I might add, is not necessarily a bad thing. So what are these capabilities that I’m speaking of? Here’s a list. And please please please keep in mind that this IS NOT AN HTML5 BASHING SESSION!!!! I am very simply, pragmatically as possible listing what Silverlight can do that HTML5 cannot do and many times shouldn’t do. I’m both an HTML5 and Silverlight developer.

The Capabilities

- Powerful client/server encryption.
     * Javascript simply doesn’t numbers big enough to handle the calculations needed to produce very powerful algorithms such as AES where Silverlight can handle these types of algorithms in applications that require the highest amount of security.

- Multithreading
     * Javascript is currently single threaded. Google gears introduced the ‘Worker Pool’ and HTML5 is bringing ‘Web Workers’ but it is still not true threading (not to diminish this new exciting feature for HTML5 however). Silverlight is truly multithreaded and there are many advantages to this.

- File System Access
     * Javascript and HTML5 do not have access to the file system where Silverlight does. There is no one talking about giving this ability to Javascript or HTML5 for security reasons, however in cases where this would be necessary Silverlight is a good alternative.

- Printing
     * The only capabilities that Javascript/HTML5 has when it comes to printing is to tell the browser to print the current page. Silverlight offers more capabilities to make adjustments when printing and to select what objects to print and what objects to exclude.

- Web Cam
     * Silverlight 4 introduced some great new features for accessing a web camera and streaming video to your Silverlight application. There are a lot of amazing possibilities especially since you can control and edit and filter the video.

- Client Side File generation
     * Many web applications have ways of exporting data sets displayed in your app to a file format such as excel or PDF. All of this must occur on the server side and then download the file to the client computer. All of which takes a lot of resources if there are many users doing this at once. Silverlight offers the ability to generate PDFs, Excel documents and much more on the clients computer thereby reducing the amount of processing required on the server and reducing the amount of data going over the wire and effectively distributing the work load amongst many computers.

- Binary Compression
     * There are many ways in which you can compress the data going to and from your browser. GZIP being one of the more common. Silverlight offers binary encoding for its data which is much more compressed than GZIP and it raises performance.

- Network Performance
     * Modern browsers allow you to connect to a maximum of 2 simultaneous connections at a time (unless you go to about:config or something similar and manually change underlying settings) whereas Silverlight allows for up to 6 simultaneous connections. As of Silverlight 5, Silverlight will be utilizing Low Latency networking as well improving performance even more.

- COM Interop
     * Some think that this is a thing of the past, however there are many instances in which the need arises to be able to interact with COM. For instance you need to access a COM enabled application such as Microsoft Office. You can send emails through Outlook, or get data from an Excel Spreadsheet. Silverlight has the capability to extend its reach into the COM environment in Out Of Browser, Trusted applications for scenarios. With Silverlight 5 we are being given the capability to p-invoke the Windows API which gives even more capabilities. For instance being able to connect with a physical device of some kind such as medical equipment.

- Out Of Browser Offline
     * While Google Gears gives some of this capability, Silverlight offers the ability to have online/offline mode and actually be installed as an application to be run outside of the browser.

- True 3D environment
     * Silverlight 5 is also offering the capability to render a true, hardware accelerated 3D environment. There are many very good looking simulations of this in Javascript such as webGL however it lacks many needed capabilities to truly create, say for instance, a first person shooter. This really opens the doors for game developers who want to build high quality 3d games that run in your browser.

- Video Streaming
     * While it is true that HTML5 has a video player, no one seems to mention that it does not have anywhere near the capabilities that Silverlight has with smooth streaming, 1080p quality, the ability to completely customize the player, slow motion (with audio pitch correction in Silverlight5) etc. While Silverlight is certainly not only about video, it shines in this area.

- Cross Platform
     * One of the biggest issues as an HTML5 developer is running into browser compatibility issues. Is this getting better? Yes and no. Yes in the sense that Microsoft has ’seen the light’ and realized (admittedly) that IE6 was a very very very bad idea and standards in HTML are very important. Hence, IE9 is going to make our lives easier. However we have more browsers to deal with today than we did a few years ago and there are still many compatibility issues to deal with that can suck a lot of time out of a developers life. Silverlight (since it is a browser plugin) works across Windows/Mac (and arguably Linux with the Moonlight project) and works in all major browsers without the types of layout and scripting compatibility issues we’ve seen with HTML/Javascript. Instead of having 5 browsers open to test, you can just run it in one browser and your assured it will work in all the others the same way.

- Other Design
     * There are many other design aspects of Silverlight that are very welcomed in the world of design. Rounded corners for instance. HTML5/CSS3 finally introduces this as well http://www.css3.info/preview/rounded-border/ with some browser. Not all support this yet. It also has the ability to do other things such as drop shadows, glow effects, gradients and much much more all in your layout code without ever having to touch photoshop. This is advantageous because you no longer have to store the PSDs externally to your project, its all in code, not to mention you don’t have to download all those extra images. Speaking of images there are a plethora of image effects that you can apply client side to images that you load in your app.

- Development Environment
     * Very large enterprise applications can get a lot of spaghetti code really fast if your not careful. C# is a very robust language that has many features that Javascript doesn’t have that are very useful to Enterprise level applications such as Classes, Interfaces, Abstract Classes, Typed object lists and many more features that would take many more articles to cover so I won’t even try to go over it all here. Other features include code compilation, more comprehensive unit testing, performance analysis tools, very powerful UI scripted tests, more powerful exception handling even at a global level (which is very important for error logging). Debugging abilities include the ability to put breakpoints in all areas of your code even in the design layout XAML (coming up in Silverlight 5).

- Development Tools
     * One area of development particularly found in Design/Development firms is the disconnect between designers and developers. Each developer reading this who has ever worked with a Designer has some story of some design that seemed artistic to the designer but ended up being nightmarish to implement. One of the tools that Silverlight offers is Blend. Blend is a design tool that has the look and feel of programs such as Photoshop and even has simple tools for creating design elements such as shapes, gradients etc. This coupled with an image editing application gives designers much more power and developers less headache. The beauty of this is that whatever the Designer creates in Blend is immediately translated into XAML code that is automatically decoupled from the developers C# code effectively shrinking the gap between designers and developers. This isn’t a silver bullet mind you but it is moving in the right direction.

So whats your point? Should we only use Silverlight?

That is absolutely not my point. There are many scenarios in which Silverlight is a terrible idea. Say for instance you want to have a very content driven website that is very visible to search engines. Silverlight is most definitely NOT a good option for something like that. Also, while the number of computers that currently have Silverlight already installed is growing at an astounding rate given the short time Silverlight has been around, it is STILL a plugin and you STILL have to install it before your application will work. Most of the time this truly isn’t a problem given that people are already installing a plethora of plugins ranging from quicktime, flash, windows media, adobe reader, java and an infinite number of firefox/chrome/IE plugins. However there are still those who don’t like it so you have to know your audience. So there are many scenarios in which HTML5 IS the better option.

Conclusion

This is not an exhaustive list of Silverlight features. There are many more things of which Silverlight is capable example being smooth animation. However Javascript/HTML5 offer a lot of very nice animation frameworks as well so the point of this list is just to show how Silverlight differentiates from HTML5. Once again (just to reiterate) I’m not saying Silverlight is NOT better than HTML5 and HTML5 is NOT better than Silverlight. They are very simply, different technologies that have different capabilities. The key is to determine what the requirements are for your application and then make an informed decision based on the facts of what the technological capabilities are for each platform. The key for developers and consumers is choice. We now have more choices than we did before. And not just more of the same, given this list (and the many many features I haven’t listed) Silverlight is much more and this is a good thing for all of us. HTML5 however is also much more than its predecessors and is a very exciting technology to say the least. At the end of the day we cannot ignore technologies that are different because we’re too scared to learn something new. This will only serve to narrow our perspective and make us less than we could be. Its time to understand these technologies and the vacuum that they are trying to fill and why and admitting that those vacuums are real and need to be addressed instead of listening to those who have uninformed opinions such as Dean Wilson. This is a textbook example of ‘A little knowledge is a dangerous thing’.

 
Friday, December 3rd, 2010

Whats New?


Get Microsoft Silverlight


Of all the session of Silverlight Firestarter 2 the most interesting (for many of us) was the first. Scott Guthrie telling us for the first time what is going to happen in the future of Silverlight and what new features are coming up. Well first he started out with talking about the controversy of HTML5/Silverilght and reassuring everyone that Microsoft is dedicated to both HTML5 and Silverlight equally. One of the ways that Microsoft is adopting Silverlight internally is a new reporting application from the SQL team which is very powerful.

What are the new features?

Here is a quick list of some of the new features:

  • Media
  • - 1080p Video Streaming
  • - Audio pitch correction (fast forward doesn’t make people sound like chipmunks)
  • - Better power management
  • - Remote control options
  • Application

  • - Breakpoints in XAML (databinding debugging)
  • - Alot more options for very simple animations for very flexable UI
  • - Native MVVM
  • - Custom Markup extensions
  • - Relative source binding
  • - Low latency networking (much improved networking)
  • Printing

  • - Improved text clarity
  • - Improved Print API (ability to print just what you want)
  • Graphics

  • - integrated Pivot Viewer control (eye popping graphics)
  • - Immediate mode graphics api
  • - GPU accelerated 3D (this opens up a lot of doors)
  • Out of Browser
  • - P-Invoke (ability to invoke external dlls including system win dlls)
  • - Multiple windows
  • Testing

  • - Automated recording testing
  • - Performance monitoring (CPU/Memory etc)
  • Performance

  • - Hardware Acceleration
  • - 64 bit

Whew! Wow that’s a lot. Thanks so much to the Silverlight team for so much work. We are all very excited for the new launch of Silverlight 5 and all of the new capabilities it brings to the table!!!


Get Microsoft Silverlight

This is a great video from Silverlight TV. One of the powerful things you can do with silverlight is more robust client side error handling than most web applications. Kyle McClellan walks us through some great techniques on how to do this. He also gives some useful tips on data binding for comboboxes as well as walking us through metadata and how it can be used in validation.

 
Tuesday, November 16th, 2010

Silverlight-Firestarter-2-December-2010-LandingPage-Banner Silverlight Firestarter 2010

Silverlight Firestarter is back for 2010. This is looking to be a great event with a ton of major players in the Silverlight realm with names such as Scott Guthrie, John Papa, Tim Heuer and more. This is a free event for current Silverlight developers and also those who are interested in Silverlight as a development platform. Even if your an HTML5/CSS developer it’s always good to know whats going on with different technologies.

What will be discussed?

Scott will start us off with ‘The Future of Silverlight’. This should be very interesting given the recent rumors that Silverlight is dead. Next up is Jesse Liberty on Data Binding Strategies with Silverlight and WP7. Later on we’ll hear from Yavor Georgiev on building apps with REST services and LINQ. Among other topics will be MVVM, Installation, Profiling and Performance and more. This promises to be a very fruitful event and at a price that can’t be beat!

 
Thursday, September 9th, 2010

So the issue that I ran into recently is that I’m getting data in an observable object list and then getting an updated list. I need to be able to compare each object in the list to see if it has been updated or not. The problem is that I have a lot of properties in each object and I had several object lists which I needed to compare. The solution I wanted involves IComparable. This is a very simple interface that implements CompareTo method only. CompareTo receives an object and returns an integer. This interface is used for comparing and doing things like sorting in arrays but in this case all I need to check for is if the CompareTo returns 0 (equals) or anything but 0 (not equal).

Another problem is that to implement this function you have to write all the checking code yourself and if you have alot of properties to check you have to do that manually somehow. I wanted something to simply check to see if all properties in the current object and the object passed in through CompareTo function were equal. Here is some code to do that:

// Implement IComparable interface and use this as your function
#region IComparable Members
            public int CompareTo(object obj)
            {
                int return_value = 0;
 
                if (obj.GetType() == this.GetType())
                {
                    Type t = this.GetType();
 
                    foreach (PropertyInfo p in t.GetProperties())
                    {
                        Type t2 = obj.GetType();
 
                        object prop1_value = p.GetValue(this, null);
                        object prop1_name = p.Name;
 
                        foreach (PropertyInfo p2 in t2.GetProperties())
                        {
                            object prop2_value = p2.GetValue(obj, null);
                            object prop2_name = p2.Name;
 
                            if (prop1_name == prop2_name)
                            {
                                if (prop1_value != null && prop2_value != null)
                                {
                                    if (!prop1_value.Equals(prop2_value))
                                    {
                                        return_value++;
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
                else
                {
                    return_value++;
                }
                return return_value;
            }
            #endregion

This uses system.reflection to iterate through the properties in both objects comparing the values using the ‘Equals’ method to validate the values are the same. If the properties are not the same the return_value is incremented and more than 0 is returned. This is pretty generic and should work with most classes you build. You may need to add in an if statement to filter out properties you do not wish to include in this comparison as this just checks all properties in the object.

 
Wednesday, June 23rd, 2010

I recently had the need for printing a Google maps static image map in a Silverlight application. It needed to actually be embedded in the Silverlight app to take advantage of the Silverlight 4 printing library (a topic I will touch on later). I wrote an API to make it easy to do pretty much every thing that the Google static API allows you to do. Here’s a quick demo of what the results look like in silverlight:


(more…)

 
Wednesday, June 2nd, 2010

One of the things I needed recently is a simple way to have a textbox that had a watermark in it. Apparantly SilverLight 4 provides it,,, and it doesn’t provide it. Check this post out. I really couldn’t help but laugh when I saw this. ‘Do not use in a Silverlight 4 application.’ and at the same time the supported version is only Silverlight 4. Aaah yes, well the only other solution is to use a watermark textbox someone else has created or to make your own. I opted to make my own. Before we get into the code here it is:

This just gives you a basic idea of what you can do. The first textbox is the user control that has watermark capabilities. If you click on the water marked textbox it will clear it out and be ready for input. If you do not type in any text and leave it blank and click on the second textbox it will replace the watermark. If you click the ‘Get Text’ button it will show blank because you do not want the watermark to count as valid text. If you click ‘Set Text’ it will programatically set the text in the textbox and you will notice that the watermark disappears.

(more…)

 
Thursday, May 27th, 2010

Reading an xml file is something that every developer has to do at some point (if not regularly). XML protocol is extremely prevalent across all technologies which makes it important to understand how to parse it. Sivlerlight exposes System.XML.Linq namespace that has all the needed classes to use Linq to query your XML to get the node/s that you need.

Always Starts with the Document

As with every XML reader you start out by creating an instance of the document and then filling it with the XML file’s data. In this case Silverlight provides ‘XDocument’ class to instantiate the document object and then the ‘Load’ method to read the data into the object. Then once we’ve loaded the object with data then we can run a traditional Linq query on the data.

Test Case

So lets run through a test case. Lets say we have a configuration file in which we want to determine what logo to display based on the url that called it. So here is our example xml:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <Logos>
    <Logo url="url1">
      <LoginWindowLogo>/namespace;path/img1.png</LoginWindowLogo>
    </Logo>
    <Logo url="url2">
      <LoginWindowLogo>/namespace;path/img2.png</LoginWindowLogo>
    </Logo>
  </Logos>
</configuration>

And here is the C# code to read it:

XDocument document = XDocument.Load("Config.xml");
 
            var images = (from e in document.Descendants("Logo")
                          where e.Attribute("url").Value == App.Current.Host.Source.Host
                          select new
                          {
                              LoginWindowLogo = e.Element("LoginWindowLogo").Value,
                          }).FirstOrDefault();
 
            if (images != null)
            {
                loginwindowlogopath = images.LoginWindowLogo;
            }

App.Current.Host.Source.Host is the property that gives you the current apps domain, the function ‘FirstOrDefault’ get the results and turn it into an object that just has the properties selected.

 
Wednesday, May 26th, 2010

An advantage of using Silverlight is the fact that the entire app is cached locally. While this may take a while to download initially, after everything is downloaded the app runs very very fast and only requires you download information asynchronously from a web service. The only problem is, what if you make changes? Since the app is cached those changes are sometimes not downloaded automatically. So what to do? Lars Holm Jensen wrote a nifty little post that shows how you can determine when the last time the silverlight package was was deployed by reading the datetime stamp on the ‘xap’ file. Just in case you didn’t click on the link, here’s the code:

<object id="Xaml1" data="data:application/x-silverlight-2," type="application/x-silverlight-2"
width="100%" height="100%">
<%
string orgSourceValue = @"ClientBin/SilverlightApp.xap";
string param;
 
if (System.Diagnostics.Debugger.IsAttached)
param = "<param name=\"source\" value=\"" + orgSourceValue + "\" />";
else
{
string xappath = HttpContext.Current.Server.MapPath(@"") + @"\" + orgSourceValue;
 
DateTime xapCreationDate = System.IO.File.GetLastWriteTime(xappath);
param = "<param name=\"source\" value=\"" + orgSourceValue + "?ignore="
+ xapCreationDate.ToString() + "\" />";
}
 
Response.Write(param);
%>
 
<param name="onError" value="onSilverlightError" />

The ‘if’ statement checks to see if your debugging. If you are, then grab the latest/greatest. If not, then it’s assumed that you are in production mode and then it checks to see if you have the latest and greatest. If you don’t, then download the latest version. Thanks Lars!

 
Wednesday, May 26th, 2010

One very important task you have as a developer is to keep track of errors. Errors you ask? ‘Errors’? ‘Not me, I write bug free code!’. Ok Mr. Programming God, but for the rest of us mortals, we have to do something to keep track of all the human errors that get embedded into our code. There are many different ways to store these errors, some people do it in flat files, others in databases. We won’t be talking about where to store these errors, just how to get them from silverlight.

The problem

Web applications have always presented a particular problem when it comes to catching errors and logging them in a central place. First, with Javascript it is difficult to know when an error has occurred and hasn’t been caught already and if so, it’s difficult to do anything after that as many javascript errors will break the app entirely and not run anymore code.

The Solution… A Solution

Silverlight attempts to simplify this process by having a central place to catch any unhandled exceptions and then do something with them. You can catch them in the App.xaml.css file. Here is an example:

private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
    {
      //Ignores logging if your debugging
      if (!System.Diagnostics.Debugger.IsAttached)
      {
        /*TODO: Some method to save the 
           the error to a file or database by using
           e.ExceptionObject.Message, e.ExceptionObject.StackTrace
        */
        e.Handled = true;
        ChildWindow errorWin = new ErrorWindow("Error", "An Error has been logged"));
        errorWin.Show();
      }
    }

Does this mean that we don’t need to do any try/catches? No, we still need to handle errors and do something with them, but in the event that we miss an error, it will be caught here and logged so that we can more easily debug the released code.

cheap software