Click here to Skip to main content
Click here to Skip to main content

Build your own Flash player custom control in a flash

By , 11 Aug 2006
 

Introduction

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

Whilst it is entirely possible to code the page to display Flash 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 Flash to the page.

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 a name for the project, and then click “OK”.

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 “EmbeddedObject.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 “EmbeddedObject.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.

Figure 1: Visual Studio 2005 New Project Dialog

Figure 2: Add New Item Dialog

Navigate back to the “EmbeddedObject.vb” file and, at the top of the file, add in the Imports statements highlighted below:

Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.Design


<DefaultProperty("Text"), 
  ToolboxData("<{0}:EmbeddedObject 
  runat="server"></{0}:EmbeddedObject>")> _
Public Class EmbeddedObject
    Inherits WebControl

We are now ready to add the code necessary to make this control functional. First off, we need to create a single private member variable; this variable will be used to contain the path to the Shockwave Flash (SWF) file that the user wants to pass to the control. To accomplish this step, create a “Declarations” region and key in the following variable declarations:

#Region "Declarations"

    Private mFilePath As String

#End Region

Once the variable is declared, we will need to provide a public property to expose the control property to the control user; in order to accomplish this step, create a “Properties” region and key in the following code:

#Region "Properties"

<Category("SWF Source File")> _
<Browsable(True)> _
<Description("Set path to the SWF 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

#End Region

Note that, in the attributes section, 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 SWF file and set the file path property through that editor’s dialog. 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))> _

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:

#Region "Rendering"

