Blue Theme Orange Theme Green Theme Red Theme
 
MindFusion's Components
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET & Web Forms » Display Videos in ASP.NET 2.0

Display Videos in ASP.NET 2.0

This article shall describe the construction of a custom control used to play video on an ASP.NET web page. The control is based upon the Windows Media Player active X control; with it you can add canned or live video to a web page by setting a property or two at design time, or from the ASP.NET page itself.

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

Introduction

This article shall describe the construction of a custom control used to play video on an ASP.NET web page. The control is based upon the Windows Media Player active X control; with it you can add canned or live video to a web page by setting a property or two at design time, or from the ASP.NET page itself.



Figure 1:  Displaying Video on a Web Page with a Custom Control.

The Solution

The solution contains two projects; the first is the web custom control and the seconds is a sample web site with two pages, each displaying the controls in use to display video. The control project is called "Web Video"; it contains a single web custom control called, "WVC". The demonstration website contained in the second project is called, "TestWVC". The website contains to web pages called "Default" and "Webcams".



Figure 2:  The Solution Showing Both Projects.

The Code:  Web Video - WVC Custom Control

The WVC custom control project is a web custom control project; it contains only a single control (WVC). This control wraps up the media player control and provides design time support for the control through a collection of properties used to set some of the various properties used by the media player control.

The only reference added to the project, aside from the defaults, was System. Design.  System. Design is necessary to support some of the design time functionality exposed by the control such as using the URL editor with the file path property of the control.



Figure 3:  Adding System Design to the Custom Control References.

