If you are using the ASP.NET Menu control, you might encounter under certain circumstances an issue where the menu appears as a white box in IE8 Standards Mode.
What IE8 is doing IS correct (by design), in the sense that in Standards mode IE8 is following the standards. Specifically, (element).currentStyle.zIndex returns "auto" in Standards mode when zindex has not been set. The ASP.NET Menu control assumes a different value.
I’d like to suggest a few possible workarounds to solve quickly the issue (note, you can use either one of them, depending on your scenario):
1 – Overriding the z-index property
You can manually set the z-index property of the Menu items using the DynamicMenuStyle property of the asp:Menu control (note lines 9-14 and 20). Full source code is:
1: <head runat="server">
2: <title></title>
3: <style type="text/css">
4: body
5: {
6: background-color: Silver;
7: }
8: </style>
9: <style type="text/css">
10: .IE8Fix
11: {
12: z-index: 100;
13: }
14: </style>
15: </head>
16: <body>
17: <form id="form1" runat="server">
18: <div>
19: <asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1">
20: <DynamicMenuStyle CssClass="IE8Fix" />
21: </asp:Menu>
22: <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
23: </div>
24: </form>
25: </body>
This solution is the least intrusive, but it require a page-by-page update (unless your menu is a Master Page).
2 – Using CSS Friendly Control Adapters
Thanks to Tim for this solution. In order to add the CSS Friendly adapter to your project, you will need to:
The CSS Friendly Control Adapters will render all the listed controls (Menu, TreeView, DetailsView, …) using CSS and HTML standards.
3 – Add the IE7 META tag to the project
By default, Windows Internet Explorer 8 will attempt to display content using its most standards-compliant mode, the IE8 Standards mode. However you can still switch to the IE7 Standards mode adding a particular META TAG to the head of the page:
1: <html xmlns="http://www.w3.org/1999/xhtml">
2: <head runat="server">
3: <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
4:
5: <title>IE8 ASP.NET Fix</title>
6: </head>
7: <body>
Using the tag, the website in IE8 will look and work in the same way as it does in IE7.
You can do a “live test” of this feature without the need to modify the page, using the new IE8 Developer Toolbar (press F12 to open the toolbar, and switch the Document Mode to IE7 Standards).
Note that you can set up the META tag at page level, at web.config level, or in IIS, or in Apache, …
What happens next?
The ASP.NET team is currently working on this issue and we will most likely create an official KB to address this issue before IE goes RTW.
EDIT: Hotfix are now available. Check here.
Thanks to all the community feedbacks we received so far.
A question I’ve been asked recently is “How can I detect IE8 using JavaScript?”. There are several ways to accomplish this task, and each one will have his pros and cons. In this post I will show the best practices to detect IE8 on real world scenarios.
If you have any feedback or you would like to suggest an alternative method, please feel free to add a comment to this post.
Detect the IE rendering engine
In the past, the Version Token (the token of the User Agent string which looks like “MSIE 7.0”) used to be a clear indicator of the browser version (IE6, IE7, …). Today, since IE8 include 3 rendering engines (IE8 Standards, IE7 Compatibility, IE6 Quirks), IE8 will set the Version Token dynamically, based on the user compatibility settings for each site.
For instance:
As you can see from the previous examples, the VT shows what rendering engine is used by IE to display the site...no matter the version of the browser.
function getInternetExplorerVersion() {
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer') {
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat(RegExp.$1);
}
return rv;
function checkVersion() {
var msg = "You're not using Windows Internet Explorer.";
var ver = getInternetExplorerVersion();
if (ver > -1) {
if (ver >= 8.0)
msg = "You're using a recent copy of Windows Internet Explorer."
else
msg = "You should upgrade your copy of Windows Internet Explorer.";
alert(msg);
Check this MSDN article for more information about this function.
Detect if Web Slices, Accelerator, Visual Search are supported by the browser
The previous function will not tell us if the Web Slices, Accelerators and Visual Search are supported by the current browser (remember, those features always work in IE8, regardless the rendering engine adopted).
In general, the best practice is to check if each feature is supported by the current browser; this statement might sound generic or “too complex”. However, since web standards and browser keep evolving, it’s not possible to know today if a feature will be supported from the same (or other browsers) in the future. Obviously this concept applies to either Internet Explorer, Firefox, Opera, ….
In particular, I recommend to use the following functions:
function WebSliceSupported {
return (typeof (window.external.AddToFavoritesBar) != "undefined");
function AcceleratorSupported {
return (typeof (window.external.AddService) != "undefined");
function VisualSearchSupported {
NOTE: in case you are adding web slices to your site, I recommend to build them for any browser (they will be transparent to other browsers…); or, if you want to send them only to IE8, you should detect the browser on the server side.
Detect IE as browser
There are scenarios where you might still want to know the version of IE installed on the machine. For instance, let’s say you want to suggest your users to upgrade from IE6 to IE8.
In this case, the best client-side solution is to check if the query string contains the new token “Trident 4.0”.
function IsIE8Browser() {
var rv = -1;
var re = new RegExp("Trident\/([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null) {
return (rv == 4);
NOTE: since the Trident number will most likely change in the future, we don’t recommend to use this function as an indicator of web slices, accelerators or visual search support.
Other useful resources
IE Blog: IE8 User Agent string
Version Vectors
Happy detection!
Internet Explorer 8 brings a lot of new features to web developers. Check out these free Virtual Labs if you want to know more!
Virtual Lab
Manual
Building Web Slices with Internet Explorer 8
Preparing for Internet Explorer 8- Application Compatibility
Using Accelerators and Web Slices in the Enterprise with Internet Explorer 8
Creating Accelerators In Internet Explorer 8
Internet Explorer 8 - Debugging and Application Compatibility
Internet Explorer 8 Improved Programmability
Using New AJAX Enhanced Layout Standards Support with Internet Explorer 8
In the previous post, I showcased the Microsoft commitment to an open and interoperable Web by rendering Web pages in their standards-compliant mode by default. We also understand that developers want to build richer Web experiences with great interoperability, so we started delivering support for some of the features from the HTML 5 Working Draft. This specification is still a work in progress; very important technical discussions are continuing in the W3C HTML Working Group on many subjects.
In this post you will see some of the features from the W3C HTML 5 Working Draft, from the W3C Web Applications specification, and from the ECMAScript-262 Language specification (a.k.a. JavaScript) that the IE Team has already implemented in Internet Explorer 8.
For each topic I will provide scenarios or ideas that you can start using straight away, plus the reference to the original specification, the MSDN documentation, and a demo. You can run most of the demos either online or offline.
The source code is available here.
Although users are increasingly “always connected” to a network, it’s not rare to lose Wi-Fi or cable connectivity. Imagine, for example, the scenario where a user is registering to a new site: he fills in many textboxes with his personal information and then – as he press the “Submit” button – the page fails because the network is no longer discoverable. This will result in a bad user experience, as the user – as soon as the network comes up again - will need to input all the data again.
Using the network connectivity events, you can easily detect whether or not the browser is connected to a network.
Further information: W3C Spec - MSDN
You are probably familiar with cookies as a way to store information on the client side; cookies however, aren't very good at handling scenarios where the user could be carrying out multiple transactions in different windows at the same time. Also, because cookies are transmitted with every request, they don’t allow for scenarios where Web applications may need to store megabytes of user data, such as entire user-authored documents or a user's mailbox, on the client side for performance reasons.
Now you can Use the new local or session storage area to store megabytes of user data for the current session or domain.
User agents commonly apply same-origin restrictions to network requests. These restrictions prevent a client-side Web application that is running from one origin, from obtaining data retrieved from another origin.
Using the new Cross Domain Request API, a response can include an Access-Control-Allow-Origin header in order to allow access to the resource's contents on external domains.
* Since you will need to modify the code on the server side, you need to run this demo offline.
If you are building AJAX applications, you are probably familiar with the JavaScript Object Notation (JSON). In the past, you had to rely on external JavaScript libraries (for example, json.org) to serialize and de-serialize JSON. Due to increasing requests from Web developers to be able to perform this operation in a secure and performing way, the JSON object has been introduced in the ECMAScript specification and implemented natively in Internet Explorer 8.
Using JSON you can easily parse and construct JSON text.
Further information: ECMAScript Spec - MSDN
Having the JSON object built natively in the browser means that IE8 will take care of the security layer automatically; it will also execute the serializations much faster, as all the code is optimized to run at a low level. In this sample, I’m running a batch of stringify/parse using the JSON library from the json.org site and then the Native IE8 JSON object. You will notice that the latter is up to ~10x faster.
IE8 introduces Asynchronous JavaScript and XML (AJAX) Navigations. These features are designed to help alleviate the frustration of end users with AJAX-enabled Web sites that are not navigable through the Back and Forward buttons, and that do not update the browsing history. With just a few simple lines of script, you can add AJAX Navigations to your Web site, making the navigation of your AJAX-enabled content as smooth and seamless as "traditional" navigation.
Selectors, which are widely used in CSS, are patterns that match against elements in a tree structure. The Selectors API specification defines methods for retrieving Element nodes from the DOM by matching against a group of selectors. It is often desirable to perform DOM operations on a specific set of elements in a document.
The CSS Selectors methods simplify the process of acquiring specific elements, especially compared with the more verbose techniques defined and used in the past.
Since the CSS Selectors are built into the browser, they perform better than any other JavaScript implementation (for example, older versions of jQuery). In this demo, I’m using the DOM navigation and the Native IE8 CSS Selectors to select all the elements with the inner class. You can see how the performance of the IE8 CSS selectors is dramatically better than the previous approach.
Today, Web developers need improved programming functionality, flexibility, and features to enable them to build the next generation of Web applications. To further empower Web developers with the programming tools necessary to build new JavaScript scenarios, IE8 offers a collection of features that extend some of JavaScript's advanced functionality into the Document Object Model (DOM).
Again, I’d like to remind you that the source code for all the demos in this post is available for download here.
I’m excited and looking forward to seeing these new functionalities implemented across the Web!
<Giorgio />
I’m happy to announce we just released a Web Application Toolkit for Internet Explorer 8!
The goal of this Web Application Toolkit is to leverage the new features in Internet Explorer 8 (Web Slices, Accelerators and Visual Search Providers) to extend the reach of your Web site and services also to those users that are not on your site.
The kit include sample projects and the following controls:
Download the code and samples here. Watch a screencast to get started here.
Happy coding!
Creating Web Slices is extremely easy and fast, and at the same time it can provide amazing results. In this post I will show how the Swine Flu Web Slice has been created (in less then one hour!). The full project with source code is provided at the end of this post.
Before starting, you need a website (unless you already have one). For the sake of this scenario, we will use Microsoft Visual Web Developer 2008 Express Edition to create an ASP.Net Web Application.
IE8 Web Slices development is described in detail in this MSDN Article. In this scenario we want to have full control over the Web Slice content, so we will use an Alternative Display Source. We also want to customize the update and notification mechanism, so we will implement an Alternative Update Source. The overall architecture looks like this:
The first step is creating a standard web page (Default.aspx ), that will be used by IE8 for the Web Slice preview; the content of this page can be pure HTML, CSS, JavaScript…but also Silverlight or any other ActiveX available on the machine.
In talking with the CDC (Centers for Disease Control and Prevention) and the WHO (World Health Organization), they available made two data feeds:
Those feeds are downloaded and parsed in the code behind of the page, as follows:
private static DateTime GetLastRssUpdate()
{
using (WebClient client = new WebClient())
string content = Encoding.ASCII.GetString(client.DownloadData(Rss_Feed));
XmlDocument rssDoc = new XmlDocument();
rssDoc.LoadXml(content);
HttpContext.Current.Cache.Insert("SwineFluRssFeed", content);
return DateTime.Parse(rssDoc.SelectSingleNode("/rss/channel/item")["pubDate"].InnerXml);
Note that we are caching the feed on the server side, in order to improve the network performance. Once we have the data, we can use the ASP.Net Framework and LINQ to bind the data to our UI.
private void BindRssFeed()
string content = Cache.Get("SwineFluRssFeed") as string;
XDocument rssFeed = XDocument.Parse(content);
rssList.DataSource = (from item in rssFeed.Descendants("item")
select new
Text = Short((string)item.Element("description")),
Url = (string)item.Element("link")
}).Take(5);
rssList.DataBind();
The second step is to customize a few properties of the web slices and define the logic that will notify the user when there is an update.
In order to do this, we will use a second page (SliceUpdate.aspx ).
<body>
<div class="hslice" id="SwineFlu">
<div class="entry-title" style="display: none">
Swine Flu Updates
</div>
<a href="http://visitmix.com/WebSlices/SwineFlu" rel="entry-content" style="display: none" />
<a href="http://www.cdc.gov/swineflu/" rel="Bookmark" style="display: none" target="_blank" />
<span class="ttl" style="display: none">15</span>
<div class="entry-content" runat="server" id="updateTrigger">
</body>
Let’s have a look more in detail to each section of the body:
The last step is to make the web slice discoverable. The CDC will soon include the web slice on their main site; in the meantime, the slice is available on the IE8 Addons Gallery.
The “Add to Internet Explorer” button calls a simple JavaScript function.
<button onclick="window.external.AddToFavoritesBar(
'http://visitmix.com/WebSlices/SwineFlu/SliceUpdate.aspx#SwineFlu',
'Swine Flu Updates',
'slice')">
Add to Internet Explorer
</button>
Note that the AddToFavoritesBar function point to the Alternative Update Source page followed by the ID of the slice (SliceUpdate.aspx#SwineFlu).
That’s it! With a couple of RSS feeds and a bunch of lines of code we made a very useful web slice!
The best part is that this Web Slice can easily be customized to show any other RSS or Twitter feed! ;-)
You can download the full project with the source code here. You can preview the slice here.
Twitter is a free social networking and micro-blogging service that allows users to send "updates" (or "tweets" (TW); text-based posts, up to 140 characters long) to the Twitter website. [Source: wikipedia]
Being an user of MSN (ops, Windows Live Messenger) since many years now, I get used to keep my WLM Personal Message (PM) updated.
Now, if we think about the two technologies together, isn’t a tweet kind of a public version of our personal message? Yep
For this reason, I’ve developed with my dear friends Stefano Santoro (Microsoft Student Partner from Italy) and Marco Bodoira (CE Embedded expert at BEPS) an add-in for Windows Live Messenger that keep the personal message of MSN synchronized with your Twitter status. Please note that this add-in is not supported. (More info about support below).
How does the add-in works?
When the add-in is turned on, it will keep your TW on Twitter synchronized with the PM on MSN; in fact your PM on MSN will be sent to TW within the specified polling time.
Where can I download the add-in?
You can download the setup file here, or download and view the source code here.
How do I install the add-in?
In order to start the magic synchronization, you need to install the Setup file (download it here). On the first restart of WLM, you will be asked to prompt your Twitter information (obviously your information will be saved and you will not be prompted to insert them again…). The only action required from you is to manually Turn On the add-in.
Why did you developed this add-in?
For fun.
To be used.
To show some example of interoperability between “everyday application” and web services in the cloud.
The whole communication layer with the Twitter web service uses web services, with the following two functions:
internal bool SendTwitter(string message) { if (string.IsNullOrEmpty(message)) return true; string auth = Convert.ToBase64String(Encoding.UTF8.GetBytes(Username + ":" + Password)); string status = "status=" + HttpUtility.UrlEncode(message, Encoding.UTF8); byte[] data = Encoding.ASCII.GetBytes(status); try { HttpWebRequest req = WebRequest.Create(SetStatusUrl) as HttpWebRequest; req.Method = "POST"; req.Headers.Add("Authorization", "Basic " + auth); req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = data.Length; Stream reqStream = req.GetRequestStream(); reqStream.Write(data, 0, data.Length); reqStream.Close(); return true; } catch { return false; } } internal string GetTwitter() { string auth = Convert.ToBase64String(Encoding.UTF8.GetBytes(Username + ":" + Password)); try { HttpWebRequest req = WebRequest.Create(string.Format(GetStatusUrl, Username)) as HttpWebRequest; req.Headers.Add("Authorization", "Basic " + auth); req.ContentType = "application/x-www-form-urlencoded"; XmlTextReader reader = new XmlTextReader(req.GetResponse().GetResponseStream()); string status = string.Empty; if (reader.ReadToDescendant("text")) status = reader.ReadString(); reader.Close(); return status; } catch { return ""; } }
An interesting bit of this project is the setup file, that performs the following operations:
Is the add-in supported?
NO, the add-in is not (and will not be) supported. However we tested it successfully on Windows XP 32bit (English and Italian), Windows Vista 32bit (English and Italian)…with Windows Live Messenger 8.5 and Windows Live Messenger 9.0. Please let us know if you can install it on platforms other than these.
Does the add-in need any 3rd-party components or Plus or will it ask me to pay?
NO, NO, NO. The add-in requires Windows Live Messenger and the .NET Framework 2.0 installed only. If the setup detects that you are missing the .Net Framework, it will download and install it automatically for you.
What are your Twitter account?
Want to know more about Windows Live Platform?
Have a look at those great blogs from colleagues:
Any feedback?
Please feel free to add a comment or a feedback to this post!
Thank you Happy twittering with MSN,
Giorgio, Marco & Stefano
The Deep Zoom composer is a great tool to manually design a composition. It is still in an early stage and I’m sure its team will add lot of interesting new features in the future.
Meanwhile…I think that something where it lacks is the possibility to perform a proper batch export, given a lot of images.
SCENARIO: your want to show 500 pictures using DeepZoom. Due to the high number of pictures, you decide to implement a collection and positionate the images at run-time.
Using the batch export feature of the composer, you can only create several single deepzoom composition…and you miss the option to create a collection.
Luckily the Deep Zoom application comes with a tool (SparseImageTool.exe) which is installed in the application folder. The tool allow you to create a collection from the command line, giving as parameter the SceneGraph file and the images input folder (plus other interesting parameters).
Not too bad...but...what is the SceneGraph.xml file? This file is an xml file containing the layout of our scene, with the following format:
We now have all the tools and information to programmaticly create our collection, avoiding the direct use of the UI of the composer. As proof of concept, I created an application to create a Deep Zoom collection using C#, without opening the Deep Zoom Composer UI.
Source-code of the application is attached at the bottom of this post.
I will move this application to CodePlex as soon as possible, since I believe the community could add more interesting features. Don’t you?
PS: Once you exported your collection using this tool, you can start positionating/resizing/… images using C#…I’ll write a new post about this later…
Silverlight for mobile is great. It allows you to build Rich (Mobile) Internet Application quickly and easily, using XAML and C#. HOWEVER, the .NET Compact Framework is not dead! Depending on the scenario and the application you are building, the .NET CF could still be the best technology to adopt (as we’ve seen in the MLB202 session at Tech ED EMEA).
Using the .NET Compact Framework you have access to all the low level APIs of your phone, including those need to build advanced UI with custom controls, transparency and so on…
With the support of Marco Bodoira, Embedded Consultant at BEPS Engineering, we built a sample solution to show how to use the .NET Compact Framework 3.5 and Windows Mobile’s APIs to create “graphically advanced” applications.
The article (and the source code!) will give you an overview of:
The article is available here. The source code is available here.
Thanks again to Marco and BEPS Engineering for their support.
NSS Labs, a trusted advisor to the information security community, released today two new Web Browser Security Reports:
They’ve been testing intensively the latest browsers (Apple Safari 4, Google Chrome 2, Microsoft Internet Explorer 8, Mozilla Firefox 3* and Opera 10 Beta)** to compare their security models and APIs.
Note that Internet Explorer 8 relies on the new SmartScreen® Filter technology, while Firefox, Safari and Chrome on the same SafeBrowsing API (developed by Google).
Let’s have a look at the result of their tests.
A Malware is software which is deceptive about functionality and is a security risk or a privacy risk. The term malicious software or malware refers to programs that demonstrate illegal, viral, fraudulent, or malicious behavior. For example, viruses, worms, and Trojan horses are malicious software.
The use of reputation systems to assist browsers in the fight against socially engineered malware is a strong use of cloud technologies. But, not all vendor implementations and daily operations yield the same results.
Although Firefox, Safari and Chrome are using the same security API, the results are different. From the report:
“The SafeBrowsing products’ protection rates were showing signs of converging just under 25%. This supports the notion that there are operational differences between the implementations of the API, but that the block lists are the same (or very similar)”
Online phishing is a method of identity theft that tricks you into revealing personal or financial information online. Phishers use phony websites or deceptive email messages that mimic trusted businesses and brands in order to steal personally identifiable information such as usernames, passwords, credit card numbers, and Social Security numbers.
Since phishing sites have an average lifespan of only 52 hours it is essential that the site is discovered, validated, classified, and added to the reputation system as quickly as possible. A good reputation system must be both accurate and fast in order to realize high catch rates.
From the report:
“We expected better results given the fanfare about Google’s SafeBrowsing initiative. Additionally, a third-party (Firefox) was able to utilize Google’s API to achieve significantly better protection that Google’s own browser.”
Internet Explorer 8 introduce a new technology called SmartScreen® Filter, an evolution of the previous Phishing Filter in IE8, to help protect IE8 users against the major security threats on the web today.
Eric Lawrence, Security Lead in the IE Team, has written many blog post where he introduce the feature and describe how it works. A FAQ about the Filter is available here.
If you want to know more about security in IE8, check out this video on Channel9.
For the sake of this post, based so far only on numbers, I’d like to show in action how IE8 identify and display an unsafe site to the end-user. We will use a test web site marked from the SmartScreen Filter as unsafe***.
If you browse to the site with IE8, the browser will start download the content of the page but shortly it will understand that the site is not safe and switch to a different view: a red warning alert will be offered to the end user.
The experience on other browsers, including Firefox and Chrome, would be completely different – since they don’t detect the site as unsafe…creating a big security threat for the end-user.
NSS Labs is not The Word; it is one of the (many) trusted voices on the web, with a deep expertise in this field. You might not trust their results (btw, have a look at the Appendix of their reports to understand the architecture/methodology they have in place…).
It’s interesting however what they call “an easy apple-to-apple comparison”: they run those tests back in February and they are now comparing the trend over time for each browser. I’m surprised (and pleased :)) to see that IE is the only browser with a positive trend == it’s getting better over time. All of the other browsers decreased protection, between 3 and 8% - within the margin in the error.
Does all this mean that IE8 is 100% secure? Absolutely not, but I feel secure now… :-D
NOTE:
* I wished they tested with Firefox 3.5. From the report, “Firefox 3.5 was not stable enough to be tested during the course of this test. A patch has subsequently become available to address the stability issue. We were able to manually verify that the protection was identical between versions 3.0.11 and 3.5”.
** They used the “vanilla versions” (as downloaded from site and updated). No antivirus, no add-on installed, no security group policy, no special settings…. Just the browser, as it is.
*** This site has been designed for demonstration purposes only. The test performed from the NSS Labs used a list of 12000 real suspicious sites.
Bing Maps is the first online service that provides geolocation support to all desktop and mobile browsers that support the new HTML5 Geolocation APIs. (*)
When you navigate to bing.com/maps, you will notice a new “viewfinder” icon in the top-left corner of the map. As you click it, the map will zoom automatically to your current location.
How does it work? The site implements the HTML5 Geolocation, which allow an User Agent, given the permission from the user, to query user’s location and receive her longitude and latitude coordinates.
The code that Bing used to implement this feature is really simple:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (position) {
//TODO Center the map around
position.coords.latitude and position.coords.longitude
},
function (error) {
//TODO Handle errors
});
else {
//TODO Fallback to IP resolution
The control available on bing.com/maps is freely available to any web developers; you can find all the APIs and the documentation in the Ajax SDK for Bing Maps. Preview live here.
Today the Bing Maps geo-location service works already in Internet Explorer 9, Firefox 3.5+, Chrome 10+, Safari 5.0+ and Opera 10.6+. It works great even on my Windows Phone 7 (with the Mango update)!
Note that if your browser doesn’t support HTML5 Geolocation, Bing Maps will fallback to IP location resolution.
(*) Unfortunately this is not the case for Google Maps. Although Google deserve credit for being the first to introduce this feature, they still don’t provide the geolocation support to any Internet Explorer user (including IE9). In fact the Google Maps page uses the “IE7 Compatibility” mode, which forces IE8, IE9, and IE10 to render the page using the old IE7 engine, instead of the default standard compliant engine. In other words, even if you have IE9 or IE10 installed on your machine, you can’t benefit of HTML5 features when you are visiting Google Maps. Hopefully this is something Google is working on and we will see a fix soon.
In a previous post I’ve showed how to automate the exporting process of a DeepZoom composition or collection. Meanwhile the Microsoft DeepZoom Composer tool has been updated (and new features have been added too!), breaking my previous sample.
Given the positive feedbacks I received from the previous post, I’ve decided to do some refactoring and updates to the previous solution. The current implementation include:
You can download the updated library and source code here.
The new class diagram is like so:
Given a directory containing all the images and a name for the collection, it’s now really easy to create programmatically a collection.
1: static void CreateCollection(string collectionName, string sourceImagesFolder, string outputFolder)
2: {
3: // Create a collection converter
4: CollectionConverter collectionConverter = new CollectionConverter();
5: // Required parameters
6: collectionConverter.SparseImageToolPath = GetSparseImageToolPath();
7: collectionConverter.ImagesCollection = GetImages(sourceImagesFolder); // IEnumerable<string> containing the path of the images
8: collectionConverter.ImagesDestinationFolder = outputFolder;
9: // Optional parameters
10: collectionConverter.CollectionName = collectionName;
11: collectionConverter.CollectionFormat = CollectionConverter.CollectionFormats.XML;
12: //collectionConverter.ConvertedOverlapPixels = ...
13: //collectionConverter.ConvertedTileSize = ...
14: //TODO: You can customize the exporting experience here, by setting the according parameters such as:
15: // Tile Size, File Format, Collection Format, Compression, Quality, ...
16:
17: // Attach to completion handler
18: collectionConverter.BatchCompleted += delegate
19: {
20: Console.WriteLine("Conversion completed\nPRESS <ENTER> TO EXIT");
21: };
22:
23: try
24: {
25: collectionConverter.BatchCollectionExport();
26: }
27: catch (Exception e)
28: {
29: Console.WriteLine(e.Message);
30: }
31:
32: Console.WriteLine("Conversion started...");
33: Console.ReadLine();
34: }
Have fun!
“HTML5” is huge. Different specifications are at different status: First Public Working Draft, Working Draft, Candidate Recommendation, Proposed Recommendation, and lastly Recommendation.
As we stated many times before, it’s important to make it right.
Browser makers have a big responsibility with developers: it’s wrong to claim “standard support” for a specification that is still changing. Or, at least, they should make clear it is still a work in progress (for example, by using vendor prefix extensions).
Rushing the implementation of a specific feature and call it “done deal” is dangerous and in some circumstance can bring to unpleasant results. Today we’ve seen an example of this with an important specification: Web Sockets.
Web Sockets enable Web applications to maintain bidirectional communications with server-side processes. The specification (from the WebApps WG) is currently in the “Working Draft” stage; there is also a dependency on the Web Sockets Protocol, discussed in the IETF hybi mailing list.
Chrome 4+ has been the first to implement it in a “final RTW build” at the end of 2009, followed by Safari 5.0.2. Instead Firefox was planning to support them in the version 4beta and Opera in version 11, but they never went in production (credits for monitoring its status before going live). IE doesn’t implement this spec in current build.
Over time the specification changed and each browser tried to adapt by releasing sequential implementation updates. Some developer even built “The Ultimate HTML5 Browser Support Test” based on specs like this that are still in Working Draft stage. A few users commented on IE Blog about IE being “the only browser” not supporting it yet.
On Nov 26th, Adam Barth shared the results of his experiments with IETF.
“The Upgrade-based handshake is vulnerable to attack in network configurations involving transparent (or intercepting) proxies.”
In other words, the current protocol used by Web Sockets might be unsecure and unstable.
Based on this discovery, Firefox and Opera promptly did the right thing, announcing they would disable Web Sockets in future releases – until a solution is found. At the time I’m writing this post, I haven’t seen any announcement made by Google or Apple yet, although I’m confident they will follow soon (as Mozilla developers do).
In developer language, this is what I call a “breaking change”. Changing (or even worst, removing) support for a feature from a version to the next one – possibly breaking all applications built by developers based on the assumption that the feature (a supposedly “web standard”) would have been supported moving forward.
After today announcements, I wonder how many apps using Web Sockets will need to be brought offline, or “freezed” or “re-written” – at least until the spec get more solid and secure? Did these developers use browser feature detection, or they just assumed that any version after (for example) Chrome 4 will support that feature the same way?
What about those existing enterprise solutions, for example Kaazing, that rely on the assumption that “most browsers” already support Web Sockets? Will they just use the Flash-based layer (as they do for IE today) for any browser?
Personally I like Web Sockets. I’m looking forward to seeing them available in all browsers. But I also do care about consistent implementations, that work the same (interoperable, secure, stable) way across any browser – over time. I don’t want to write some code today, falling in the “(non) Web Standard trap”, and then have to re-write my code in 1 year from now because that particular implementation wasn’t exactly ready for prime time yet and has been removed or changed.
I don’t want to see the “IE6 phenomenon” happening again to “Chrome4” or others. Do you?
Someone today was so disappointed that he created a short humoristic video…
Time to go back to W3C and IETF to discuss what went wrong and look at what we can do to accelerate the progress of this (and other) specs...
Building a great browser is complex; this is valid for Internet Explorer, Firefox, Chrome, Opera, Safari and any other browser out there.
When we started the planning of IE9, we decided to offer more visibility to developers over the progress of the platform – releasing a Platform Preview every eight week. Thanks to your help, we collected thousands of feedbacks and lastly to make IE a better product. It’s been a great journey so far – the partnership IE Team-community has been working really well!
I just ran across an article from Mike Dewey. Forgetting for a moment about the “sensational title” (which btw is funny), I believe there are also a lot of interesting observations and feedbacks. I also like the approach of suggesting (for the time being) workarounds. Thanks Mike!
Lol. Do you have a repro test? Should we call the ghost-busters?
Seriously, let me explain what (probably) happened.
IE9 by default uses the IE9 Standards Engine, which supports all the great new HTML5 stuff. Thus, if you create a plain page with the correct doc-type and you publish it on your server, it will just work.
For compatibility reason, it also allow you to specify an older engine (IE8, IE7, IE Quirks) by using the X-UA-Compatible meta tag. Note that some website specify this rule “at a server level” by setting an HTTP header on all the pages. Bottom line: even in this case, you are in control of what engine you want to use.
As you noted, globalCompositeOperation is not supported in Platform Preview 7. Or, better, we support only the source-over state. We do care about supporting this property, but we also care about it being interoperable across all browsers.
At the time we announced and shipped support for the Canvas, the other browsers were supporting the globalCompositeOperation, but they didn’t have the same rendering behaviors – making developer life very complex. Chrome and Safari in fact implemented the drawing model differently from Opera and Firefox. You can still see this in action today. For instance, navigate to this site. Firefox 4.0b8 and Chrome Canary 10.0.638 are rendering different results. [We obviously looked at all other browsers, even if I don’t mention them in this post].
Given that evident interoperability challenge, we decided it was critical to have first that conversations with the HTML Working Group – before shipping something unreliable for end-users.
Since then, we believe we made good progress – you should expect to hear more from us soon.
Good catch! It looks like you are hitting an old bug that has already been fixed (fix to come in the next build). If you see similar issues in the future, I’d strongly suggest to file a bug to Connect. More on “why Connect” at the bottom of this post.
I admit this is weird, but I can’t repro on my machine. It’s possible that this falls in the same bucket of (3).
What I noticed instead is that different browsers render your code in a different way. I created this dummy page using the code on your site (let me know if I missed something) and here’s what I get.
Personally I believe Firefox is closest to the result I was expecting. What do you think?
As you know, we highly appreciate developer feedbacks and we encourage you to try (and try to break if you want) the Platform Previews of IE9.
Remember you can download the latest build from www.ietestdrive.com and you can file a bug on Microsoft Connect. This will ensure that:
Again, thanks Mike for your feedbacks. Looking forward to the next build!
Along with all the other announcements, today I’m very happy to announce the X-Icon Editor, an HTML5 application that allows you to create high resolution icons. I’ll be honest: I love this tool. Let me show you why.
First of all, what is a high resolution icon? The ICO format supports multiple resolutions. In the past, websites usually implemented a 16x16 pixel icon. Today Internet Explorer 9 allows websites to specify crisper icons that will shine in the different parts of the UI (for example, navigation bar, taskbar, or new tab page).
The X-Icon Editor helps you build a high resolution icon that can include up to 4 sizes: 16x16, 24x24, 32x32 and 64x64 pixels.
Let’s get started. Open either Internet Explorer 9 and go to www.xiconeditor.com.
You can hand-draw your own icon or import an existing image: transparent png, gif, jpg, bmp, and ico formats are all supported. To have some fun, I’ll use my photo. After uploading the image, you can crop out just the area you are interested in working on.
From the panel on the right, you can select all the sizes that will apply to this image. In a different scenario, you might want to upload 4 different images (one for each size).
The editing tools are not super advanced, but they still allow you to be pretty flexible and creative. Let’s add some transparency to the background. In order to do this, I will use the Paint Bucket Tool to set the Alpha channel to 0 and change the Tolerance to 15%. When you click on the background, the tool will automatically detect the “adjacent area” and clear it. If you make a mistake, you can use the blue arrows to go back/go next.
Now that I’m happy with the icon at 64x64 pixels, I can click on the 32x32 box in the right panel and repeat the same Paint Bucket Tool operations. Or, after clicking the 32x32 pixel option, I can import my 64x64 pixel image and it will come in with all the same formatting, but at 32x32 pixels.. I repeat the same steps for the 24x24 and 16x16 sizes. At the end, this is what I get.
Before exporting the icon, I can preview how my icon will fit in the browser.
Moreover, since the new icon actually becomes the default icon for this page, I can do a live test and drag-and-drop my tab to the Windows 7 Taskbar.
It’s awesome--I always dreamed of being between IE9 and Visual Studio!!
I like my icon: the transparency is neat and the IE9 chrome picks up nice colors. When you click Export, the tool will generate only 1 icon, which embeds all the dimensions used (that is, where at least one pixel in the dimension is not transparent). You will also get some recommendations in regard to performance (for example, use max-age, expires date, and compress the icon using GZIP).
With the addition of one standard line, you can add it to your site…
<link rel="shortcut icon" href="favicon.ico"/>
…and you are ready to go!
Special thanks go to Gregor and the other folks at Avarice who built this awesome application. You guys rock!
Please let us know.
A short answer could be “the future of the Web”. Enough? No, especially if you are a developer.
I answered more in detail this question at PDC (links below). Here’s just one slide, where I tried to summarize what’s behind the “HTML5” term.
HTML5 is not only a marketing message, but also the bread that the developers will use for years and years. It is a critical component and as such, it’s very important to make it right. In the session I explained what “right” means for Microsoft and W3C and how we are working to move these specifications forward. Enjoy!
View session: watch the recording online
Download slides: “HTML5”: More Than Just HTML5
Btw, what do you think about HTML5? Are you ready to HTML5-fy your site?
Update 2:04pm: as Chris noted in the comments, David released their CSS 2.1 Report here. However, for some obscure reason (that I still ignore) that report is still not appearing on the designated directory which is here.
This is a great news – as it is another step forward for CSS 2.1. On top of this, Opera released their report as well a few hours ago. If my counts are correct, here’s the pass rate so far:
I can’t find Chrome’s report – anyone have seen it?
Internet Explorer 9 Release Candidate is now available for download here.
There are many news, from new HTML5 features to enhanced performance, from state-of-the-art security to redesigned user experience. Here’s my TOP 5:
A page is now able to request the user location in a secure way using a few lines of code. The geo-location specification is now implemented by all major browsers! There’s no more reason for Google Maps to use browser detection code and block that feature to IE users…
if (navigator.geolocation != undefined)
navigator.geolocation.watchPosition(onPositionFound, onPositionError);
function onPositionFound(pos) {
Debug("Lat: " + pos.coords.latitude + ", Long: " + pos.coords.longitude);
IE9 has by far the cleanest UI of all browsers out there today. Huge step forward from IE8!
It’s fast. It’s smoking fast! You can measure it with synthetic benchmarks, you can run the demos on ietestdrive…but my advice is to run it with your favorite site. There’s no better benchmark than that!
I absolute love the ability to format the JavaScript code using the F12 Developer Tools (embedded in the browser, you don’t need to install addons).
As noted earlier, we have not been able to implement the remaining part of the <canvas> specification (globalCompositeOperation) in IE9 Beta due to still happening important conversation in W3C at that time. Since then we made a good progress and we are now happy to announce full support for the <canvas> spec in IE9 RC!
(Scratch-off demo by Beej Jorgensen)
Obviously there is much more…What are your TOP 5 features?
I don’t know what language you talk today, but if you are looking for a simple and free tool to convert videos to H.264 (.mp4) or VP8 (.webm), here’s a quick tip.
Find more info about the <video> tag on my previous post.
Based on an interesting script of David Flanagan to generate a snow flake using recursive JavaScript and HTML5 <canvas>, I had some fun during the weekend and added some snow to my blog.
David’s implementation is based on several canvas elements (one for each snow flake) added to the DOM tree and animated using CSS. I preferred to create only one Canvas and animate all the flakes inside it. To avoid the Canvas to block the interaction with the page I added it as an element with background priority.
(function () {
// Start Animation only if browser support <canvas>
if (document.createElement('canvas').getContext) {
if (document.readyState === 'complete')
Snow();
window.addEventListener('DOMContentLoaded', Snow, false);
var deg = Math.PI / 180; // For converting degrees to radians
var sqrt3_2 = Math.sqrt(3) / 2; // Height of an equilateral triangle
var flakes = []; // Things that are dropping
var scrollspeed = 64; // How often we animate things
var snowspeed = 500; // How often we add a new snowflake
var maxflakes = 20; // Max number of flakes to be added at the same time
var rand = function (n) { return Math.floor(n * Math.random()); }
var canvas, sky;
var snowingTimer;
var invalidateMeasure = false;
function Snow() {
canvas = document.createElement('canvas');
canvas.style.position = 'fixed';
canvas.style.top = '0px';
canvas.style.left = '0px';
canvas.style.zIndex = '0';
document.body.insertBefore(canvas, document.body.firstChild);
sky = canvas.getContext('2d');
ResetCanvas();
snowingTimer = setInterval(createSnowflake, snowspeed);
setInterval(moveSnowflakes, scrollspeed);
window.addEventListener('resize', ResetCanvas, false);
function ResetCanvas() {
invalidateMeasure = true;
canvas.width = document.body.offsetWidth;
canvas.height = window.innerHeight;
sky.strokeStyle = '#0066CC';
sky.fillStyle = 'white';
function drawFlake(x, y, size, order) {
sky.save();
sky.translate(x, y);
snowflake(order, 0, Math.floor(sqrt3_2 * y), size);
sky.fill();
sky.stroke();
sky.restore();
function snowflake(n, x, y, len) {
sky.save(); // Save current transformation
sky.beginPath();
sky.translate(x, y); // Translate to starting point
sky.moveTo(0, 0); // Begin a new subpath there
leg(n); // Draw the first leg of the fractal
sky.rotate(-120 * deg); // Rotate 120 degrees anticlockwise
leg(n); // Draw the second leg
sky.rotate(-120 * deg); // Rotate again.
leg(n); // Draw the final leg
sky.closePath(); // Close the subpath
sky.restore(); // Restore original transformation
// Draw a single leg of a level-n Koch snowflake.
// This function leaves the current point at the end of
// the leg it has drawn and translates the coordinate
// system so the current point is (0,0). This means you
// can easily call rotate() after drawing a leg.
function leg(n) {
sky.save(); // Save current transform
if (n == 0) { // Non-recursive case:
sky.lineTo(len, 0); // Just a horizontal line
else { // Recursive case: _ _
// draw 4 sub-legs like: \/
sky.scale(1 / 3, 1 / 3); // Sub-legs are 1/3rd size
leg(n - 1); // Draw the first sub-leg
sky.rotate(60 * deg); // Turn 60 degrees clockwise
leg(n - 1); // Draw the second sub-leg
sky.rotate(-120 * deg); // Rotate 120 degrees back
leg(n - 1); // Third sub-leg
sky.rotate(60 * deg); // Back to original heading
leg(n - 1); // Final sub-leg
sky.restore(); // Restore the transform
sky.translate(len, 0); // Translate to end of leg
function createSnowflake() {
var order = 2;
var size = 10 + rand(90);
var t = (document.body.offsetWidth - 964) / 2;
var x = (rand(2) == 0) ? rand(t) : t + 964 + rand(t); // Make it fit with my blog
var y = window.pageYOffset;
flakes.push({ x: x, y: y, vx: 0, vy: 3 + rand(3), size: size, order: order });
if (flakes.length > maxflakes) clearInterval(snowingTimer);
function moveSnowflakes() {
sky.clearRect(0, 0, canvas.width, canvas.height);
var maxy = canvas.height;
for (var i = 0; i < flakes.length; i++) {
var flake = flakes[i];
flake.y += flake.vy;
flake.x += flake.vx;
if (flake.y > maxy) flake.y = 0;
if (invalidateMeasure) {
var t = (canvas.width - 964) / 2;
flake.x = (rand(2) == 0) ? rand(t) : t + 964 + rand(t);
drawFlake(flake.x, flake.y, flake.size, flake.order);
// Sometimes change the sideways velocity
if (rand(4) == 1) flake.vx += (rand(11) - 5) / 10;
if (flake.vx > 2) flake.vx = 2;
if (flake.vx < -2) flake.vx = -2;
if (invalidateMeasure) invalidateMeasure = false;
} ());
I did a quick test check with performance, and it looks like IE9 perform better with CPU/Memory usage (IE9 Beta Refresh, Firefox 4 Beta7, Chrome 10 Canary, Opera 11Beta and Safari 5).
You can find the original script from David here, the script with my updates here.
Happy Holidays!
To summarize with one picture the great recap of the Compatibility View written by Scott on the IE blog…
…you can make your site compatible with IE8 just adding the META tag:
Internet Explorer Compatibility Center: msdn.com/iecompat
Quick tip: if you are using jQuery UI with IE9, you might hit an issue today. There is in fact a code bug (of the series “do feature, not browser detection”) in the jQuery.UI.Mouse module, which is used by the Slider control or by other drag&drop features.
The jQuery team already identified the issue and a workaround – they are currently working to fix this in the main branch.
You can track it here.
As announced on the Windows blog this morning, today Pirates Love Daises - a new HTML5 tower defense game - has been released!
Grant Skinner, the leader of the team that built the game, reported his experience on his blog. He shared some interesting thought about the shift of paradigm for an experienced Flash developer approaching HTML5. He also described some of the unexpected (but pleasant) surprises and challenges he faced during the development phase.
In this post, I’d like to complement his comments with further lessons we’ve learned along the path.
Let’s start talking about Performance. We heard many times that IE9 is fast…but I think this is the first time IE9 has been defined “smoking fast”! Grant, you are a primer!
I like to think about this game as a real world performance benchmark. No secret functions, no ray-tracing algorithms, no synthetic tests. Just a well designed HTML5 game.
The best way to test the performance, it’s to try it on your machine with your browser. For those of you that don’t have 7+ browsers installed on your machine , I recorded a video where I play the game on all the latest browsers builds available today.
Based on my personal experience, I reported the results in the table below. The CPU and Memory (Private Working Set) values have been captured using the Windows Task Manager, after about 5 seconds playing in the easiest map. A better measurement should take count of an average over time, since the complexity of the app increase quickly during the game.
Firefox 3.6
According to Grant’s tests, the game runs on Mac and iOS as well, although with poor performance. I don’t have any of these machines, can any reader record and share a video of the game playing on a Mac or an iPad (or any other device with HTML5 support)?
As we stated many times, HTML5 is doing great progress and this game is yet another confirmation of its capabilities. Let’s see a few key learning we made along the path.
I hope Grant will share more insights into his development experience with the Canvas. It’s exciting what he achieved in terms of complexity – it almost doesn’t feel any more like HTML!
A common technique that he used for the game is called “sprite animation”: you build a large image (composed of many sub images) and then you draw only one part of it at a given time. If you need to do an animation, you can re-draw very quickly on the same location – and all the human eye will see is an animation!
For example, here’s the Kraken sprite:
If you are interested to build your own animation, have a look at the library used in the game and gently made available by Grant: http://easeljs.com/
One of the interesting questions we got was: what is the max size of an image that the <canvas> can handle? 1000, 2000, 4000 pixels width? More? In this case I think the answer is “it depends”. It depends probably on the browser architecture (not necessarily the browser itself!) as there is a tight dependency on the video card and the OS. Having a browser that supports hardware acceleration helps, but there are still technical boundaries that can’t be overcome. Based on empirical experiments, we found that ~4000pixels seems to be the current limit. I’d be interested to hear from other people what they experienced on their machines.
There are hundreds thousands of fonts available today. For this project, Grant’s team got one that fits perfectly within the game. During the development of the project, they started with the ttf (True Type Font) format. They realized however that it was better to use an open font format…and what better one than WOFF, the new standard submitted by Mozilla and Microsoft to W3C!
We used Font Squirrel to generate the @font-face Kit (also check out TypeKit) and we initially generated the compact CSS rule:
@font-face {
font-family: freeBooterFont;
src: url('../fonts/freebooterupdated.woff') format('woff');
font-weight: normal;
font-style: normal;
It was working fine on all browsers, except Safari (both on Windows and Mac). Looking at online resources, we realized that – although committed to – they don’t support WOFF yet in the current build. Interesting, since it’s already on Chrome WebKit (shouldn’t the code be the same/shared?). I’m sure it will be added soon…and in the meantime we adjusted the CSS syntax (luckily super easy to do!) to include a fallback format.
src: url('../fonts/freebooterupdated.woff') format('woff'), url("../fonts/FreebooterUpdated.ttf") format("truetype");
Having one <audio> element on a page playing without plugins is already awesome.
Having 40 of them playing together is an orchestra! There are topics however that the spec doesn’t cover (and I think shouldn’t cover) where IMHO a little more documentation should be given by browser vendors to developers (IE Team already took note). For example, what’s the best practice to pre-load multiple audio samples? How many audio files can the browser play at the same time? I’m planning to spend some time on this topic in a future post.
I didn’t build the game, but I was reviewing the interim builds using the Developer Tools in IE9. They come with the browser, no need to install anything special, you just press F12 and they fire up.
The feature that I love more than anything else and that was very helpful in this project is “Format JavaScript”. If you go to the site now, you’ll notice that the code has been compressed and crunched to optimize performance.
If you are like me and you want to understand what’s behind it…you can go to the Script tab and press the “Format JavaScript” button. The result? A nicely “reverse-engineered” formatted source code! (Sorry Grant, I hope you won’t be upset )
There is much more to cover and to explore, but I’ll let you play the game now.
Resources:
Enjoy!
How do I develop using Canvas, SVG, CSS3? What’s new in JavaScript? In this deep dive you will learn how to use HTML5 and how new web standards help solve existing challenges on the web. Expect a lot of code, demos, and best practices!
How do you start an HTML5 page? Actually HTML5 is evolutionary, not revolutionary. Any page built yesterday with HTML 4.1 will be an HTML5 page automatically tomorrow. However, the HTML5 specification provides a few optional changes that can simplify your markup. For example, the following code is what I use as a template for my new pages.
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8">
</head>
</html>
HTML5 also provides a set of new tags (for example, <article>, <nav>, and <figcaption>) that adds more semantic meaning to the content, and helps accessibility tools (such as screen readers) and search engines to better understand the page.
The <video> tag is probably one of the most interesting (and most discussed) new tags in the HTML5 markup language. It allows you to embed a video on the page without using a plug-in. The samples I provide explain how to use its properties (for example, poster to define the initial frame, or controls to show the control buttons, or preload to set the pre-fetching rules). As we’ve seen, the current specification doesn’t allow the player to go full-screen. If you need this scenario, you can change the size of the control dynamically and bring it on top of the page using the zIndex. Through its events loadedmetadata, canplay, and timeupdate you can monitor when the video is ready to play and track its progress. Lastly, the canPlayType property allows you to test whether the UA supports a specific codec or container; remember, the return values are either “”, “maybe”, or “probably”.
Drawing on a page has never been so easy. You have a brush that you can move across the screen to draw images – that’s all you need in order to create amazing drawings or animations! If you are drawing an image, remember to wait for it to be loaded. When you develop an animation, you will need to decide the best strategy to serve your purpose. Use time-based animation if you need a precise, smooth, and predictable result. Use frame-based animation if you need to develop quickly and are comfortable with losing some cycles (timer resolution is not perfect!).
With a little bit of creativity, you can achieve quite interesting scenarios – for instance, drawing a video on a canvas and dynamically appending its mirrored shadow.
ctx.translate(0, 200);
ctx.scale(1, -1); // Flip video
// Prepare gradient
var gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
gradient.addColorStop(0, "rgba(255,255,255,255)");
gradient.addColorStop(1, "rgba(255,255,255,0)");
ctx.fillStyle = gradient;
myVideo.addEventListener('canplay', function () {
setInterval(function () {
ctx.drawImage(myVideo, 0, 0, 300, 200); // Draw video frame
ctx.fillRect(0, 0, 640, 360); // Draw fading
}, 60);
}, false);
If you are looking for a tool to design on canvas or to design prototype animations, check out the AI2Canvas Exporter plug-in built by our own Mike Swanson. You can achieve great results with it – for instance, take a look at what Joshua Davis did!
In this group of demos, you will also find a little game I built on the plane while I was flying to Berlin. I’ll get back to this in a future post.
SVG (Scalable Vector Graphics) adds even more capabilities to what you can achieve with the Canvas. This time you are dealing with objects, which have their own properties, events, and programmability. You can embed your SVG snippets inline in an HTML page (did you know Internet Explorer 9 is the first browser to support this?), or embed in an XHTML document, as well as standalone files or files that are referenced inside an <img> tag.
SVG is intrinsically designed to work with the rest of the standards. You can program it using JavaScript and the APIs that you already know; and you can style it using CSS!
<svg xmlns="http://www.w3.org/2000/svg" width="600" height="300">
<rect width="200" height="300" fill="#009246" />
<rect width="200" height="300" x="200" fill="#fff" />
<rect width="200" height="300" x="400" fill="#ce2b37" />
</svg>
The last demo (Gradients) is a prototype of SVG+CSS+HTML5+JavaScript in action. Using a few tricks, you can use SVG to build a color gradient dynamically and use CSS properties to apply it to any HTML element on the page. I had some interesting conversations with Jonathan and Robert about this approach – I think it might be interesting to explore it further. eCSStender from Aaron Gustafson seems to be the natural evolution of the prototype; please ping me if you are interested in further exploring this approach with me!
What about news for web designers? CSS3 brings a lot of new and interesting modules to the table. Of all of them, text/border shadows, colors (rgba, opacity), multiple backgrounds, border radius, media queries, and WOFF are the ones I believe to be the most stable today.
<style type="text/css" media="screen">
@font-face
font-family: '3DumbRegular';
src: local('☺'), url('WOFF/3Dumb-webfont.woff') format('woff');
.fontface
font: 60px/68px '3DumbRegular' , Arial, sans-serif;
letter-spacing: 0;
</style>
Run the demo, “1. Media Queries” to understand how CSS allows you to pick specific rules depending on the screen resolution. Plus, you can have some fun with my hand (seriously – that’s my hand, copyright at Giorgio Sardo ).
Last but not least, JavaScript has some very neat new features for developers! For example, it includes a native JSON object that allows you to accomplish serialization/deserialization operations very quickly, that in the past you probably did with external libraries.
var result;
var myArray = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
//NEW! forEach
var multiply = function (value, index, array) { array[index] = value * this };
/* No Return! */ myArray.forEach(multiply, 3);
//result= 3, 6, 9, 12, 15, 18, 21, 24, 27, 30
There are a lot of new Array methods that simplify common tasks such as looping through the Array and performing a particular operation. I personally love the ability to do “kind of lambda expression” using forEach().
The object model has also evolved. With the new syntax, Object.create can more easily define new and cleaner prototypes.
Lastly, you finally have access to some helper functions, such as Date.Parse() and String.Trim().
This is not an extensive coverage of all the new features of HTML5 and related web standards. There is much more in the pipeline (Robert talked more about this)! What I covered in this session is probably the most mature content in the specification. It is (or soon will be) available across all the major browsers. It’s interoperable and it doesn’t apply only to Internet Explorer 9…but to any browser. In other words, it’s ready!
You can download all the source code here. Please feel free to contact me if you have any feedback or questions – I’m sure somebody out there knows how to improve this!
Did you know that you can now turn Facebook into a Windows application?
Using Internet Explorer 9, you can drag&drop any url to the Taskbar…and the site will become automatically a Windows application! The chrome of IE will adapt to the Facebook logo, you will be able to quickly jump to specific part of the sites and also receive notifications (through icon updates) when there are new messages on the site. Cool!
Site Mode:
Jump List:
Icon Overlay:
I think my productivity at work is going to improve now!
As I said in the previous post, .NET 3.5 Service Pack 1 addresses issues that were found through a combination of customer and partner feedback, as well as internal testing. Overall, .NET 3.5 Service Pack 1 offers customers many new features and improvements in responsiveness, stability and performance for Visual Studio 2008 and .NET Framework 3.5.
Now…obviously I trust the WPF team , but I was curious to test the “real difference” given from the .NET Framework SP1 (Beta); for the sake of a perf exercise, I’ve written a tutorial to compare the previous BitmapEffect with the new Effect, which is one of the new classes with HW-acceleration support introduced by the SP1.
You can download the source code for this tutorial here. Please remember that, in order to compile the project, you need to install the .NET 3.5 Service Pack 1.
1) Button with Blur Effect
The first sample I’ve created is a Button with a Blur effect.
The Radius property of the Blur effect is bound to a slider, which allows me to change easily its value at runtime.
1: <Button Content="Ciao" x:Name="button" Width="400" Height="150" Grid.Column="1" Grid.Row="1">
2:
3: <!-- FAST, HW ACCELERATED -->
4: <Button.Effect>
5: <BlurEffect Radius="{Binding Path=Value, ElementName=slider}" />
6: </Button.Effect>
7:
8: <!-- SLOW, SW ACCELERATED (deprecated) -->
9: <!--<Button.BitmapEffect>
10: <BlurBitmapEffect Radius="{Binding ElementName=slider, Path=Value}" />
11: </Button.BitmapEffect>-->
12:
13: </Button>
After running and profiling this sample (how-to later in this post), these are my empirical results:
As expected, the Effect is 5 times faster then a Bitmap Effect.
2) StackPanel with Animating Blur Effect
Running the Perforator tool with a slightly more complex sample, the results are stunning: you can see a huge step in the memory usage, from 150MB (sw acceleration) to 16MB (hw acceleration)…an outstanding 1000%!!!
3) HOW-TO PROFILE AND MEASURE PERFORMANCE
I would like to share quickly how I’ve done the previous tests.
These are Snapshots from my tests:
CVD…
These are just easy snippets of code, that don’t really require a lot of memory. However, although simple, they already clearly show some of the performance improvements provided from the .NET Framework SP1 (BETA).
I can’t wait to install the SP1 RTM!!
If you want to try this with your machine, you can download the source code for this tutorial here. Please remember that, in order to compile the project, you need to install the .NET 3.5 Service Pack 1.