Silverlight 4 : YouTube – Standard Feed, Search and Play videos – Tip of the day

 

Download: Source

YouTube is the most popular and largest video sharing website on which users can upload, view and share videos.  One of the key features of YouTube is the ability to view its videos on other web pages and client applications.

The YouTube APIs allows us to bring the YouTube experience to web pages, applications and devices.

YouTube .NET client APIs can be used by authenticated and anonymous users.

  • Anonymous user : Read only standard feeds.(Most Viewed,Top Rated,Watch On Mobile, Most Discussed,Top Favourites,Most Responded, Most Recent etc)
  • Authenticated user : Public feeds, private feeds (user’s inbox feed), upload, delete and update operations.

In order to user YouTube SDK, we have to perform the following initial steps

  1. Sign up for the Developer key. A Developer key uniquely identifies a product that is submitting the request. This Key should be provided in every YouTube API request
  2. Download and install .NET YouTube SDK

Default Location for the installed YouTube dlls

The following is a sample feed that we can parse manually to get video related information or this could be done easily by using YouTube .NET client APIs (there are three dlls in the package).

Example: Standard Feed – http://gdata.youtube.com/feeds/api/standardfeeds/most_viewed

In this article i am going to walk through a silverlight out of browser app, called silverTube.

This app got following abilities:

  • Fetching standard and private feeds,
  • Perform keyword search,
  • Playing videos, and
  • Hint of pagination capabilities.

Before stating the project, lets have a look at the end product.

Open the Visual Studio 2010 or Visual Web Developer 2010 Express with the Silverlight 4 tools installed.

Create a new silverlight project and name whatever you like. (here silverTube)

We already installed the YouTube SDK and now we need to have reference to them in our silverlight application. But silverlight runtime doesn’t allow to include those YouTube dlls in the project!

There is a workaround about this issue. We will add those dlls as well as a new WCF Service to our silverTube.Web project, and then our silverlight app can easily call that web service.

Add another reference to System.Runtime.Serialization.dll. The System.Runtime.Serialization namespace contains classes that can be used for serializing and deserializing objects.

Now add the following classes to the silverTube.Web project. Those classes will hold video meta data information.

We will now add a Silverlight-enabled WCF Service to this project and name it as svcSilverTubeServer.svc. Here i am using Silverlight-enabled WCF service template over the standard WCF Service because it is already pre configured and ready to use with Silverlight.

Insert the following namespaces

 

Before start coding lets have a look at the following diagram that will explain the base concept

 

Now we will write a private function called InitializeRequest that takes two parameters

  • prmUserName
  • prmPassword

If we provide valid Username and Password, then our intention is to get private feeds and also to perform upload, delete and update operation. Otherwise we could only get public feeds.

 

The following is the first public facing web service function for this project.

Our PrepareFeed method takes Atom feed collection and populate our custom collection for the later use

 

The GetYouTubeByKeyword method allows us to search videos by:

  • prmKeyword: a search query term
  • prmSafeSearch: Our intention to include all types of videos
  • prmOrderBy: Sorting our entries.
  • prmVideosBetweenTimeRange: A time period to limit standard feed results.
  • prmVideoCategory: Videos by categories.
  • prmCurrentPage: Current page no is the starting entry no.
  • prmPageSize: Maximum number of entries to return for the current page.

Have look at the method implementation. I guess its well commented.

Now its time to get private feed. Authentication is required for this purpose.

 

At this point we done with our WCF service. Now its time to consume the service in our Silverlight application.

Right-click the silverTube project in Solution Explorer > Select Add Service Reference > Click Discover to get following screen that lists all the supported operations and give a namespace as clientYouTube

Following XMAL is for our app that could be modified and extended by you. Based on the requirements your XMAL could be different than my one.

 

ImagePathConverter class:

Code behind for this app is very straight forward. So i am not going to explain here, you better please download the source.

Now we are going to configure the application so that it can be installed for out of browser use.

