October 2011 - Posts
Build Modern Web Applications with HTML5, CSS3 and JavaScript Session Slide Deck and Demos
Today I delivered a MSDN session at Microsoft HQ about “Build Modern Web Applications with HTML5, CSS3 and JavaScript” and in particular HTML5. I want to thank all the attendees which came to hear about the transition that the web eco-system is going through. The session agenda was as follows:
- What is HTML5?
- The New Elements
- Migration to HTML5
- HTML5 APIs (Canvas, Web Storage, Geolocation and Web Workers)
The slide deck and demos can be downloaded from here.
Enjoy!
Adding Video Element on the Fly and Drawing it to a Canvas Element
One of the requirements in a project that I work on lately is to create on the fly video elements and to show them inside a canvas element. This post will show you how you can do it.
Adding Video Element on the Fly
The HTML5 Video element is a DOM element. As any other DOM element you can create it using the document.createElement function and then to supply its relevant properties. After the creation of the element you will have to append it into the DOM tree. One place that you might append the element to is at the end of the body element (but you might append it to other elements as well). The following code snippet shows how to create a video element on the fly and append it to the body element:
var video = document.createElement('video');
video.src = 'your source goes here';
video.controls = true;
document.body.appendChild(video);
Drawing The Video to a Canvas Element
After you have created the video element and append it to the DOM tree the video won’t start up until somebody will play it (or you use the autoplay attribute). If you need to display that video on a canvas you will have to wire up an event handler to the video’s onplay function and to draw the video on the canvas in the handler. Pay attention that you will have to draw the video’s frames or the canvas will only show the first frame that you draw. This is way you will need to call the draw in an interval. Here is a simple example of how to do exactly that:
var canvas = document.getElementById('canvas')
var ctx = canvas.getContext('2d');
video.onplay = function() {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
draw();
};
function draw() {
if(video.paused || video.ended) return false;
ctx.drawImage(video, 0, 0);
setTimeout(draw, 20);
}
The Full Example
Here is the full example:
<!DOCTYPE html>
<html>
<head>
<title>On the Fly Video inside a Canvas</title>
</head>
<body>
<canvas id='canvas'></canvas>
<script type="text/javascript">
var video = document.createElement('video');
video.src = 'trailer.mp4';
video.controls = true;
document.body.appendChild(video);
var canvas = document.getElementById('canvas')
var ctx = canvas.getContext('2d');
video.onplay = function() {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
draw();
};
function draw() {
if(video.paused || video.ended) return false;
ctx.drawImage(video, 0, 0);
setTimeout(draw, 20);
}
</script>
</body>
</html>
Summary
When you need to create on the fly videos in your web pages you can just create them as a any other DOM element. If you need to show these elements inside a canvas then you will have to draw the video inside the canvas element while it is playing.
HTML5 and Government Organizations Session Slide Deck
Yesterday I had the pleasure of delivering a session in the HTML5Fest conference. The session subject was about HTML5 and government organizations. I want to thank all the attendees who came to hear me. The topics that I talked about included:
- What is HTML5?
- Government Organizations Main Challenges
- HTML5 and Government Organizations
If you are interested in the session slide deck you can download it from here.
Quick Tip – Converting JSON Serialized .NET DateTime to JavaScript Date
When you are using the controller JSON method in ASP.NET MVC or scriptable WCF services you sometimes have to serialize a .NET DateTime property. The DataContractJsonSerializer will serialize it into the following format:
This format indicate to the client side parsers that the data fragment that was sent is a date representation.
But how can you convert it to a JavaScript Date object?
There are a few methods:
- “Brutal Force”: Extract the number using regular expression or substring functions and pass it to the Date object which get the time in milliseconds in its constructor:
var date = new Date(1235398665390);
- Server Side Approach: Send to the client side not a .NET DateTime but the total milliseconds and then use the same constructor from the previous bullet. You should pay attention that JavaScript’s base date is 1/1/1970. The following code can help:
var baseDate = new DateTime(1970, 1, 1);
var currentDate = DateTime.Now.ToUniversalTime();
TimeSpan ts = new TimeSpan(dcurrentDate.Ticks - baseDate.Ticks);
return ts.TotalMilliseconds;
- The Eval Way: on the client side use the eval function to evaluate and create the Date object:
var date = eval("new " + dateFromTheServer.slice(1, -1));
Where the dateFromTheServer is in the format which was presented at the top of the post.
There are probably other ways which can help you. What is your way?
Avoiding Circular Reference for Entity in JSON Serialization
One problem that I was facing yesterday while working on an ASP.NET MVC application was a JSON serialization issue. The problem was a circular reference caused by the DataContractJsonSerializer because of relations between the entity and other entities. In this post I’ll show you how you can use a simple workaround in order to avoid the problem.
The JSON Serialization Error
Returning the output of the JSON method in an ASP.NET MVC controller with a JSON object graph based on an Entity Framework Code First object causes the following error – “A circular reference was detected while serializing an object of type ‘object name’”. Here is an example of a method that might cause the problem:
public ActionResult Details(int id)
using (var context = new DbEntities())
{
var entity = context.Entities.
Include(e => e.OtherEntities).
FirstOrDefault(e => e.EntityId == id);
return Json(entity, JsonRequestBehavior.AllowGet);
}
}
Pay attention that this is a fake method and isn’t a real method.
The error I was getting didn’t show up on the server side (nothing crashed). I found the error by inspecting Fiddler since the application kept on working but the client side callback wasn’t. Here is an example of the calling client side function which is using jQuery getJSON function:
function getDetails() {
$.getJSON('/ApplicationName/Details/' + Id, {}, function (data) {
fillDetails(data);
});
}
The circular reference is a known problem that my colleague Ido wrote about in Microsoft Connect.
So how to avoid it?
The Workaround
Use a data projection to project only the relevant data that you need and send this data to the client side. This workaround will minimize the object that you are sending and also play a role as a ViewModel kind of object instead of an entity when it is available on the client side. Here is an example of using the workaround with the previous method:
public ActionResult Details(int id)
{
using (var context = new DbEntities())
{
var entity = context.Entities.
Include(g => g.OtherEntities).
Select(e => new {
e.Id,
e.Url,
e.Name,
e.OtherEntities
}).
FirstOrDefault(e => e.Id == id);
return Json(entity, JsonRequestBehavior.AllowGet);
}
}
Summary
The circular reference issue might happen also in WCF script services or in other places while serializing Entity Framework’s entities into JSON representation. The simple workaround is to create a projection of the data that you need and serialize it into JSON representation. One of the gains of this method is minimizing the response size from the server.
Update Your Windows Phone 7 to Mango Release Today
Two days ago I updated my Windows Phone 7 (HTC HD7 device) to the Windows Phone 7.5 (Mango) even though the update didn’t arrive to my device from my device carrier. If you ask yourself how I did it, the answer is simple. I used a hack. You can read about this hack in this PC magazine article – How to Force Your Phone to Upgrade to Windows Phone Mango.
Pay attention that it might take a few tries up until this hack will succeed to operate (it took me 5 tries and to other people that I know it even took up to 10 tries). So don’t get frustrated if it doesn’t go on the first attempt (or even in the second or third etc.).
Thanks to Alex for the tip about the hack.
Third Year in a Row
Yesterday I received the mail from Microsoft that congratulate me for being a Microsoft MVP for the third time. It’s is a honor for me to get the award three years in a row. This time the receiving of the mail was somewhat weird since I saw on Twitter that people got the mail and I didn’t get it…
Apparently, my Gmail mail account (which is my personal mail account) “thought” that the congratulation mail is spam and moved it into the spam directory. This of course shows the true relationship between Google and Microsoft
.
I would like to say thanks to all of you, my blog readers and the Microsoft community, for helping me keep the MVP Award for a third year! Also, I would like to thank the following people - Guy Burshtein, Maor David, and all my colleagues in Sela Group which IMHO everyone of them deserve to get the award! (and Congrats to Ido and Arik for their new MVP Award. You deserved it!)