Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
ASP.Net 4 Hosting is here
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET and Web » Flash Player Custom Control for ASP.NET 2.0

Flash Player Custom Control for ASP.NET 2.0


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.

Author Rank:
Total page views :  27957
Total downloads :  783
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
embeddedObject.zip
 
Become a Sponsor

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 import statement 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 declaration:

#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"

#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:D27CDB6E-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 string builder collects three variables from the control, the File Path is passed to the object's source  and the controls 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 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.  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.

In the download you will find two files that you will need to add 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


Login to add your contents and source code to this article
 About the author
 
Scott Lysle
Freelance software developer residing in Alabama. Bachelors, Masters Degrees from Wichita State University. I spent the first half of my career working on aircraft controls and displays and in that time I worked on the cockpits for the OH-58 AHIP, the AH-1W, the V-22, the F-22, the C-130J, the C-5 AMP, AWACS, JPATS, and a few others. Since 1997 I have been largely involved with Windows and web development, GIS application development, consumer electronics development (embedded linux/java), but still sometimes work on aircraft and military projects, the most recent of which was the presidential transport helicopter. I tend to work primarily with C/C++, Java, VB, and C#.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments
Error when i run the proyect by karla On July 30, 2007
Hi , when i run the proyect the control it's black and when i right clicking appear in a gray color the l;eyend movie not loaded
Reply | Email | Delete | Modify | 
Error when i run the proyect by karla On July 30, 2007
Hi , when i run the proyect the control it's black and when i right clicking appear in a gray color the l;eyend movie not loaded
Reply | Email | Delete | Modify | 
Re: Error when i run the proyect by Scott On August 1, 2007

Karla:

Try setting the height and width properties to the height and width of the swf file; that typically eliminates this problem.

Scott

Reply | Email | Delete | Modify | 
Re: Re: Error when i run the proyect by omar On September 4, 2008
i have the same problem and i set the control size size as the flash movie size but still not loaded file :(, any help???
Reply | Email | Delete | Modify | 
Thanks. Great. by Henry On May 18, 2009
Thanks a lot. Fantastic tips. Hill
Reply | Email | Delete | Modify | 
Re: Thanks. Great. by Scott On May 19, 2009
Thanks, I'm glad it helped.
Reply | Email | Delete | Modify | 
SomeTitle by Toshko On July 30, 2009
It would be a good idea to actually supply the whole solution rather than a .vb file.
Reply | Email | Delete | Modify | 
some errot to rebuild the project by Noman On August 27, 2009
when i import System.Web.UI.Design then this line got underlined
and also in the properties region the following line got underlined
System.Web.UI.Design.UrlEditor
please help me, the project is not rebuilding
Reply | Email | Delete | Modify | 
fasf by watches On July 11, 2010
As to many people, owning an authentic louis vuitton purse has become his or her pursuit, and a symbol of status. Why people are willing to buy such an extremely expensive louis vuitton bags ? In the first place, Monogram Roses Canvas has long history famous for its high qualitative sense for leather, especially those leathers having been used for a long time. Monogram Rubis would become honey color.
Reply | Email | Delete | Modify | 
lv by watches On July 11, 2010
Louis vuitton bags features a zipper closure with a padlock to ensure absolute safety and optimum utility. It is made of Damier canvas, together with red textile lining and smooth leather trimmings. The lv is embellished with shiny golden brass piece, which enhances the aesthetic apple of louis vuitton and brings the sunshine to you heart. With louis vuitton bag , you do not need to worry about the safety of your purse and cell phone for there are an interior flat pocket and a cell phone pocket.
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.