Right-click the silverTube project in Solution Explorer > Silverlight > Check Enable running applications out of the browser

There is one last thing we need to do is to add clientaccesspolicy.xml file in the silverTube.Web project. This configures the service to allow cross-domain access.

Throughout this article I tried to show you how searching and playing of YouTube videos could be done. In future i will look more into uploading and downloading YouTube videos.

Ref: http://code.google.com/apis/youtube/2.0/developers_guide_dotnet.html 

Until than Happy coding.
Sumon Barua

 Download: Source

Advertisements

Silverlight 4 : Data Validation – Tip of the Day – Part 1

Data validation is very very important for all sort of data driven applications and websites. It is a purifying process where it ensures only valid data is being saved into the database. So, today I am going to talk about Data Validation in Silverlight.

By default silverlight doesn’t give any visual feedback when the data binding system encounters error relating to incorrect input. But what it does is, it rejects data internally.  At this point the user is under the impression that data has been saved. But its not the case. I agree with you, its misleading.

In this situation what can we do?

Yes, it would be nice if the silverlight data binding engine notify or alert us through visual feedback when there is a violation of rules. Lets start with simple application which will give us a simple basic ground for future advanced investigation on data validation.

 

Step 1 : Create a silverlight application and add the following Student class to your project

Step 2 : Open the MainPage.xaml.cs code behind and modify the MainPage() constructor that should look like the following section. LayoutRoot is our grid container.

 

Step 3 : There you go, XAML. The following section goes between UserControl tag.

Step 4 : Run the application and type any string in the age filed and then try to move your cursor to other control. As expected internal validation has happened by rejecting the invalid input with no visual feedback. But we want visual feedback, lets see what can be done to achieve this “Visual feedback” or “error message”.  

Step 5 : ValidatesOnExceptions is the very first step for implementing all types of validation.

ValidatesOnExceptions

ValidatesOnExceptions = True, by doing that, it will makes sure silverlight will provide visual feedback for the validation error. This property tells the binding engine that if any sort of exception happens during data transfer to the underlying data source, then treat the exception as a validation error.

Silverlight reports a validation error in the following situations

  • Type conversions failure.
  • When there is a error in binding object’s set accessor.
  • When there is an exception from validation attribute

Key points to remember:

  • Data binding must be TwoWay
  • ValidatesOnExceptions = True
  • When a TwoWay bound control (in our example, textbox) looses focus, the value gets updated to the source.

Now look at the modified XAML for the text boxes:

Step 6 : Run the application and type any string in the age filed and try to move your cursor to other control. This is like magic, now I can see the visual feedback from Silverlight app and this is about the wrong data type. But that’s not enough for me, I want to put a range validation(0 to 100) for the Age field. Don’t get bored, you might be wondering why Mr Sumon is proceeding slowly? Mate, that’s how I proceed. Lets move on …..

 

Step 7 : Now its time to modify the existing Student Class. Modify the Age property setter.

 

Step 8 : Run the application, at this stage the Age field is able to handle two types of validation (Invalid data type and Range validation). Now that we are clear on that, I am hungry for more adventure, just keep following me.

What I want now is that when there is an invalid input in the Age field, I want the textbox to have yellow background and also showing the error message via tooltip. I am just showing different ways but its up to you guys to drive your imagination.

Step 9 :

NotifyonValidationError = True

NotifyonValidationError = True, this makes the binding engine to raise the BindingValidationError event during the exception. This is a routed event which could be handled by the target control or by the parent container(more realistic). Again modify the XAML for the textboxes

So, I attached BindingValidationError event to the Grid container. The handler at the parent or container level could conceivably perform validation on multiple child elements.

 

Step 10 : Up to this point, we are having relative visual error feedback but we want more control! In BindingValidationError handler we can specify more validation actions. In our case wanted actions are, making the background yellow and showing error message using the tooltip for the guilty control.

Step 11 : I can’t wait to run the app. There you go!

 

