Add Multimedia Content with a Custom Control in VB.NET

Introduction:

This article describes a quick and simple approach to creating a custom web control used to display multimedia files within an ASP.NET page. Whilst the article and demonstration project are focused upon the presentation of multimedia files, the basic idea is applicable to any sort of object that you may wish to embed within an ASP.NET 2.0 page.

It is entirely possible to code the page to display multimedia files without using a custom control, having the control handy simplifies the process to the point where someone using it need only drop it onto the page and set a couple of properties within the IDE (or at runtime) to bring multimedia to the page.

At the heart of the control lies the Microsoft Windows Media Player control and for that reason, this custom control will handle any file or streaming media source that the Media Player control itself can handle. The example provided demonstrates the use of the control to display streaming audio and video from a web cam and to display stored contain accessible through a URL.

Since the Media Player is an ActiveX control, be advised that the browser may flag the control as a security risk to the end user. The demonstration web site included in this project includes four external sources of multimedia data; two were gleaned from California's Monterey Bay Aquarium which provides web cam feeds of several of its display areas; in the example, one control is pointed to the penguin cam and the other to the aviary cam; both are fun and interesting to look at. Also, when they are feeding and handling the penguins in front of a group you can listen to the speaker talk about the penguins (which are from South Africa). The aviary shows different types of seashore birds in a natural environment and it can be interesting to watch as well.

The other two controls are used to display a couple of rather odd television commercials for VW automobiles; these stored videos are made available through the popular You Tube web site (which seems to have quite a lot of odd and often humorous clips available for viewing). If you do not have a broadband connection, you may wish to consider dropping all but one of the controls from the demo page.

MultiMediaControl1-in-vb.net.gif

Figure 1. A demonstration of four controls in simultaneous use.

Getting Started:

In order to get started, open up the Visual Studio 2005 IDE and start a new project. From the new project dialog (Figure 1), under project types, select the "Windows" node from beneath "Visual Basic", then select the "Web Control Library" template in the right hand pane. Key in "MMP" for the project and then click "OK". (Note: all of the files are included with the project and you may opt to use those files in lieu of recreating everything from scratch)

Once the project has opened; right click on the solution and click on the "Add" menu option, and then select "New Item". When the "Add New Item" dialog appears (Figure 2), select the "Web Custom Control" template, after selecting the template, key "MediaPlayer.vb" into the name field and then click "Add" to close the dialog. You may now delete the default web control that was created when the project was originally initialized from the template.

At this point, we should have an open web control library project with a single web control named "MediaPlayer.vb" in that project. One last step prior to writing the code for this project will be to add in one needed reference. To add this reference, double click on the "My Project" icon in the solution explorer to open "My Project", from here, select the "References" tab, and then click the "Add" button. When the "Add Reference" dialog opens, select the .NET tab, and search down the list until you find the "System.Design" reference. Select this library and click on the "OK" button.

MultiMediaControl2-in-vb.net.gif

Figure 2. Visual Studio 2005 New Project Dialog

MultiMediaControl3-in-vb.net.gif

Figure 3: Add New Item Dialog

Navigate back to the "MediaPlayer.vb" file and, at the top of the file, confirm that the projects imports match the following:

Imports System

Imports System.Collections.Generic

Imports System.ComponentModel

Imports System.Text

Imports System.Web

Imports System.Web.UI

Imports System.Web.UI.WebControls

 

 

<ToolboxData("<{0}:MediaPlayer runat=server></{0}:MediaPlayer>")> _

Public Class MediaPlayer

Inherits WebControl

 

We are now ready to add the code necessary to make this control functional. First off, we need to create some private member variables; these variables will be used to contain the path to the multimedia file and set which (if any) controls will be displayed along with the media player at runtime..

To accomplish this step, create a "Declarations" region and key in the following variable declarations:

#Region "Declarations"

 

Private mFilePath As String

Private mShowStatusBar As Boolean

Private mShowControls As Boolean

Private mShowPositionControls As Boolean

Private mShowTracker As Boolean

 

#End Region

 

Once the variables have been declared, we will need to provide public properties to expose the control properties to the control user; in order to accomplish this step, create a "Properties" region and key in the following code:

#Region "Properties"

 

<Category("Media Player")> _

<Browsable(True)> _

<Description("Set path to media player source file.")> _

<Editor(GetType(System.Web.UI.Design.UrlEditor),

GetType(System.Drawing.Design.UITypeEditor))> _

Public Property FilePath() As String

Get

Return mFilePath

End Get

Set(ByVal value As String)

mFilePath = value

End Set

End Property

 

<Category("Media Player")> _

<Browsable(True)> _

<Description("Show or hide the tracker.")> _

Public Property ShowTracker() As Boolean

Get

Return mShowTracker

End Get

Set(ByVal value As Boolean)

mShowTracker = value

End Set

End Property

 

<Category("Media Player")> _

<Browsable(True)> _

<Description("Show or hide the position controls.")> _

Public Property ShowPositionControls() As Boolean

Get

Return mShowPositionControls

End Get

Set(ByVal value As Boolean)

mShowPositionControls = value

End Set

End Property

 

<Category("Media Player")> _

<Browsable(True)> _

<Description("Show or hide the player controls.")> _

Public Property ShowControls() As Boolean

Get

Return mShowControls

End Get

Set(ByVal value As Boolean)

mShowControls = value

End Set

End Property

 

<Category("Media Player")> _

<Browsable(True)> _

<Description("Show or hide the status bar.")> _

Public Property ShowStatusBar() As Boolean

Get

Return mShowStatusBar

End Get

Set(ByVal value As Boolean)

mShowStatusBar = value

End Set

End Property

 

#End Region

 

Note that, in the attributes section of the file path property, the code specifies an editor and further that the editor specified is defined as the URL Editor. Adding this attribute to the control specifies to the IDE how the property is to be edited; in this instance, when the control user sets the File Path property for the control, the property grid will display a button with an ellipsis in it at the right hand side of the text box. If the user clicks on the button, the IDE will open the URL editor and will permit the user to use that editor to navigate to the multimedia file and set the File Path property through that editor's dialog. The control user may just key or paste the file path or URL directly into the space provided without opening the editor. Properties set in this manner will be persisted within the control user's project.

<Editor(GetType(System.Web.UI.Design.UrlEditor), _ GetType(System.Drawing.Design.UITypeEditor))>_

The remaining properties are used to set Boolean values for each media player control related options such as whether or not to show the controls at all, or to show the track bar, etc. There is no editor associated with the Boolean values but the user will be limited to supplying either true or false in the property editor.

At this point, the only thing left to do is to define how the control will be rendered. To complete this step, create a "Rendering" region and, within this region, override the RenderContents sub with the following code (note that this code was cleaned up to fit on the page, the line breaks used here will not work in the IDE):

#Region "Rendering"

 

Protected Overrides Sub RenderContents(ByVal writer As

System.Web.UI.HtmlTextWriter)

 

Try

 

Dim sb As New StringBuilder

sb.Append("<object classid=clsid:22D6F312-B0F6-11D0-94AB-0080C74C7E95 ")

sb.Append("codebase=http://activex.microsoft.com/activex/

controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701

Width = " & Width.Value.ToString() & " Height = " &

Height.Value.ToString() & "type=application/x-oleobject

align=absmiddle")

sb.Append("standby='Loading Microsoft&reg; Windows&reg;

Media Player components...' id=mp1 /> ")

sb.Append("<param name=FileName value=" & FilePath.ToString() & "> ")

sb.Append("<param name=ShowStatusBar value=" &

ShowStatusBar.ToString() & "> ")

sb.Append("<param name=ShowPositionControls value=" &

ShowPositionControls.ToString() & "> ")

sb.Append("<param name=ShowTracker value=" &

ShowTracker.ToString() & "> ")

sb.Append("<param name=ShowControls value=" &

ShowControls.ToString() & "> ")

sb.Append("<embed src=" & FilePath.ToString() & " ")

sb.Append("pluginspage=http://www.microsoft.com/Windows/

MediaPlayer type=application/x-mplayer2 ")

sb.Append("Width = " & Width.Value.ToString() & " ")

sb.Append("Height = " & Height.Value.ToString())

sb.Append(" /></embed></object>")

 

writer.RenderBeginTag(HtmlTextWriterTag.Div)

writer.Write(sb.ToString())

writer.RenderEndTag()

 

Catch ex As Exception

 

' with no properties set, this will render "Custom MediaPlayer

Control" in a

' a box on the page

writer.RenderBeginTag(HtmlTextWriterTag.Div)

writer.Write("Custom Media Player Control")

writer.RenderEndTag()

 

End Try

 

End Sub

#End Region

 

Within this code there are a few things worth looking at; first, you can see how the embedded object tag is created and it does not take too much imagination to figure out that you can embed any valid object using this same approach. The string builder collects several variables from the control, the File Path is passed to the object's source, the controls height and width are also collected and passed to the object tag, and the control related properties are gathered and passed to the object's parameters.

Having defined the contents of the object tag, the only detail remaining is to put the control on the rendered page. This is accomplished in the three lines following the definition of the string builder:

writer.RenderBeginTag(HtmlTextWriterTag.Div)
writer.Write(sb.ToString())
writer.RenderEndTag()

In this example, the HTML writer is set up to place an opening Div tag, within the Div, the object defined in the string builder is written to the rendered page, and in the last line, the Div is closed.

The control is now complete. Prior to testing the control, rebuild the project. Once that has been completed and any errors encountered are repaired, it is time to test the control. To test the control, add a new web site project to the web control library project currently open (or use IIS to create a virtual directory for the included site and view that if you prefer). Once the test web site has been created, set the test project as the start up project by right clicking on the web site solution in the solution explorer and selecting the "Set as Start Up Project" menu option. Next, locate the Default.aspx page in the web site solution, right click on this page and select the "Set as Start Page" menu option.

Open the Default.aspx page for editing. Locate the newly created control in the toolbox (it should be at the top) and drag the "MediaPlayer" control onto the page (Figure 4).

MultiMediaControl4-in-vb.net.gif

Figure 4: Custom Control in Toolbox

You may now click on the object control and set its height, width, control, and file path properties. For this demo, the example webpage contains four controls each set with valid paths to media (valid as of November 30, 2006 anyway). Looking at the IDE's property editor, you should see each of the properties for any given control by clicking on the control:

MultiMediaControl5-in-vb.net.gif

Figure 5: Setting the Media Player Control's Properties in the IDE

Build the application and run it; you should now be looking at multimedia presentations on the page.

Summary

The article demonstrates the creation of a custom control; the example provided shows an approach to embedding a Windows Media Player control through a custom control as a means of simplifying the amount of work necessary to display multimedia content on an ASP.NET web page. The example code and projects were generated using ASP.NET 2.0 in Visual Studio 2005.

Up Next
    Ebook Download
    View all
    Learn
    View all