Kunal-Chowdhury.com - Microsoft Technology Blog for developers and consumers: November 2009

In this post I will describe you another feature of Silverlight 4 “Access to external content”. Here I will show how to drag and drop some external images to my sample application. Earlier Silverlight 4 this feature was not available. There was no client file access permission. But in this new release they introduced this functionality by which you can implement the same.

To implement this feature you must need Silverlight 4, which is now available in Beta 1 version. You need Visual Studio 2010 Beta 2 which you can download freely from Microsoft site.

Now if your dev environment is ready then we can go further to implement the same. Excited so much to do it? Create a Silverlight project which will create “MainPage.xaml” for you. Inside the MainPage.xaml add a ScrollViewer containing a WrapPanel. Your ScrollViewer will have a fixed Height & Width where as your WrapPanel will be free size. This ensures that, if more components are added inside the WrapPanel it will automatically add a scrollbar to it. So, you can scroll through the child components. In this example I want to drop some external image files inside this panel. So, I will set the WrapPanel “AllowDrop” property to true. This will make the panel droppable.

On the Drop event handler of the wrap panel you will get the dropped files as data to the DropEventArgs which has an array of FileInfo. DataFormats.FileDrop sets the droppable permission to the panel.

FileInfo[] droppedFiles = e.Data.GetData(DataFormats.FileDrop) as FileInfo[];
Now for each dropped file you can check whether it is a supported image file. If so, proceed further to add it to the wrap panel. See the sample code:
void imageContainer_Drop(object sender, DragEventArgs e)
    FileInfo[] droppedFiles = e.Data.GetData(DataFormats.FileDrop) as FileInfo[];

    foreach (FileInfo droppedFile in droppedFiles)
        if (IsSupportedImageFile(droppedFile.Extension))
            Border imagePlaceHolder = new Border()
                Child = CreateImage(droppedFile),
                Background = transparentColor,
                Margin = new Thickness(10.0),
                Cursor = Cursors.Hand,
            ToolTipService.SetToolTip(imagePlaceHolder, droppedFile.Name);

            imagePlaceHolder.MouseEnter += imagePlaceHolder_MouseEnter;
            imagePlaceHolder.MouseLeave += imagePlaceHolder_MouseLeave;

Here IsSupportedImageFile() method takes the extension of the dropped file as a parameter which will check whether it is a valid image format. I used .jpg & .png for the demonstration which actually uses switch case. The CreateImage() method creates an object of the image from the FileStream of the dropped file.
private Image CreateImage(FileInfo droppedFile)
    using (FileStream fileStream = droppedFile.OpenRead())
        BitmapImage bitmapImage = new BitmapImage();

        return new Image() { Source = bitmapImage, Width = 100, Margin = new Thickness(5.0) };

Now after writing this code, your application will be ready to get external file droppable inside it. Run your application & drop some jpg/png files from your image directory to your browser i.e. Silverlight application. You will see that the dropped images are automatically added inside your panel. This is a good example of accessing external files droppable inside your web application. Download the sample solution & implement what you want to do.

So what next? I think from the above example you will get the idea of what we can achieve from this. Anyway you can implement file upload utility by just dragging & dropping inside the web application just like Skydrive. You can also drop text files to read the file instead of browsing & uploading to the server. And more… Go ahead & enjoy programming with Silverlight 4.

Download Sample Application:   Silverlight 4 Drag-N-Drop External Image

Published by on under .Net |

Silverlight 4 has now support for Mouse Wheel. From now onwards you can use mouse wheel event to trigger on mouse wheel rotation. Until the release of Silverlight 4 Beta 1 you had to write JavaScript code & a huge lines of code in C#. Now just forget about those lines. Your code will be clean.

If you want to use the clean coding for mouse wheel, you have to just register & implement the said event in your code. Apart from the MouseLeftButtonDown / MouseLeftButtonUp / MouseRightButtonDown / MouseRightButtonUp / MouseEnter / MouseLeave events there you will find another event called MouseWheel. This event is responsible for clean up your code to implement the feature. You can also override the OnMouseWheel event in your main control.

See the below code:

protected override void OnMouseWheel(MouseWheelEventArgs e)

    txbMouseWheelValue.Text = string.Format("Mouse Wheel Value: {0}", e.Delta);

    if (e.Delta > 0)
        rotateBrdWheeler.Angle += 10;
        rotateBrdWheeler.Angle -= 10;