I am happy that individual control is showing the related error messages and doing extra activities. I got another idea, it would to nice if I could show all the error messages in one place in a summary format. Does this ring a bell? Yes, we can achieve this through ValidationSummary control in Silverlight.

Step 12 :

ValidationSummary

Namespace:  System.Windows.Controls
Assembly:  System.Windows.Controls.Data.Input (in System.Windows.Controls.Data.Input.dll)

Using ValidationSummary control we can display a consolidated list of validation errors. By default, the control displays error for its parent container control. To specify a different container we have to set the Target property. Target property is null by default.

Quick steps:

  • Add a reference to System.Windows.Controls.Data.Input
  • Declare the namespace in the XAML markup.
  • Finally insert the ValidationSummary control tag.

Step 13 : Running the app should give you the following one.

 

Validation for the textbox happens when it loses focus, if the data is valid it gets reflected on data source otherwise gets rejected which is a default behaviour. But I want data propagation and validation to happen only when I click the save button, not when textbox looses focus . That means I have to change the default behaviour. This could be done using UpdateSourceTrigger property of the Binding object.

Step 14 :

UpdateSourceTrigger

UpdateSourceTrigger accepts two values:

  • Default
  • Explicit

UpdateSourceTrigger = Default indicates automatic update what it was doing until now. UpdateSourceTrigger = Explicit, to disable automatic updates to the binding source. That means, from now on you have to manually update the source. This is useful when user want to perform some sort of activities before the data propagation to source and on demand validation (i.e. in our case Button click event), not when textbox looses focus.

 

 

Step 15 : Now we will see how we could manually update the source which in turns fires the validation process. When user types invalid data and moves to other control, there should be no validation. Now validation only happens in button click.  

This is a multipart article and I want to take a break.  My next articles will be based on following topics:

  • Data Annotation
  • Validation with IDataErrorInfo and INotifyDataErrorInfo (This is new to Silverlight 4)

Can’t wait to start the second part of this article.

Happy Coding.
Sumon Barua

Download: Source

Silverlight 4 – Datagrid (Sorting, Grouping, Filtering and Paging) – Tip of the day

A Datagrid is an excel like graphical user interface element that presents data in tabular format. It provides the ability to select, sorting, grouping, filtering, paging, adding, editing, deleting from its associated data source.

 

In this article I am going to discuss about the sorting, grouping, filtering and paging. Some of the features are built into Datagrid, say for example sorting. But sometimes, we need to code them manually.

 

Before we start our journey have a look at the diagram. If you understand the diagram that’s good, if you don’t that’s even better. I will explain them as we proceed.

 

 

 

We can achieve above functionalities in various way(hard way or easy way). I am lazy and always looking for the easy way so I prefer PagedCollectionView class. It represents a view for sorting, grouping, filtering, paging.

Simply I can say PagedCollectionView  is a collection view as a layer on top of a binding source collection that allows us to achieve the above functionalities without having to manipulating the underlying source. More easily,  PagedCollectionView is a wrapper for your collection.

PagedCollectionView can act on any collection that implements the IEnumerable interface such as a ObservableCorllection, List etc

 

 

Sorting:

 

Namespace: System.ComponentModel

Assembly:  WindowsBase (in WindowsBase.dll)

 

Sorting is the built in feature of the Datagrid and allows user to sort by clicking on the header of a column. But in our case, we will be sorting Datagrid based on the ComboBox item selection.

 

SortDescriptions collection of PagedCollectionView describes how items are sorted in view. SortDescriptions is a collection in which we can add more than one sort field. We add sort field by adding SortDescription that specify which property will be used for sorting and the direction(ascending or descending order).

 

The quick steps :

 

1.      Clear the existing sorting from the collection.

2.      Create a SortDescription and pass the name of the property to sort and direction

3.      Add the SortDescription to the SortDescriptions collection. Based on the requirements we can add more than one SortDescription(So it can be done multilevel)

