While surfing thru different forum I noticed that, lots of people are actually facing issues while trying to implement the drag and drop feature. The main problem arises while trying to drag from a ListBox to a panel like canvas. In this post, I will go thru the steps to demonstrate such feature.

Here I will use Telerik control to give out the demonstration. You can download the trial version of the dlls from Telerik Silverlight Control Page. I have implemented the demo using Silverlight 4 Beta 1. The same thing is also possible in earlier version of Silverlight. You can download Silverlight SDK from Silverlight Site. To develop apps in Silverlight 4 you must need Visual Studio 2010 Beta 2 which you can download from Microsoft site.

So, lets go for implementing the same. Create a Silverlight project. Lets create a ListBox and a Canvas inside the LayoutRoot:

<Grid x:Name="LayoutRoot" Background="White">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="150"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <ListBox x:Name="lstBox" Margin="10" Grid.Column="0"/>
    <Canvas x:Name="cnvDropBox" Background="Yellow" Margin="10" Grid.Column="1"/>
</Grid>
Now in the code behind, we have to register the Drag and Drop events for the ListBox & Canvas. Use RadDragAndDropManager class to register the same. 
RadDragAndDropManager.AddDragInfoHandler(lstBox, OnDragInfo);
RadDragAndDropManager.AddDragQueryHandler(lstBox, OnDragQuery);
RadDragAndDropManager.AddDropInfoHandler(cnvDropBox, OnDropInfo);
RadDragAndDropManager.AddDropQueryHandler(cnvDropBox, OnDropQuery);

RadDragAndDropManager.SetAllowDrop(cnvDropBox, true);
The implementation of the events will be as below:
private void OnDragQuery(object sender, DragDropQueryEventArgs e)
{
    if (e.Options.Status == DragStatus.DragQuery)
    {
        var draggedListBoxItem = e.Options.Source as Image;
        e.Options.DragCue = draggedListBoxItem.Source;
        e.Options.Payload = draggedListBoxItem.Source;
    }

    e.QueryResult = true;
    e.Handled = true;
}
private void OnDragInfo(object sender, DragDropEventArgs e)
{
    if (e.Options.Status == DragStatus.DragComplete)
    {
        // comment this block if you are going to clone
        lstBox.Items.Remove(e.Options.Source);
    }
}
private void OnDropInfo(object sender, DragDropEventArgs e)
{
    var droppablePanel = e.Options.Destination;

    if (e.Options.Status == DragStatus.DropComplete && droppablePanel is Canvas)
    {
        FrameworkElement dragableControl = null;
        Point desiredPosition = new Point();
        Point currentDragPoint = e.Options.CurrentDragPoint;
        Point canvasPosition = cnvDropBox.TransformToVisual(null).Transform(new Point());

        if (e.Options.Source is Image)
        {
            // create the new instance & update the necessary properties
            // this step is require if you are going to make a clone
            Image tempDragableControl = e.Options.Source as Image;
            dragableControl = new Image() { Source = tempDragableControl.Source };
            cnvDropBox.Children.Add(dragableControl);
        }

        desiredPosition.X = currentDragPoint.X - canvasPosition.X;
        desiredPosition.Y = currentDragPoint.Y - canvasPosition.Y;
        dragableControl.SetValue(Canvas.LeftProperty, desiredPosition.X);
        dragableControl.SetValue(Canvas.TopProperty, desiredPosition.Y);
    }
}
private void OnDropQuery(object sender, DragDropQueryEventArgs e)
{
    var droppablePanel = e.Options.Destination;

    if (e.Options.Status == DragStatus.DropDestinationQuery && droppablePanel is Canvas)
    {
        e.QueryResult = true;
        e.Handled = true;
    }
}

As I am using Image inside the ListBoxItem, hence OnDragQuery I am setting the Source as an Image to the DragCue & PayLoad properties. OnDragInfo I am removing item from the ListBox. If you don’t want to remove the dragged image from the ListBox then just remove that line. OnDropInfo I am just placing the Image to the appropriate position which we will get as CurrentDragPoint in the DragDropEventArgs.

This is a sample demonstration. So, you have to explore it more to fulfil your requirement.

Download Sample Application:  Drag And Drop ListBoxItem to Canvas Demo

Published by on under .Net | Silverlight

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;

            imageContainer.Children.Add(imagePlaceHolder);
        }
    }
}
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();
        bitmapImage.SetSource(fileStream);

        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

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)
{
    base.OnMouseWheel(e);

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

    if (e.Delta > 0)
        rotateBrdWheeler.Angle += 10;
    else
        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 | Silverlight

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.Children.Add(popupCanvas);
    popupGrid.Children.Add(CreateContextMenuItems(currentMousePosition));

    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);
    ShowPopup(currentMousePosition);
}

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

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

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"/>
            </StackPanel>
        </StackPanel>
    </Grid>

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");
            }
            else
            {
                btnPlayCapture.IsEnabled = false;
                btnStopCapture.IsEnabled = false;

                // Set the Capture Source to the VideoBrush of the rectangle
                VideoBrush videoBrush = new VideoBrush();
                videoBrush.SetSource(captureSource);
                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 | Silverlight

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 | Silverlight

Silverlight 3 came up with Out Of Browser support. Using that feature one can install the application just like a standalone windows application. Hence no need to open the browser to run the Silverlight application. Today for the first time I gone thru the APIs & created a sample application. Here I will discuss about the same to give you a demonstration. It is quite easy to implement.

Create a Silverlight application using Visual Studio 2008. This will automatically create “MainPage.xaml”. Now open the MainPage.xaml & add the following lines inside the LayoutRoot Grid:

<StackPanel Margin="20" HorizontalAlignment="Center">
<
TextBlock Text="Silverlight Out Of Browser Demo Application"
FontSize="20" HorizontalAlignment="Center"/>
<
Button x:Name="btnInstall" Content="Install as Out Of Browser Application"
Width="300" Height="20" Margin="20"/>
</StackPanel>

Read the Complete Article @ DotNetFunda.com

Published by on under .Net | Silverlight

Microsoft released their all new Operating System as expected. From now onwards it is available for the general public i.e. you can purchase a new PC/Laptop with Windows 7 preloaded. Not only this, those who recently purchased PC/Laptop with Windows Vista they are able to upgrade to Windows 7 free of charge. So, grab your copy now & enjoy the real experience with Windows 7.

For last couple of months I am using the trial edition of Windows 7. According to me, it is a great operating system Microsoft had ever launched with lots of goodies. My special thanks to Microsoft & Windows 7 team for their excellent work.

No doubt this is really a great Microsoft Operating System with a huge performance boost, a great UI, new taskbar & multi-touch function. Here are the list of things I liked more in Windows 7:

  • A great new Graphical User Interface
  • The all new Taskbar & Taskbar thumbnails panel
  • The new Taskbar Jump List
  • A huge performance boost than the earlier operating systems
  • Multi-touch capability
  • The latest User Account Control, which is now a great experience rather than Vista
  • Scheduled Desktop Wallpaper changer & Theme support
  • New kernel dumping methods which actually improved the performance
  • The new control panel, device manager & user libraries
  • And more…

It’s definitely a great ERA in the computing world.

Published by on under News | Windows7