The imports, namespace, and class declarations are as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebVideo
{ 
    [DefaultProperty("FilePath")]

    [ToolboxData("<{0}:WVC runat=server></{0}:WVC>")]

    public class WVC : WebControl

{

Note that in the class declaration, the default property is set to "FilePath"; this property is used to set the URL to the actual media file to be played by the player control. By setting this value to "FIlePath", whenever the developer adds the control to a web page, the property grid will focus on this property first.

After the class declaration, the next block of code is used to declare a set of local member variables, each of which shall be controlled by a related property:

#region Declarations
private string mFilePath;
private bool mShowStatusBar;
private bool mShowControls;
private bool mShowPositionControls;
private bool mShowTracker;
#endregion

Following these member variable declarations, the next region of code shall be used to provide the code for the properties which will be used to set and get the values for each of the member variables (note the attributes provided for each property; the description provided is used in the property grid to describe what each property does):

#region Properties
[Category("File URL")]
[Browsable(true)]
[Description("Set path to source file.")]
[Editor(typeof(System.Web.UI.Design.UrlEditor), 
typeof(System.Drawing.Design.UITypeEditor))]
public string FilePath
{
    get
    {
        return mFilePath;
    }

    set

    {

        if (value == string.Empty)

        {

            mFilePath = string.Empty;

        }

        else

         {

            int tilde = -1;

            tilde = value.IndexOf('~');

            if (tilde != -1)

             {

                  mFilePath = value.Substring((tilde + 2)).Trim();

             }

            else

            {

                mFilePath = value;

            }

        }

    }

}   // end FilePath property

  

[Category("Media Player")]

[Browsable(true)]

[Description("Show or hide the tracker.")]

public bool ShowTracker

{

    get

    {

        return mShowTracker;

    }

     set

     {

         mShowTracker = value;

     }

}

  

[Category("Media Player")]

[Browsable(true)]

[Description("Show or hide the position controls.")]

public bool ShowPositionControls

{

    get

    {

        return mShowPositionControls;

    }

    set

    {

        mShowPositionControls = value;

    }

}

  

[Category("Media Player")]

[Browsable(true)]

[Description("Show or hide the controls.")]

public bool ShowControls

{

    get

    {

        return mShowControls;

    }

    set

    {

        mShowControls = value;

    }

}

  

[Category("Media Player")]

[Browsable(true)]

[Description("Show or hide the status bar.")]

public bool ShowStatusBar

{

    get

    {

        return mShowStatusBar;

    }

    set

    {

         mShowStatusBar = value;

    }

}

#endregion

 

The last region of code contained in the custom control is that used to actually render the control:

#region "Rendering"
protected override void RenderContents(HtmlTextWriter writer)
{
    try
    {
        StringBuilder sb = 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

    {

        // with no properties set, this will render "Display PDF

        // Control" in a

        // a box on the page

        writer.RenderBeginTag(HtmlTextWriterTag.Div);

        writer.Write("Display WVC Control");

        writer.RenderEndTag();

    }  // end try-catch

}   // end RenderContents

#endregion

To render the control, the "RenderContents" method is overridden. Within a try-catch block, the contents of the control are defined using a string builder; once defined, the string builder is converted to a string and dropped within the beginning and ending div tags. Once the control is added to a page, the control will be contained within a div. As far as the string builder goes, it sets the class ID of the object to point to the ID of the media player control, sets the code base, and then sets each of the parameter values used in the control to configure the media player.

In the catch portion of the try-catch block, if the control errors the words, "Display WVC Control" will appear on the page. This will happen if the file path property is not set (which it will not be when the control is dragged onto a form). In order to prevent the lack of a file name causing an error, the control is rendered differently (and without the media player control) as soon as it is added to the form.

Since the control is wrapped in a div; any of the properties also available to a div are also added to the control's property grid (for example, one may set the border style, background color, etc. of the control because those properties are available to the div).

The Code:  Test Web WVC

The demonstration web project is comprised of two web pages; one page, the default, demonstrates a single control in use. It also uses a drop down list control set to auto postback; the list contains a set of items with the value property pointing to a valid source of media. When the drop down list is used, the media player's file path is set to point to the new source of media. The second page contains four controls each set to a different source and with the control panel options enabled. The code is trivial and is not reported in this document.



Figure 4:  Demo Page One.



Figure 5:  Demo Page Two.

Summary :

By wrapping up the media player control in a custom web control, it becomes very easy to embed or even dynamically embed the controls into web pages. By moving the code required to display a media player into the custom control, it is no longer to code out the content into each page using the controls.


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.
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.
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 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
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
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
WVC.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
Display Video using a C# Web Custom Control by Jack On June 20, 2007
Sweet, Can I add this control to a repeater and access it in the ItemDataBound event? You should post this to spikesolutions.net
Reply | Email | Delete | Modify | 
HELP NEEDED by r On July 3, 2007
Hi Scott, Have gone through the article which displays video using a C# Web Custom Control, I have been doing the R&D almost for 3 weeks always got stuck in playlist area. Mentioned below are the steps involved: 1) I have alist of videos/audios (of any format 3gp,rm,mov,.mpeg|.mp3|.m3u|.aac|.aif|.iff|.mid|.midi|.mpa|.ra|.ram|.wav|.wma .wmv|.mpg|.3gp|.asf|.asx|.avi|.mov|.mp4|.qt|.rm|.swf|) 2)User selects any of this files and clicks on play button 3)so accordingly i need to dipaly the video / audio file 4)Also he has the option to include files in playlist which will execute the files one after the other. Now my problem is with WMPlayer u can run some specific files/Quicktime can run some specific files/Real player can run some specific files. Need to know which player to use so that it can deal with maximum of formats. Alos it would be great if you could assist me achieving the desitred output since you already have knowledge. Any help will be greatly appreciated. Luking ahead.... Reagrds, Rupali
Reply | Email | Delete | Modify | 
thanks for info by rushabh On August 30, 2007
Hi scott!i have found this info.very useful.
Reply | Email | Delete | Modify | 
How do connect the video to my USB camera by Chun On September 14, 2007
Hi Scott: This is the best example for playing video. Thank you for the contribution. I'd like to feed real time video from my USB camera or IP camera. Please advise, Thank in advance. Chun Zhang
Reply | Email | Delete | Modify | 
Display Video by Manish On October 18, 2007
Hi Scott, Good article but i have one problem with this control, This control works fine in mojila but in IE version less than 6.0 ,it doesn't display the video during scrolling of the page. Please help.
Reply | Email | Delete | Modify | 
Great Work! Thanks by Kamran On October 31, 2007
absoulutly great work done
Reply | Email | Delete | Modify | 
Help Need by Sudheer Reddy On December 12, 2007
After i studied this article, i thought it solves my problem becaz am also searching how to play a video files in Webbrowser using Asp.net & C#.net. But in this article i not found "Test Web WVC" Web part code. I need that code to implement in my application. Please provide that code to me, it's very help to me.
Reply | Email | Delete | Modify | 
i can download wvc.zip by kalpesh On January 25, 2008
you have given the download option to download but i cannot download it
Reply | Email | Delete | Modify | 
Re: i can download wvc.zip by Scott On January 25, 2008
If you have a problem with the download, send me an email at scottlysle@cableone.net and I will email you a copy of the article and project.
Reply | Email | Delete | Modify | 
one file missing on WVC.zip folder by sudarshan On February 4, 2008
Hi one asp.net file named WebCams.aspx is missing. Please help where can i find the same... Thanks in Advance.
Reply | Email | Delete | Modify | 
Re: one file missing on WVC.zip folder by irshad On January 7, 2009

HI Sudarshan

        I also need the webcam.aspx file, have you find this file ? if you have then plz send to me on irshad.don@gmail.com

Reply | Email | Delete | Modify | 
not work in firefox by Ahmed On October 27, 2008
please tell me why the control worked well in IE but not worked in FireFox
Reply | Email | Delete | Modify | 
Re: not work in firefox by Scott On November 5, 2008

You need to install the firebox adobe flash player plugin.

http://www.macromedia.com/software/flash/about/

Reply | Email | Delete | Modify | 
Nice by Dale On December 2, 2008
Simple and elegant. Good use of extension.
Reply | Email | Delete | Modify | 
Test WVC isn;t found by june On December 16, 2008
I have downloaded WVC.zip, However, TestWVC isn't found. I really need help for my project Any advice or help? Thanks (:
Reply | Email | Delete | Modify | 
Re: Test WVC isn;t found by Scott On December 17, 2008

Sure; email me at scottlysle@cableone.net and I will send you a copy.

Scott

Reply | Email | Delete | Modify | 
controlling the video by Jerry On January 9, 2009
great code, thx! two questions: 1. is it possible to use the control but not have the video play until the user hits the play button? currently, the video automatically loads and plays when the page is loaded. this causes a problem, because i use three instances of the control on a page, and they all start playing at once. 2. can the contol pay other types of media, or is it limited to wmv files? thanks again!
Reply | Email | Delete | Modify | 
Re: controlling the video by Scott On January 10, 2009

To do what you want to do with the control, add a new class to the control project, call it viewer, open the code window and past in this code:

Once done, use the viewer control in lieu of the original version and set the autostart property to false and set the UI mode property to full or mini.  The control will come up paused, the user can click the play button to start it off.

As for files types, you can play any video file type compatible with the Windows Media Player and you can also stream media to the player (asf).

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Text;

using System.Web;

using System.Web.UI;