//========================================================================================================= 
//Sort data by Fieldname
private void SortByFieldName(string prmFieldName) { //globalPVC is a PagedCollectionView object if (globalPVC != null && prmFieldName.Trim().Length>0) { globalPVC.GroupDescriptions.Clear(); globalPVC.SortDescriptions.Clear(); globalPVC.SortDescriptions.Add(new SortDescription(prmFieldName.Trim(), ListSortDirection.Ascending)); } } //=========================================================================================================

 

Grouping:

 

Namespace: System.Windows.Data

Assembly:  PresentationFramework(in PresentationFramework.dll)

 

Grouping is similar to sorting and can be done multilevel. For grouping we are going to use PropertyGroupDescription property.

GroupDescriptions collection of PagedCollectionView describes how items are grouped in view. GroupDescriptions is collection in which we can add more than one Grouping. We add Grouping field by adding PropertyGroupDescription that specify which property will be used for groping.

 

The quick steps :

 

1. Clear the existing grouping from the collection.

2 .Create a PropertyGroupDescription and pass the name of the property to group.

3. Add the PropertyGroupDescription to the GroupDescriptions collection of PagedCollectionView. Based on the requirements we can add more than one PropertyGroupDescription (So it also can be done multilevel)

        //==================================================================================================
        //Grouping data by Fieldname
        private void GroupByFieldName(string prmFieldName)
        {
            if (globalPVC != null && prmFieldName.Trim().Length>0)
            {
                //globalPVC is a PagedCollectionView object
                globalPVC.GroupDescriptions.Clear();
                globalPVC.SortDescriptions.Clear();
                globalPVC.GroupDescriptions.Add(new PropertyGroupDescription(prmFieldName.Trim()));

            }
        }
        //=================================================================================================

 

Filtering: 

 

Namespace: System.Windows.Data

Assembly:  System.Windows.Data (in System.Windows.Data.dll)

 

Filtering is used to determine whether an item is suited for inclusion in the view. This can be achieved by setting a callback method to the PagedCollectionView.Filter property.

Callback method provides the filtering logic. This callback method examines each row and indicates if the row should be included or excluded by returning true or false.

 

The quick steps:

 

1. Remove the existing filter.

2. Create a callback method that accepts a parameter of type Object.

3. Set the callback method to the PagedCollectionView.Filter property.

 

        //=====================================================================================================
        void butFilter_Click(object sender, RoutedEventArgs e)
        {
            //globalPVC is a PagedCollectionView object
            globalPVC.Filter = null;
            globalPVC.Filter = new Predicate<object>(DoFilter);
        }

                //Callback method

                private bool DoFilter(object o)

                 {

                       //it is not a case sensitive search

                       Employee emp = o as Employee;

                       if (emp != null)

                           {

                              if( emp.Name.ToLower().IndexOf (txtFilter.Text.Trim().ToLower()) >= 0 )

                                    {

                                       return true;

                                    }

                              else

                                  {

                                     return false;

                                  }

                           }

                     return false;

                  }

                 //=============================================================================================

 

 

Paging:

 

PagedCollectionView is able to split data into multiple pages having a fixed number of rows per page. Paging is useful for large amount of data.

 

In silverlight paging became simpler because of DataPager control. The DataPager control provides a configurable user interface for paging through a data collection. We can bind the DataPager to any IEnumerable collection. In our case we will bind DataPager with PagedCollectionView or ItemsSource of the Datagrid.

 

The following are the important properties from the data binding point of view:

PageSize – Number of rows to be displayed per page

DisplayMode – Defines the look of the DataPager

SourcePagedCollectionView or any collection that implements IEnumerable

You can modify the appearance of the DataPager by setting the DisplayMode property 

  

 image source: http://msdn.microsoft.com/en-us/library/system.windows.controls.datapager(v=VS.95).aspx

Now we will develop a small project which will target the above features. The end result will resemble to the following one. This is not a fancy one but will serve our purpose.

  

 Step 1: Create a new silverlight application project and name it whatever you like

Step 2: First focus on the UI build. Open the  MainPage.xaml and place the following code between UserControl tag. Now your XAML should be similar to the following.

    <Grid x:Name="LayoutRoot" Background="White">

        <Grid.RowDefinitions>

            <RowDefinition Height="25" />

            <RowDefinition Height="25" />

            <RowDefinition Height="25" />

            <RowDefinition Height="25" />

            <RowDefinition Height="227" />

            <RowDefinition Height="25" />

        </Grid.RowDefinitions>

 

        <StackPanel  Orientation="Horizontal"  HorizontalAlignment="Left" Grid.Row="0">

            <TextBlock Name="textBlock1" VerticalAlignment="Top" Text="Sort By:" Height="20" Width="100" />

            <ComboBox  Name="comSort" VerticalAlignment="Top"  Width="330" />

        </StackPanel>

 

        <StackPanel  Orientation="Horizontal"  HorizontalAlignment="Left" Grid.Row="1">

            <TextBlock Name="textBlock3" VerticalAlignment="Top" Text="Group By:"  Width="100" />

            <ComboBox  Name="comGroup" VerticalAlignment="Top" Height="20" Width="330" />

        </StackPanel>

 

        <StackPanel  Orientation="Horizontal"  HorizontalAlignment="Left" Grid.Row="2">

            <TextBlock Name="textBlock4" VerticalAlignment="Top" Text="Search by name :"  Width="100" />

            <TextBox Name="txtFilter" Width="330"/>

            <Button Name="butFilter" Content="Search" Width="50" />

        </StackPanel>

       

        <StackPanel  Orientation="Horizontal"  HorizontalAlignment="Left" Grid.Row="3">

            <TextBlock Name="textBlock5" VerticalAlignment="Top" Text="Enable Pagin"  Width="100" />

            <CheckBox x:Name="chkPaging" />

        </StackPanel>   

   

        <sdk:DataGrid x:Name="dgEmployee" AutoGenerateColumns="True" 

                      Grid.Row="4" Height="211" Margin="0,16,0,0" 

                      VerticalAlignment="Top" Width="453"  HorizontalAlignment="Left" />

       

        <sdk:DataPager x:Name="pagerEmployee" PageSize="3"

                       DisplayMode="PreviousNext"

                       NumericButtonCount="3" Grid.Row="5"

                       Height="24" HorizontalAlignment="Left"  VerticalAlignment="Center" Margin="0,0,147,0" Width="450"

                       Visibility="Collapsed"></sdk:DataPager>

 

    </Grid>

 

 

Step 3: In order to keep the project simple we will work on in memory data(in future article will work on real data from database). So at this stage we are going to create and code an Employee class. The following is the Employee class:

public class Employee
{
    public int EmployeeID { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
    public double Salary { get; set; }
}

Step 4: Now the code behind

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.ComponentModel;
using System.Collections.ObjectModel;

namespace FirstDataGridC
{
    public partial class MainPage : UserControl
    {
        PagedCollectionView globalPVC;
        public MainPage()
        {
            InitializeComponent();

            //Populate Sort and Group Combo
            PopulateCombos();

            //Load Employee and Populate Datagrid
            LoadEmployee();

            //Selection Changed Event for Sort and Group Combo
            comSort.SelectionChanged += new SelectionChangedEventHandler(comSort_SelectionChanged);
            comGroup.SelectionChanged += new SelectionChangedEventHandler(comGroup_SelectionChanged);

            //Click Event Handler
            butFilter.Click += new RoutedEventHandler(butFilter_Click);

            chkPaging.Click += new RoutedEventHandler(chkPaging_Click);
        }

        void chkPaging_Click(object sender, RoutedEventArgs e)
        {
            if (chkPaging.IsChecked == true)
            {
                //avtivate datapager
                //pagerEmployee.Source = globalPVC;
                pagerEmployee.Source = dgEmployee.ItemsSource;
                pagerEmployee.Visibility = Visibility.Visible;
            }
            else {
                //deavtivate datapager
                pagerEmployee.Source = null;
                pagerEmployee.Visibility = Visibility.Collapsed ;
                LoadEmployee();
            }

        }

        void butFilter_Click(object sender, RoutedEventArgs e)
        {
            globalPVC.Filter = null;
            globalPVC.Filter = new Predicate<object>(DoFilter);
        }

        //Callback method
        private bool DoFilter(object o)
        {
            //it is not a case sensitive search
            Employee emp = o as Employee;
            if (emp != null)
            { 
                if( emp.Name.ToLower().IndexOf (txtFilter.Text.Trim().ToLower()) >= 0 )
                {
                    return true;                
                }
                else
                {
                    return false;
                }
            }
            return false;
        }
        void comGroup_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string localItem = comGroup.SelectedItem as string;
            GroupByFieldName(localItem);
        }

        //Grouping data by Fieldname
        private void GroupByFieldName(string prmFieldName)
        {
            if (globalPVC != null && prmFieldName.Trim().Length>0)
            {
                globalPVC.GroupDescriptions.Clear();
                globalPVC.SortDescriptions.Clear();
                globalPVC.GroupDescriptions.Add(new PropertyGroupDescription(prmFieldName.Trim()));

            }
        }

        void comSort_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string localItem = comSort.SelectedItem as string;
            SortByFieldName(localItem.Trim());
        }

        //Sort data by Fieldname
        private void SortByFieldName(string prmFieldName)
        {
            if (globalPVC != null &&  prmFieldName.Trim().Length>0)
            {
                globalPVC.GroupDescriptions.Clear();
                globalPVC.SortDescriptions.Clear();
                globalPVC.SortDescriptions.Add(new SortDescription(prmFieldName.Trim(), ListSortDirection.Ascending));

            }
        }

        //Loading dummy data
        private void LoadEmployee()
        {
            ObservableCollection<Employee> objColEmp = new ObservableCollection<Employee>();
            objColEmp.Add(new Employee { EmployeeID = 1, Name = "Sumon Barua", Department = "IT", Salary = 10 });
            objColEmp.Add(new Employee { EmployeeID = 2, Name = "Sharmila Barua", Department = "Finance", Salary = 11 });
            objColEmp.Add(new Employee { EmployeeID = 3, Name = "Sujan Barua", Department = "IT", Salary = 8 });
            objColEmp.Add(new Employee { EmployeeID = 4, Name = "Saurov Barua", Department = "Finance", Salary = 8 });
            objColEmp.Add(new Employee { EmployeeID = 5, Name = "Raj1", Department = "IT", Salary = 20 });
            objColEmp.Add(new Employee { EmployeeID = 6, Name = "Raj2", Department = "IT", Salary = 25 });
            objColEmp.Add(new Employee { EmployeeID = 7, Name = "Raj3", Department = "IT", Salary = 8 });
           globalPVC = new PagedCollectionView(objColEmp);
           dgEmployee.ItemsSource = globalPVC;
        }

        //Populating ComboBox
        private void PopulateCombos()
        {
            comSort.Items.Add("----- Select a field name -----");
            comSort.Items.Add("Name");
            comSort.Items.Add("Department");
            comSort.Items.Add("Salary");
            comSort.SelectedIndex = 0;

            comGroup.Items.Add("-----Select a field name -----");
            comGroup.Items.Add("Name");
            comGroup.Items.Add("Department");
            comGroup.Items.Add("Salary");
            comGroup.SelectedIndex = 0;
        }

    }
}  