Protected Overrides Sub RenderContents(ByVal writer _
          As System.Web.UI.HtmlTextWriter)

        Try
            Dim sb As New StringBuilder
            sb.Append("<object classid=clsid:D27" & _
                      "CDB6E-AE6D-11cf-96B8-444553540000 ")
            sb.Append("codebase=http://download.macromedia.com/pub/" & _ 
                      "shockwave/cabs/flash/swflash.cab#version=5,0,2,0 " & _ 
                      "Width = " & Width.Value.ToString() & _
                      " Height = " & Height.Value.ToString() & " > ")
             sb.Append("<param name=movie value=" & FilePath.ToString() & "> ")
             sb.Append("<param name=quality value=high> ")
             sb.Append("<param name=BGCOLOR value=#000000> ")
             sb.Append("<param name=SCALE value=showall> ")
             sb.Append("<embed src=" & FilePath.ToString() & " = high ")
             sb.Append("pluginspage=http://www.macromedia.com/shockwave/" & _ 
                       "download/index.cgi?P1_Prod_Version=ShockwaveFlash" & _ 
                       " type=application/x-shockwave-flash ")
             sb.Append("Width = " & Width.Value.ToString() & " ")
             sb.Append("Height = " & Height.Value.ToString() & " ")
             sb.Append("bgcolor=#000000 ")
             sb.Append("scale= showall></embed></object>")

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

        Catch ex As Exception

            writer.RenderBeginTag(HtmlTextWriterTag.Div)
            writer.Write("Custom Flash 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 StringBuilder collects three variables from the control, the file path is passed to the object’s source, and the control's height and width are also collected and passed to the object tag. The rest of the parameters are canned in this demonstration but could be replaced with additional properties which could also be set at design time, if so desired.

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 StringBuilder:

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 StringBuilder 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. 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.

If you downloaded the sample project, you may wish to grab two files from that sample web site and add them to the root of the web site solution. These files are entitled “cybertrick.swf” and “cybertrick.txt”. You may add the files to the project by right clicking on the web site solution in the Solution Explorer and selecting “Add Existing Item”.

Open the Default.aspx page for editing. Locate the newly created control in the toolbox (it should be at the top) and drag the “EmbeddedObject” control onto the page (Figure 3).

Figure 3: Custom Control in Toolbox

You may now click on the embedded object control and set its height, width, and file path properties. For this demo, the SWF file provided was designed to be 300 pixels tall and 600 pixels wide, so set the height and width properties to hold 300 and 600. Next, click on the file path property button to open the URL editor dialog. From here, select the “cybertrick.swf” to point the file path property to this file.

Build the application and run it; you should now be looking at a Flash presentation displayed within the custom control (Figure 4).

Figure 4: Flash in the Custom Control

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

salysle
Software Developer (Senior)
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralGood Work and Thanksmembersantosh d2 Mar '09 - 0:51 
I was looking for same project for last 3-4 days Thanks for this
Expecting more project like this.
QuestionDinamic Controlmemberdrc_no123 Jun '07 - 23:56 
Hello!
I have a question. I want to activate your control from C# code (or VB if you want :P ) ... something like<code>
List<BXSW.EmbeddedObject> lista_mea = new List<BXSW.EmbeddedObject>();
lista_mea.Add(new BXSW.EmbeddedObject());
lista_mea[lista_mea.Count - 1].FilePath = s;
lista_mea[lista_mea.Count - 1].Height = Unit.Pixel(1);
lista_mea[lista_mea.Count - 1].Width = Unit.Pixel(1);
lista_mea[lista_mea.Count - 1].Visible = true;
lista_mea[lista_mea.Count - 1].Enabled = true;
</code>
but nothing happens. s is a string with the content: "~/App_Data/Sounds/BanuManta.swf". And nothing happens.
The idea is that i want to dinamically set some sounds (because those files are wav imported files). And i want those sounds to play one after another. If you have any ideas, pleas do not hesitate to contact me.
Thank you a lot,
Catalin David.
AnswerRe: Dinamic ControlmemberMurrayMelvin24 Jul '07 - 11:25 
The problem is that the control isn't using Page.ResolveUrl on the FilePath property, which is what it needs to properly translate that ~ into the application path. If you go into the source, in EmbeddedObject.vb, change these lines:
 
Before:
sb.Append("<param name=movie value=" & FilePath & "> ")
After:
sb.Append("<param name=movie value=" & Page.ResolveUrl(FilePath) & "> ")
 
Before:
sb.Append("<embed src=" & FilePath & " = high ")
After:
sb.Append("<embed src=" & Page.ResolveUrl(FilePath) & " = high ")
 
This may also be the solution to jsmith4701's problem.
GeneralFlash doesn't appear in controlmemberjsmith470129 May '07 - 10:45 
I set the file path propery and I made sure I can just open the .swf file with IE, but my control won't play it. It just has a black background. Any ideas?
GeneralRe: Flash doesn't appear in controlmembersalysle30 May '07 - 17:23 
Yes, set the height and width properties to the exact size of the SWF file and give it another try. I have seen this as well and this has worked so far.
GeneralRe: Flash doesn't appear in controlmemberjsmith470131 May '07 - 15:30 
I set it to 300 x 600, but it still doesn't appear.
GeneralRe: Flash doesn't appear in controlmembersalysle4 Jun '07 - 13:59 
Is the control actually there; one way to tell would be to hover over the control and see if you get the "Click to activate and use this control" tip.
GeneralRe: Flash doesn't appear in controlmemberjsmith47015 Jun '07 - 2:43 
Yes, the control is there, but the movie doesn't play. No errors are being thrown. I just can't get a movie to come up.
GeneralRe: Flash doesn't appear in controlmembersunkmath17 Jan '09 - 9:10 
I am getting the same problem.Did you solve this?
QuestionDoes it convert WAV format to SWF?memberVince Zhou28 Mar '07 - 19:08 
I am looking for a audio conversion library in .Net that can convert WAV format to SWF format programmatically.
 
You will be appreciated if your tool can fulfill this requirement.
 
thanks,
Vince
AnswerRe: Does it convert WAV format to SWF?memberAlpha Nerd7 Jun '08 - 2:06 
It's NO. Duh.
 
"What if you guys are ever lost in the woods? Or trapped in a really dark place? Or if minesweeper.exe is missing from your aunt's computer?" - Jeff Atwood

GeneralThanksmemberBritney S. Morales23 Nov '06 - 2:48 
Good Control, I cant believe that VStudio 2k5 dont have a default flash control Cry | :((
 
keep Learning and you never will be out of date...

GeneralASP.NET Pro Magazinememberbri189b16 Aug '06 - 16:26 
If you look in the most recent ASP.NET Pro magazine you can find this article with how to customize for different browsers and make W3C compliant.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 11 Aug 2006
Article Copyright 2006 by salysle
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid