ControlFreak
LANGUAGES:VB.NET | C#
ASP.NETVERSIONS: 2.x
QuickTimePlayer
Tour the Source Code of the Free ASP.NET QuickTimePlayerControl
By Steve C. Orr
Playing QuickTime movies from an ASP.NET Web form can be alittle tricky. At first it may not seem difficult, but there are a lot oflittle details to worry about ? such as browser differences, ActiveXactivation, and the list of acceptable parameters. The QuickTimePlayer controldetailed here (and shown in Figure 1) takes care of all those issues, reducingthe task to drag-and-drop simplicity.
Figure 1: The QuickTimePlayercontrol eliminates the chores involved with playing QuickTime movies.
During the exploration of this control you?re also likelyto learn a lot about custom Web control design, ActiveX activation, and ASP.NET2.0 Web resources. All major browsers are supported by the QuickTimePlayercontrol, including Internet Explorer, Firefox, Safari, America Online, Opera,and Netscape.
How to Use It
The QuickTimePlayer.dll can be added to your Visual Studiotoolbox via right-click just like any other control (see end of article fordownload details). When that task is done, it can be dragged from the toolboxonto any ASP.NET Web form, where a definition similar to this will be renderedto the ASPX:
<cc2:QTPlayer
ID="QTPlayer1"
runat="server"
MOVFile="Sample.mov"
Width="250"Height="270"
AutoPlay="true"
ShowMenu="false">
</cc2:QTPlayer>
Of course, you can type such a declaration manually, ifpreferred. The MOVFile property is the only one you?ll definitely need toadjust, because it defines which QuickTime movie (*.mov) will be played. Thereare a variety of other useful properties, as well, including properties forcaching the movie and looping the movie endlessly. The full list of uniqueQuickTimePlayer properties is shown in Figure 2.
| QuickTimePlayer Property | Default Value | Description |
| AutoPlay | True | Specifies whether or not the movie file should automatically start playing as soon as the page is loaded. |
| Cache | False | A Boolean property that determines whether to cache the video file or not. |
| Hidden | False | If this Boolean property is set to True, video will not be shown; audio only. |
| Loop | False | When this Boolean property is set to True it will cause the movie to loop continuously. |
| MOVFile | | Set this string property to the filename of the QuickTime file that should be played. |
| ShowMenu | True | If this Boolean property is set to False then the dropdown/context menu for the control will not be available, disabling the feature to save the file locally. |
Figure 2:TheQuickTimePlayer control has many properties that allow adjustment of the lookand behavior of the player.
The ShowMenu property can be used to disable thedropdown/context menu that is normally available in QuickTimePlayer. That menu?sprimary feature is to allow the user to save the movie file to a local drive. Setthe ShowMenu property to False to deny users of that feature. (However,knowledgeable users can still likely use more complex techniques to snag yourcontent.)
The Hidden property can be set to True if you only want toplay audio. No video or user interface will be visible when this property isset to its non-default value of True.
The AutoPlay property ensures that a movie starts playingat its first available opportunity. If set to False the movie will load but notplay upon page load, as it normally would. The movie can then be started viaJavaScript or as a result of the user clicking the play button. The BooleanAutoPlay property?s default value is True.
With the knowledge you now have about using theQuickTimePlayer control, you could stop reading here and start developing withit. But if the developer in you wants to find out the details about theQuickTimePlayer?s inner workings, keep reading ...
How It Works
To play a QuickTime movie on your own (without the aid ofthe QuickTimePlayer control), you?d include some HTML similar to that shown in Figure3.
<embed src="QuickTimeSample.mov"
width="160"height="144"
autoplay="true"
pluginspage="http://www.apple.com/quicktime/download/">
</embed>
Figure 3:QuickTime movies can be played in most browsers (except Internet Explorer) witha bit of HTML such as this.
This would work great in virtually all browsers exceptInternet Explorer, which requires a completely different syntax. To play amovie in Internet Explorer, the syntax shown in Figure 4 must be used. However,if this HTML is placed directly in the page, then ActiveX activation will berequired, annoying users and forcing them to click on the control before theycan interact with it.
<objectclassid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"
width="160"height="144"
codebase="http://www.apple.com/qtactivex/qtplugin.cab">
<paramname="SRC" value="sample.mov">
<param name="AUTOPLAY"value="true">
</object>
Figure 4: InternetExplorer requires this syntax to play QuickTime movies, but ActiveX activationwill be required if this HTML is embedded directly in the page.
One common technique is to always output both syntaxes. Allbrowsers will pick the syntax they like and ignore the other one, so it workswithout issue. When given a choice, however, I prefer tidy HTML output. I don?twant to waste bandwidth by outputting HTML that is not used. Therefore, theQuickTimePlayer control only outputs the most appropriate syntax.
Essentially the QuickTimePlayer control detects whichbrowser the user has and outputs the syntax in Figure 4 for Internet Explorer,or the syntax shown in Figure 3 for other browsers. The control?s private RenderForAltsubroutine (listed in Figure 5) takes charge of rendering the HTML for non-InternetExplorer browsers. The resulting output is similar to that shown in Figure 3.
''' <summary>
''' Renders QuickTime embed tag for non-IE browsers
''' </summary>
Private Sub RenderForAlt(ByVal output As HtmlTextWriter)
Dim pp As String
pp ="http://www.apple.com/quicktime/download/"
Dim sb As StringBuilder= New StringBuilder
sb.Append("<embed")
sb.Append("pluginspage='")
sb.Append(pp)
sb.Append("' enablejavascript = 'true'")
sb.Append("src='")
sb.Append(Page.ResolveClientUrl(Me.MOVFile))
sb.Append("'width='")
sb.Append(Me.Width.ToString)
sb.Append("'height='")
sb.Append(Me.Height.ToString)
If Not Me.BackColor.IsEmptyThen
sb.Append("'bgcolor='")
sb.Append(Color2Hex(Me.BackColor))
End If
sb.Append("'autoplay='")
sb.Append(Me.AutoPlay.ToString.ToLower)
sb.Append("'loop='")
sb.Append(Me.Loop.ToString.ToLower)
sb.Append("'cache='")
sb.Append(Me.Cache.ToString.ToLower)
sb.Append("'kioskmode='")
sb.Append((NotMe.ShowMenu).ToString.ToLower)
sb.Append("'")
If Me.Hidden Thensb.Append(" hidden ")
sb.Append(" />")
output.Write(sb.ToString)
End Sub
Figure 5: ThisVB.NET function interprets the QuickTimePlayer control?s property settings anduses them to render HTML similar to that shown in Figure 3.
We could use a nearly identical function for outputtingFigure 4 HTML syntax for Internet Explorer, but, as mentioned previously, thatwould impose ActiveX activation upon the user.
Avoiding ActiveX Activation
To avoid ActiveX activation, object tags (such as shown inFigure 4) must be output dynamically on the client side by an externalJavaScript file. The JavaScript file (named qt.js) used by the QuickTimePlayercontrol is listed in Figure 6.
// JavaScript File (qt.js)
function CreateIEMOV(ID, Movie, Width, Height, Clr, Play,
Loop,Cache, Hide, Menu)
{
var doc = document;
var clsid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B";
varcodebase="http://www.apple.com/qtactivex/qtplugin.cab";
doc.write('<object classid="' + clsid + '" ');
doc.write('codebase="'+ codebase + '" ');
doc.write('width="'+ Width + '" ');
doc.write('height="' + Height + '" ');
doc.write('id="' + ID + '">');
doc.write('<param name="src" value="'+ Movie +'"');
doc.write('<param name="autoplay" value="'+Play+'">');
doc.write('<param name="loop" value="'+ Loop+'">');
doc.write('<param name="cache" value="'+ Cache+'">');
doc.write('<param name="kioskmode" value="'+Menu +'">');
doc.write('<param name="enablejavascript"value="true');
doc.write('<param name="bgcolor" value="'+ Clr+ '">');
if (Hide) doc.write('<param name="hidden">');
doc.write('</object>');
}
Figure 6: Thisclient-side JavaScript function is invoked to dynamically output HTML objectsyntax similar to that shown in Figure 4, thus avoiding ActiveX activation.
Because this script remains static, the only dynamicserver-side output the QuickTimePlayer control needs to render for InternetExplorer browsers is a single line of JavaScript that calls the function inFigure 6:
CreateIEMOV('QTPlayer1', 'Sample.mov', 250, 270, '0000cd',
true, false, false,false, false);
The private RenderForIE subroutine (listed in Figure 7)dynamically generates the above JavaScript function call.
''' <summary>
''' Renders QuickTime init script for Internet Explorer
''' </summary>
Private Sub RenderForIE(ByVal output As HtmlTextWriter)
Dim sb As StringBuilder= New StringBuilder
sb.Append("CreateIEMOV('")
sb.Append(Me.ClientID)
sb.Append("','")
sb.Append(Page.ResolveClientUrl(Me.MOVFile))
sb.Append("',")
sb.Append(Me.Width.ToString)
sb.Append(",")
sb.Append(Me.Height.ToString)
sb.Append(",'")
If NotMe.BackColor.IsEmpty Then
sb.Append(Color2Hex(Me.BackColor))
End If
sb.Append("',")
sb.Append(Me.AutoPlay.ToString.ToLower)
sb.Append(",")
sb.Append(Me.Loop.ToString.ToLower)
sb.Append(",")
sb.Append(Me.Cache.ToString.ToLower)
sb.Append(",")
sb.Append(Me.Hidden.ToString.ToLower)
sb.Append(",")
sb.Append((NotMe.ShowMenu).ToString.ToLower)
sb.Append(");")
output.Write("<scriptlanguage='JavaScript'>")
output.Write(sb.ToString)
output.Write("</script>")
End Sub
Figure 7: ThisVB.NET function generates a line of JavaScript that calls the function inFigure 6, which in turn instantiates QuickTimePlayer for Internet Explorer.
ASP.NET 2.0 Embedded Web Resources
You?re likely aware that external JavaScript files must bereferenced with HTML similar to this:
<script language="javascript" src="qt.js"></script>
If the qt.js file is not referenced, Internet Explorerrendering won?t work because the client-side CreateIEMov function won?t beavailable. These items can be embedded within the control itself to avoidhaving to remember to include the JavaScript file and the above reference to itin every page and project that uses the QuickTimePlayer control.
The qt.js file shown in Figure 6 is included in theQuickTimePlayer control?s Visual Studio Web control library project. This file?sBuild Action property is set to Embedded Resource, which causes it to becompiled directly into the control?s assembly. The next step required for configuringthis file as an ASP.NET 2.0 embedded resource is to add the followingdeclaration near the top of the class file:
<Assembly:System.Web.UI.WebResource("ControlFreak.qt.js", _
"text/javascript")>
The file (qt.js) must be prefixed with the correctnamespace (ControlFreak); this is all case sensitive. When an embedded resourceisn?t rendering as you expect, this string is the most likely culprit. It mustbe formed quite specifically or it won?t work.
Finally, the reference to the file must be rendered forInternet Explorer users, as is done by the VB.NET code shown in Figure 8. Onceagain, be very careful with the file and namespace reference (assigned to thersname variable); it must be precise.
Protected Overrides Sub OnPreRender(ByVal _
e As System.EventArgs)
MyBase.OnPreRender(e)
If Me.DesignMode ThenExit Sub
WithContext.Request.Browser
If.Browser.ToString.ToUpper = "IE" Then
' Define theresource name and type.
Dim rstype AsType = Me.GetType
Dim rsname As String ="ControlFreak.qt.js"
' Register theclient resource with the page.
Dim cs AsClientScriptManager = Page.ClientScript
cs.RegisterClientScriptResource(rstype, rsname)
End If
End With
End Sub
Figure 8: TheOnPreRender event is a good place to include references to embedded resources.
ASP.NET 2.0 embedded Web resources are vital for creatingprofessional, user-friendly server controls. I suggest you get to know and lovethem.
Finishing Touches
The Render method listed in Figure 9 is used to ensure theMOVFile property is set and to determine which browser output should berendered. Either the RenderForIE subroutine or the RenderForAlt subroutine iscalled, depending on the user?s browser.
Protected Overrides Sub Render(ByVal _
output AsHtmlTextWriter)
If Me.DesignMode ThenExit Sub
If Me.MOVFile.Trim ="" OrElse _
Me.Width = 0 OrElse _
Me.Height = 0 Then
Dim msg ="MOVFile property is missing"
Throw New ArgumentNullException(msg)
End If
WithContext.Request.Browser
If.Browser.ToString.ToUpper = "IE" Then
RenderForIE(output)
Else
RenderForAlt(output)
End If
End With
End Sub
Figure 9: TheRender method is overridden to ensure the MOVFile property is set and todetermine which browser output should be rendered.
The properties of the QuickTimePlayer control are fairlystandard, with most of them looking a lot like those shown in Figure 10.
<Bindable(True), Category("Behavior"),DefaultValue(True), _
Description("play thevideo immediately ")> _
Public Property AutoPlay() As Boolean
Get
IfViewState("Play") IsNot Nothing AndAlso _
Convert.ToBoolean(ViewState("Play")) = False Then
Return False
Else
Return True
End If
End Get
Set(ByVal value AsBoolean)
ViewState("Play") = value
End Set
End Property
Figure 10: Theproperties of the QuickTimePlayer control are fairly standard.
As you can see, standard attributes are applied tocategorize the property, permit data binding, set the default value, andprovide a description to be shown in the Visual Studio Property window atdesign time. ViewState is used to store the property value between postbacks.
The MOVFile property definition is a little moreinteresting, adding a couple more attributes (see Figure 11).
<Bindable(True), Category("Data"),DefaultValue(""), _
Description("URL to aQuickTime (*.mov) file"), _
Editor(GetType(System.Web.UI.Design.UrlEditor),_
GetType(System.Drawing.Design.UITypeEditor))>_
Public Property MOVFile() As String
Get
Dim s As String =CStr(ViewState("MOVFile"))
If s Is NothingThen
ReturnString.Empty
Else
Return s
End If
End Get
Set(ByVal value AsString)
ViewState("MOVFile") = value
End Set
End Property
Figure 11: Addedattributes make the MOVFile property definition more interesting.
The Editor attribute is used to ensure the UrlEditordialog box should appear when the developer clicks the ellipsis button next tothe property in the Visual Studio Property window at design time.
This sums up the major features and functions of theQuickTimePlayer control.
Conclusion
The QuickTimePlayer control encapsulates the complexitiesinvolved with playing QuickTime movies. It automatically handles browserdifferences, detecting and outputting the best and most efficient HTML syntax. Italso eliminates ActiveX activation by refactoring the rendering of the objecttag into an external JavaScript file. This JavaScript file is incorporated asan ASP.NET 2.0 embedded Web resource to add a professional polish and eliminatethe possibility that required resources or references could be forgotten.
Download the control now to simplify QuickTime movieplaying in your ASP.NET Web applications. If you don?t like it, do somethingabout it! You?ve got the source code. I?d love to hear about any creativeenhancements you make to the QuickTimePlayer control.
The source code forthis article is available for download.
Steve C. Orr is anASPInsider, MCSD, Certified ScrumMaster, Microsoft MVP in ASP.NET, and authorof the book Beginning ASP.NET 2.0 AJAX by Wrox. He?sbeen developing software solutions for leading companies in the Seattlearea for more than a decade. When he?s not busy designing software systems orwriting about them, he can often be found loitering at local user groups andhabitually lurking in the ASP.NET newsgroup. Find out more about him at http://SteveOrr.net or e-mail him at mailto:Steve@Orr.net.