To top at all, I hope this basic introduction of Datagrid gave you a basic insight and hopefully you can use it to your advantage.

Happy coding.

Download: Source

Silverlight 4 – Webcam Support

Author: Sumon Barua.

 

Silverlight 4 is now not only more mature but also came with rich features. Most of these features were recommendations from Silverlight community.

Webcam support is one of them. This was a very highly requested feature and has now been included in this version.

 

The following steps will get you up and running for the initial adventure:

Steps:

Step 1: First step is to get all the available capture devices(webcams, microphones etc) or default capture device on the system. So CaptureDeviceConfiguration class help us to obtain information about all available devices. This helper class exposes a number of static members for this purpose.

               CaptureDeviceConfiguration.GetAvailableVideoCaptureDevices()

       It returns a collection of video devices on the system.

               CaptureDeviceConfiguration.GetAvailableAudioCaptureDevices()

       All the audio devices.

               CaptureDeviceConfiguration.GetDefaultAudioCaptureDevice()

       Default audio device.

               CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice()

       Default video device.

So after the first step we got the device

Step 2: Before any interaction with the device, Silverlight application needs permission from the user(The user must grant permission in the security prompt and that way it ensures the call is safe).

               CaptureDeviceConfiguration.RequestDeviceAccess() : – To request access, call this static method in response to user initiated event like listbox item selection, button click etc. If your application automate this call without user interaction (i.e. Load event)  the method will return false and further action by application will throw an InvalidOperationException.