Here when the mouse wheel event is registered, it will set e.Delta as the output of mouse wheel rotation. You can check whether the value is positive / negative & depending on that you can decide your own logic. In the demo app I am rotating a Rectangle by 10 degree depending on the sign of delta. You can do your own logic there.

It’s so easy. So, go ahead & clean your code (only supports in Silverlight 4). Enjoy the new feature. Cheers…  :)

Download Sample Application:   Silverlight 4 Mouse Wheel Demo Solution

Published by on under .Net |

In my previous posts I discussed about “How to work with Notification API?” & “How to Capture Video from Default Webcam?”. In this post I will describe about the another cool new feature (“How to use the all new Right Click Context Menu?”) of Silverlight 4.

Silverlight 4 has now support for right click. You can now register the event “MouseRightButtonDown” & “MouseRightButtonUp” to any FrameworkElement. Hence, no need to use JavaScript to disable the right click option. If you want to disable the right click option then just implement those events with:

e.Handled = true;

Now if you want to implement a Context Menu on right click, create the Popup Context menu & position it to proper location. The following code will create the context menu:

private Popup CreateContextMenu(Point currentMousePosition)
    Popup popup = new Popup();
    Grid popupGrid = new Grid();
    Canvas popupCanvas = new Canvas();

    popup.Child = popupGrid;
    popupCanvas.MouseLeftButtonDown += (sender, e) => { HidePopup(); };
    popupCanvas.MouseRightButtonDown += (sender, e) => { e.Handled = true; HidePopup(); };
    popupCanvas.Background = new SolidColorBrush(Colors.Transparent);

    popupGrid.Width = Application.Current.Host.Content.ActualWidth;
    popupGrid.Height = Application.Current.Host.Content.ActualHeight;
    popupCanvas.Width = popupGrid.Width;
    popupCanvas.Height = popupGrid.Height;

    return popup;
CreateContextMenuItems() will add some context menu items, on click it will show which menu item has been cllicked by you. Upto this I only talked about the creation of the customized context menu. Now we have to show it on right click inside the Silverlight application. In my example, I added a Border control which has the right click event registered. Now check the below implemented code which will be responsible for showing the context menu:
void brdRightClickZone_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
    txbMessage.Text = "Right Clicked";
    Point currentMousePosition = e.GetPosition(LayoutRoot);

private void btnRightClick_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
    e.Handled = true;

On right mouse down, I am setting the e.Handled = true. This ensures that, this will not show up the default Silverlight context menu & the right mouse up implementation will popup the customized context menu at the current mouse position.

What next? Download the sample application created by me & implement your own logic to create the customized context menu which will open on right click on your silverlight application.

Download Sample Application:  Silverlight 4 Right Click Context Menu Demo

Published by on under .Net |

Silverlight Notification API is a new feature introduced in Silverlight 4 Beta 1. If you are developing your application using Silverlight & want to show some notification message like Outlook to the user, then you can use this. Remember that, this feature only works out of browser.

To develop Silverlight 4 application you must need Visual Studio 2010 Beta 2 which you can download from the Microsoft site. If you are using Visual Studio 2008 then you can install Visual Studio 2010 side by side too. After you installed the studio, just go with the installation of the “Silverlight 4 Tools for Visual Studio 2010”.

After you setup your development environment create a new Silverlight 4 application using Visual Studio 2010. This will automatically create a page “MainPage.xaml” for you. Add two buttons in your XAML. One is to install the Silverlight application as out of browser & another is to show the notification.

<Button x:Name="btnInstall" Width="150" Height="20" Content="Install OOB" Margin="5"/>
<Button x:Name="btnShowNotification" Width="150" Height="20" Content="Show Notification" Margin="5"/>

For implementing the Silverlight out of browser feature follow my earlier post: “How can you implement Silverlight 3 Out-Of-Browser feature?” Now go to the code behind file “MainPage.xaml.cs” & implement the click event for those. On page load, if it is running out of browser then create the notification window instance:

// Initialize a new instance of Notification Window
notificationWindow = new NotificationWindow();
notificationWindow.Height = 50.0;
notificationWindow.Width = 300.0;
Create your custom notification panel either using XAML or code behind. You can go for a nice looking UserControl. Here for example I will use a TextBlock inside a Border to show a simple message.
Border border = new Border()
    Background = new SolidColorBrush(Colors.Gray),
    Height = notificationWindow.Height,
    Width = notificationWindow.Width,
    Child = new TextBlock()
        Text = "This is a Custom Notification from Silverlight 4",
        Foreground = new SolidColorBrush(Colors.White)