Okay application got the permission. Lets proceed for the next step

Step 3: Now we have permission and device handy. It’s time for the application to interact with the device using CaptureSource class. This class allows you to collect the video feed from the camera. To make this happen  create a CaptureSource object and set the VideoCaptureDevice to the selected device. With the help of CaptureSource the application is now capable of performing the following task on the devices

·         Start                                     

·         Stop

·         State of the device.

·         Capturing single video frame

 

Step 4: Now create a video brush. A VideoBrush gives us the ability to paint any area or controls with video content. At this stage we use CaptureSource as a  source of our brush

Step 5: The next thing we need to do is to call CaptureSource.Start() method to begin capturing our live video.

Step 6: Finally we’ll set the Fill property of a Rectangle object to this brush.

 

Simple application:

Now we will code a very simple application

1. Create a Silverlight application and open the MainPage.xaml

2. Add one rectangle(for display purpose) and two buttons(start and stop).

    <Grid x:Name="LayoutRoot" Background="White">

        <StackPanel Name="mainStackpanel">

            <Rectangle Height="256" Name="myDisplay" Stroke="Black" StrokeThickness="1" Width="584" />

            <StackPanel Name="subStackpanel" Orientation="Horizontal" HorizontalAlignment="Center">

                <Button x:Name="butStart" Content="Start" Click="butStart_Click"/>

                <Button x:Name="butStop" Content="Stop" Click="butStop_Click" />

            </StackPanel>

        </StackPanel>

    </Grid>

 

3.Code behind as follows

  public partial class MainPage : UserControl

    {

        CaptureSource captureSourec;

 

        public MainPage()

        {

            InitializeComponent();

 

        }

 

        private void butStart_Click(object sender, RoutedEventArgs e)

        {

            //Get the default video device

            VideoCaptureDevice myWebcam = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();

           

            //Grant permission

            if (CaptureDeviceConfiguration.AllowedDeviceAccess ||

                                           CaptureDeviceConfiguration.RequestDeviceAccess())

            {

               

                captureSourec = new CaptureSource();

                captureSourec.VideoCaptureDevice  = myWebcam;

               

                //Create video brush that will get feed from captureSourec

                VideoBrush myBrush = new VideoBrush();

                myBrush.SetSource(captureSourec);

                myBrush.Stretch = Stretch.UniformToFill;

 

 

                //Stat the web cam

                captureSourec.Start();

 

                //Now display through the Rectangle

                myDisplay.Fill = myBrush;

 

 

            }

        }

 

 

        private void butStop_Click(object sender, RoutedEventArgs e)

        {

            if (captureSourec != null)

            {

                captureSourec.Stop();

            }

        }

    }