Now, on “Show Notification” button click event check for whether it is running out of browser. If so, assign the notification panel you created to the content of the notification window instance & call the show method of the notification window. Here you have to pass the duration of the visibility of the notification in milliseconds.
notificationWindow.Content = border; // add the custom notification panel
notificationWindow.Show(2000); // show the notification
Now run your application & click on the “Install OOB” button. This will install the Silverlight application and open the desktop version of it. Click the “Show Notification” button to show the notification at the right bottom corner of your desktop.

Download Sample Solution:   Silverlight 4 Notification API Demo

Published by on under .Net |

Silverlight 4 Beta 1 has been released by Microsoft on 18th November 2009. There are lots of goodies came up with the release of the new version. Among them, most of all are requested by the developers & users of Silverlight. In this post I will demonstrate one of the new feature “Accessing Default Webcam using Silverlight 4”.

To create a Silverlight 4 application you need “Visual Studio 2010 Beta 2”. Download it from the Microsoft site. Then install the “Silverlight Tools 4 for Visual Studio 2010 Beta 2”. After successful installation, create a Silverlight 4 Application project.

Once you done with the project creation, Visual Studio will open the MainPage.xaml for you. Add a Rectangle & three Buttons inside the Grid. The Rectangle will responsible for the Video output from your VideoCaptureDevice & buttons will be responsible for the interaction with the device. After adding the same your XAML will look like this:

   <Grid x:Name="LayoutRoot" Background="White">
        <StackPanel HorizontalAlignment="Center">
            <Rectangle x:Name="rectWebCamView" Width="500" Height="400"/>
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
                <Button x:Name="btnCaptureDevice" Content="Capture Device" Margin="5"/>
                <Button x:Name="btnPlayCapture" Content="Start Capture" Margin="5"/>
                <Button x:Name="btnStopCapture" Content="Stop Capture" Margin="5"/>

Now, go to the code behind file (MainPage.xaml.cs) & create an instance of CaptureSource. Then call TryCaptureDevice() to initiate the Video Capture. This first get the default Video Capture device & assign it to the VideoBrush instance of the rectangle. Remember that, this will ask the user to grant permission to the user device & upon successful only it will start the device.

        private void TryCaptureDevice()
            // Get the default video capture device
            VideoCaptureDevice videoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();

            if (videoCaptureDevice == null)
                // Default video capture device is not setup
                btnPlayCapture.IsEnabled = false;
                btnStopCapture.IsEnabled = false;
                btnCaptureDevice.IsEnabled = true;

                MessageBox.Show("You don't have any default capture device");
                btnPlayCapture.IsEnabled = false;
                btnStopCapture.IsEnabled = false;

                // Set the Capture Source to the VideoBrush of the rectangle
                VideoBrush videoBrush = new VideoBrush();
                rectWebCamView.Fill = videoBrush;

                // Check if the Silverlight has already access to the device or grant access from the user
                if (CaptureDeviceConfiguration.AllowedDeviceAccess || CaptureDeviceConfiguration.RequestDeviceAccess())
                    btnPlayCapture.IsEnabled = true;
                    btnStopCapture.IsEnabled = false;
                    btnCaptureDevice.IsEnabled = false;

Download Sample Solution:   Silverlight 4 Webcam Demo

Published by on under .Net |

Microsoft released the first beta version of Silverlight 4 on 18th November 2009 at PDC in Los Angels. This version has been released for the developers only to have a look on what they are actually featuring on Silverlight 4 final release. As it’s not a Go-Live version hence you can’t develop commercial application using it. The Silverlight 4 runtime is not available for the end user till now.

Silverlight 4 Beta 1 comes up with a lot of powerful capabilities as already requested by the developers. Microsoft shipped it with almost 90% of requested features. You can see the list of new features in “What's new in Silverlight 4?

To develop Silverlight 4 application you will need Visual Studio 2010 beta 2 which you can download it from “Get Tools” section. All necessary links are available on that page. Microsoft also released the new Expression Blend & the new Silverlight Toolkit for Silverlight 4 Beta 1. You can download them from the same location.

Have a look into Tim Heuer's Blog for more details.

Published by on under News |
© 2008-2018 Kunal-Chowdhury.com - Microsoft Technology Blog for developers and consumers | Designed by Kunal Chowdhury
Back to top