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

It’s a great day in the Microsoft era. They are going to launch the official release of Windows 7 today. From now onwards, this will be available to purchase all over the world.

You can view the Windows 7 Launch celebration here directly from New York city, which will be hosted by Steve Ballmer. This will start at 8 AM (Pacific) / 11 AM (Eastern).

Published by on under News | Windows7

Microsoft has just released it’s October 2009 release of Silverlight 3 Toolkit. You can download it from: Silverlight 3 Toolkit October 2009 Installer. Also have a look into the sample application at: Silverlight 3 Toolkit Sample Application

Silverlight 3 Toolkit has now full design time supports for Visual Studio 2010. Charting tool has been changed. They now introduced ISeries interface as the base interface for all the Series & StylePalette now renamed to Palette. So, those who are using StylePalette just make those changes in your code. You can now customize the LegendItem very easily. Silverlight team now added the support to Themes for Accordion, DataForm, DataPager, GridSplitter & ChildWindow. Added support for Drag & Drop functionality for some common items like ListBox, TreeView, DataGrid and Charting tools. Moreover the mousewheel support has been now added to navigate the GlobalCalendar & TimePicker controls.

Have a look into those latest features of Silverlight 3 Toolkit. In real scenarios those are really very awesome features. Though it is their 5th release of Silverlight Toolkit, hope they will come up with lots of required controls in the future versions.

Published by on under .Net | News

In my last post Windows 7 Multitouch Application Development (Part - I), I described about how to handle multitouch image manipulation in Windows 7 which gives a very basic idea on the multitouch development. That code uses multitouch manipulation for the entire screen. If there are multiple images in the screen this will raise event for all.

image In this post, I will show you how to manage multitouch events for all the images separately. See one of such kind of image manipulation demo here.

For this we have to assign a unique touch-id for each finger on the screen. As long as the finger touches the screen the associated touch-id will remain same for that particular finger. If the user releases his finger the system will release the touch-id & that can be again assign by the system automatically on next touch. So, how can we get the touch-id? You can get the same from the StylusEventArgs (i.e. args.StylusDevice.Id). The stylus device will automatically generate this ID for each touch, only thing is you have to assign it with the respective finger touch.

First of all, we will create an UserControl which will consist of a single Image & XAML code for it’s RenderTransform. The same thing we did in the previous post which was inside the Window, but here it will be inside the UserControl (Picture class). Create a DependencyProperty to assign the ImageLocation dynamically.

<UserControl x:Class="Windows7MultitouchDemo.Picture"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Image Source="{Binding Path=ImageLocation}" Stretch="Fill" Width="Auto"
           Height="Auto"  RenderTransformOrigin="0.5, 0.5">
        <Image.RenderTransform>
            <TransformGroup>
                <RotateTransform x:Name="trRotate"/>
                <ScaleTransform x:Name="trScale"/>
                <TranslateTransform x:Name="trTranslate"/>
            </TransformGroup>
        </Image.RenderTransform>
    </Image>
</UserControl>

To track the multi-touch simultaneously for the above “Picture” usercontrol, you can use the PictureTracker class which comes with the Windows 7 Training Kit. You can download it from Microsoft Site. It looks similar to this:

/// <summary>
/// Track a single picture
/// </summary>
public class PictureTracker
{
       private Point _prevLocation;
       public Picture Picture { get; set; }
       public void ProcessDown(Point location)
       {
           _prevLocation = location;
       }
       public void ProcessMove(Point location)
       {
           Picture.X += location.X - _prevLocation.X;
           Picture.Y += location.Y - _prevLocation.Y;
           _prevLocation = location;
       }
       public void ProcessUp(Point location)
       {
           //Do Nothing, We might have another touch-id that is
           //still down
       }
}

Now, we have to store all the active touch-ids associated with the PictureTracker class. So, we will use a dictionary for that. We will use the same PictureTrackerManager class which again comes with the Windows 7 Training Kit.

private readonly Dictionary<int, PictureTracker> _pictureTrackerMap;
Create an instance of the PictureTrackerManager class inside your Window1.xaml.cs & register the stylus events with the PictureTrackerManager events. So now whenever a touch occurs on the Picture, the PictureTrackerManager will first find the associated touch-id for the respective instance and raise event to process the same.
//Register for stylus (touch) events
StylusDown += _pictureTrackerManager.ProcessDown;
StylusUp += _pictureTrackerManager.ProcessUp;
StylusMove += _pictureTrackerManager.ProcessMove;
Reference:  Windows 7 Training Kit
Download Sample Application

Published by on under .Net | Tips
Microsoft is going to launch the new Windows 7 operating system in October 2009. Currently the RC version is available online. As you know, Windows 7 came up with lots of goodies including better resource management, better performance, jumplist management, multitouch functionality & many more. Here I will discuss on developing a simple multitouch application using .Net 3.5 SP1.

Before doing anything you have to download the Windows 7 Multitouch API. You can download it from here. Extract the downloaded zip file to your local hard drive. Be sure that, you are using Windows 7 & you have a multitouch enabled screen to test it out.

Create a WPF application using Visual Studio 2008. This will automatically add a XAML file named Window1.xaml for you. Now add an image to your solution directory & insert it in the XAML. Now your Window1.xaml will look something like this:

<Grid>
    <Image Source="images/Hydrangeas.jpg"/>
</Grid>
Add RenderTransform to the image so that, we can scale or rotate the image properly. This will produce XAML similar to this:
<Grid>
    <Image Source="images/Hydrangeas.jpg" RenderTransformOrigin="0.5,0.5" Width="400">
        <Image.RenderTransform>
            <TransformGroup>
                <ScaleTransform x:Name="trScale" ScaleX="1" ScaleY="1"/>
                <RotateTransform x:Name="trRotate" Angle="0"/>
                <TranslateTransform x:Name="trTranslate" X="0" Y="0"/>
                <SkewTransform AngleX="0" AngleY="0"/>
            </TransformGroup>
        </Image.RenderTransform>
    </Image>
</Grid>
Use proper names when you are adding different types of transform to the transform group. It will be easier for you to handle it from the code behind file. Run your application. This will open up your Window with an image inside it. If you want to drag or rotate the image this will not work because we haven’t integrated the functionality yet. Add two project references i.e. “Windows7.Multitouch” & “Windows7.Multitouch.WPF” from the extracted zip folder to your solution. These are the managed API codes for multitouch application development. Go to your Window1.xaml.cs & be sure that following namespaces are already included. You may have to add some of them.
using System; 
using System.Windows; 
using Windows7.Multitouch; 
using Windows7.Multitouch.Manipulation; 
using Windows7.Multitouch.WPF; 
Create two private members inside your partial class:
// object of a .Net Wrapper class for processing multitouch manipulation 
private ManipulationProcessor manipulationProcessor = new ManipulationProcessor(ProcessorManipulations.ALL);

// boolean value to check whether you have a multitouch enabled screen 
private static bool IsMultitouchEnabled = TouchHandler.DigitizerCapabilities.IsMultiTouchReady;
Now inside the Window Loaded event write the following lines of code:
// check to see whether multitouch is enabled 
if (IsMultitouchEnabled) 
{ 
    // enables stylus events for processor manipulation 
    Factory.EnableStylusEvents(this); 

    // add the stylus events 
    StylusDown += (s, e) => 
    { 
        manipulationProcessor.ProcessDown((uint)e.StylusDevice.Id, e.GetPosition(this).ToDrawingPointF()); 
    }; 
    StylusUp += (s, e) => 
    { 
        manipulationProcessor.ProcessUp((uint)e.StylusDevice.Id, e.GetPosition(this).ToDrawingPointF()); 
    }; 
    StylusMove += (s, e) => 
    { 
        manipulationProcessor.ProcessMove((uint)e.StylusDevice.Id, e.GetPosition(this).ToDrawingPointF()); 
    }; 

    // register the ManipulationDelta event with the manipulation processor 
    manipulationProcessor.ManipulationDelta += ProcessManipulationDelta; 

    // set the rotation angle for single finger manipulation 
    manipulationProcessor.PivotRadius = 2; 
}
Write your logic inside the manipulation event handler implementation block. Here I will do rotation, scaling & positioning of the image. Here is my code:
private void ProcessManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
    trTranslate.X += e.TranslationDelta.Width;
    trTranslate.Y += e.TranslationDelta.Height;

    trRotate.Angle += e.RotationDelta * 180 / Math.PI;

    trScale.ScaleX *= e.ScaleDelta;
    trScale.ScaleY *= e.ScaleDelta;
}
From the ManipulationDeltaEventArgs you can get various values & depending upon them you can implement your functionality in this block. TranslateTransform will position the image, RotateTransform will do the rotation & the ScaleTransform will resize the image. Run your project to test your first multitouch application.
Download Sample Application
Published by on under .Net | Tips
While working in Windows you have seen that, while focusing on any TextBox the entire text inside it has been selected. This is a default behaviour of Windows, but in WPF this behaviour is not present. For this you have to write code.

If you want to add the same behaviour in your WPF application then you have to register the TextBox.GotFocus event for each textbox inside your Window and in that event implementation you have to write the code to select all the text inside the focused TextBox, right? If you do like this, then you have to write so many event registration for each one of the TextBox.

 

 

Lets say, you have a single Window with 100 TextBoxs in it. In this case though you can write the event definition inside a single implementation but you have to register the event for 100 times. Now imagine the same behaviour for 10 Windows inside the same application. Here you have to write the event implementation for each and every Window & register the event for each TextBox. This will definately clutter your code.

So, how can you get the said behaviour in your WPF application? It is a simple trick inside your App.xaml.cs file. This will be a global event handler for any TextBox in your application. If you open your App.xaml.cs you will find a overridable method named "OnStartUp". Inside this register the TextBox.GotFocus event for every TextBox before calling the OnStartup method for the base class. After doing this trick, your OnStartup method will look like this:

 

 

protected override void OnStartup(StartupEventArgs e)
{
    EventManager.RegisterClassHandler(typeof(TextBox), TextBox.GotFocusEvent, new RoutedEventHandler(TextBox_GotFocus));
    base.OnStartup(e);
}

Here, the EventManager class will be responsible to register the event handler for all TextBox. So simple right? Now add the event handler implementation for the TextBox in the same class. This will look like this:
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
    TextBox tb = sender as TextBox;
    tb.Focus();
    tb.SelectAll();
}  
             
Now run your application with multiple Windows having multiple TextBox on them. Focus on any TextBox having some texts inside it. You will see the same behaviour has been added to all of your TextBox.
Published by on under Tips | WPF
MoXAML is an AddIn for Visual Studio to make your coding more productive for WPF and Silverlight Applications. By using this great power toy, you can code without giving more efforts. It has lots of features like beautifying the XAML code, Keyword Lookup, better comment support for XAML, automated Dependency Property creation and more.

You can also explore the features of XAML Power Toys. This will give you a extended power to design your XAML. This is really a good AddIn not only for the designers but also for the developers. You can create your ViewModel class, create ListView or Form for selected class, extract properties to style, option to generate x:Name for controls, grouping controls inside GroupBox and lots of other goodies. Check out the site for the latest features.

Mole is a tool that integrates with Visual Studio which lets you inspect the Visual Tree of your application, view and edit properties or data, view the XAML for selected elements and more. It allows unlimited drilling to objects and sub objects.

Snoop is a tool which you can use to hook to your running WPF application and browse the Visual Tree of the application. You can also inspect and edit the properties, inspect routed events and magnify sections in the UI and also debug binding errors.

Crack.Net is a runtime debugging tool for .Net desktop applications (both WPF & WinForms) just like Mole & Snoop. It allows you to go thru the managed heap of another .Net application, view all kinds of values on different objects and also manipulate them easily. You can also read the Crack.Net article.
Published by on under .Net | Silverlight
Microsoft released Silverlight 3 on 10th July 2009 as per the schedule. You can download the SDK, Visual Studio Tools & Blend from the following location:
Silverlight 3 came with the following features:
  • Out of Browser support
  • Network status check
  • Pixel Shader Effects
  • Bitmap APIs
  • Runtime themeing support
  • Enhanced control skinning
  • Support for System Colors
  • Bitmap Caching
  • Perspective 3D view
  • GPU hardware acceleration
  • Text animation
  • H.264 support
  • RAW audio/video support
  • Save File Dialogue
  • Wrap Panel, View Box, Dock Panel
  • Support for local fonts
  • Binary XML
  • Component caching & Scene caching
Published by on under .Net | Silverlight
Azure service platform is a cloud computing platform hosted in Microsoft data centers. This provides operating system & different set of development service which the developers can use to build their own web applications or enhance them directly in that platform. Without purchasing any upfront technology, developers can create their applications more quickly & easily in the cloud. They only need working knowledge in .Net Framework & Visual Studio Environment. Azure service currently supports native languages. In future it will support many more including Microsoft & Non-Microsoft languages. Once the coding is done, the developer can build & host the application in the cloud, so that end user will be able to run it over the internet.
Azure platform consists of Windows Azure, which is an Operating System to provide on demand computing, storage and management of cloud applications. In short, Windows Azure is an Operating System for the cloud computing platform designed for utility computing. It provides facilities to write, host or manage applications & store data on demand. The service layer consists of different services like: Live Service, .Net Service, SQL Service etc. which provides building blocks within the platform for the developers.
image
Published by on under Web |

Cloud computing is a dynamic style of computing in which virtualized resources are provided as a service over the internet. The users of cloud computing need not to worry about the capital expenditure and maintenance cost of hardware and software resources. They have to pay only what they are using. This can be of two types. User can either pay the provider based on the resources consumed during the time period or a time based subscription.

Published by on under Web |

Microsoft launched their new search engine named Bing (Kumo) on 28th May in Europe which went fully online on 3rd June. This search engine was designed to help people not only to quickly find anything over the internet but also to plan a trip or make a purchase decision. Using "Bing" the end user can find any information they need on their daily basis to accomplish their tasks. Bing categories results in different category, based on which the user can find relevant results more accurately.

imageimage

image image

You can find some Tips & Tricks on Bing.com at: http://www.labnol.org/internet/bing-tips/8931/

Published by on under News |

Google Wave is a project announced by Google on 28th May 2009 at the Google I/O conference is expected to release later in 2009. This will be a next generation email subsystem designed to merge email, instant messaging, social networking & wiki featuring strong spelling/grammar checking & automated translation between nearly about 40 different languages.

The term "Waves" described by Google as "equal parts conversation and document", means any authorized participant can reply anywhere in the conversation, they can edit or can add more participants during the conversation process. All the participants will be notified of changes or replies in all the waves they are actively participating & all the modifications will be seen at real time, letter by letter. Not only this, multiple participants may edit a single wave simultaneously in the same context.

imageThis ability of Google Wave will let user to create collaborative documents modified in different location with full modification history, which can be searched by an user to view/modify any changes just like wikis.

More information about this is available in Google Wave Site.

Published by on under News |

Microsoft has recently launched Visual Studio 2010 and .Net 4.0 Beta 1 with more expressive features. Some of them are mentioned below:

[New Language Support]
Visual F# is a new programming language which actually combines functional & object oriented programming to provide scalable language for .Net.

[Test Driven Development]
Visual Studio 2010 now offers greater support for test driven development where tests can be written before the actual code as an approach to the software design.

[Multi Targeting]
By using the multi targeting feature you can also create application of earlier version in new IDE of visual studio.

[Parallel Processing]
Using the new parallel extension of .Net 4.0 developers can create application which will scale efficiently as the number of cores & processors increase.

[Security]
The new framework improvements & expanded capabilities in the security model by simplifying the security policy. Now runtime support has been removed for enforcing the Deny, RequestMinimum, RequestOptional, and RequestRefuse permission requests.

[Performance]
.Net framework 4.0 beta 1 now provides improvement in the startup time and faster performance for multi threaded applications.

[Lazy Initialization]
By using this feature, the memory for an object is not allocated until it is needed. This improves the performance by spreading the object allocation across the lifetime of the application.

[In-Process Execution]
This enables an application to load & activate multiple version of the CLR inside the same process. Now you can run applications those are based on the .Net 2.0 & .Net 4.0 inside the same process.

[Profiler]
In the new framework you can now attach, run and detach profiling tasks at any point of time.

[Garbage Collection]
.Net Framework 4.0 now supports background garbage collection. In earlier frameworks it was a concurrent garbage collection.

[Collection & Data Structure]
- The new framework now includes BigInteger which supports all the standard numeric operation including the bit operation.
- It now supports self balancing SortedSet tree which sorts automatically after insert/delete operation.
- A new data structure named Tuple has been introduced in this framework which can hold an ordered set of heterogeneous items.

[Exception Handling]
The new CLR can now handle any exception regarding the corrupted state of the underlying operating system.

and more…

Published by on under .Net |

Recently, I was facing performance issue while working with huge data. I need to bind those data inside a panel as Custom User Control & want to change the properties multiple times in a second. When I used less no's of data it was working fine, but, when I tried with more no of data, my application starts crying. It was a real pain to the application to start while loading those records & unfortunately I didn’t get any solution to that.

After doing a lot of analysis with VirtualizingStackPanel concept that I shared in my previous post “What is Virtualizing StackPanel?” didn’t solve my problem which I was facing due to huge no of data.

Later, I found a very good post (“WPF: Adventures in Virtualization by Mike Taulty”) shared by Dr. WPF on implementing custom Virtual Panel, which actually resolved my problem.

Here you will find some very good articles on step-by-step implementation of Virtual Panel:

Those are very nice articles to implement the custom virtual panel step-by-step & after implementation of this panel, I noticed a huge performance improvement in my application. This really helped me while working with a huge records.

Now, come to the basic concept of this virtual panel. What it actually does. It loads all the records in a different thread & populate them in the UI as much as records that can be viewable in the screen. While scrolling, it actually creates new object of the elements by virtualizing the existing elements. So, only those objects will be in the memory which are available in the screen. The rest will go for a cleanup process. Hence, improving the performance more & more…. depending on the visible UI elements.

See a nice example in this location: http://blogs.msdn.com/jgoldb/attachment/8116217.ashx

Published by on under .Net | Tips

Virtualizing StackPanel generates container items when needed & throws them from memory when they are no longer in the view. When the panel has huge number of items, at that time there is no need to keep the extra items in memory which are not in view. This solves the memory problem.

If you are populating a huge number of items in any panel, then it is a better idea to use the Virtualization. But, due to throwing away of the extra items & recreating them when in view, costs some extra processing power when the Virtualizing StackPanel uses the default Standard Mode. To solve this issue, just change the virtualization mode to "Recycling". This is called as Container Recycling, which introduced in .Net 3.5 SP1 as a new feature.

By default, this recycling mode is turned off. To enable the container recycling, first turn on the Virtualizing StackPanel with “VirtualizationModeProperty” as “Recycling”.

<WrapPanel x:Name="wrpPanel" VirtualizingStackPanel.IsVirtualizing="true" VirtualizingStackPanel.VirtualizationMode="Recycling" />

You can also use GetVirtualizationMode() & SetVirtualizationMode() to get or set the current mode.

Published by on under .Net | SilverlightTips

DependencyProperty is set to enable declarative code to alter the properties of an object which reduces the data requirements by providing a more powerful notification system regarding the change of data in a very specific way. In .NET, there are two types of properties. One is the normal property & another is the DependencyProperty which has added functionality over the normal property.

Now, let us discuss on how to implement such DependencyProperty to give a powerful notification on data change:

First of all, implement the UserControl class from INotifyPropertyChanged interface:

public partial class MyUserControl : UserControl, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Create your own normal Property, lets say the name of the property is “Caption”.

public string Caption

    get { return GetValue(CaptionProperty).ToString(); } 
    set { SetValue(CaptionProperty, value); }
}

Now, register the DependencyProperty to the CLR by calling the Register method by passing the property field that you used to store the data in earlier step:

public static readonly DependencyProperty CaptionProperty = DependencyProperty.Register("Caption", typeof(string), typeof(MyUserControl), new PropertyMetadata(string.Empty, OnCaptionPropertyChanged));

The name of the identifier field of the DependencyProperty will be same as you used in the property after appending “Property” at the end. In this example, our Property name is “Caption”, hence our identifier field name is “CaptionProperty”. Add the PropertyMetaData with default value & callback event handler within the Register method as mentioned in the above code. Mark the identifier as static & readonly so that this will be unique to the CLR.

Now, implement the OnCaptionPropertyChanged event handler:

private static void OnCaptionPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)

    MyUserControl myUserControl = dependencyObject as MyUserControl; 
    myUserControl.OnPropertyChanged("Caption"); 
    myUserControl.OnCaptionPropertyChanged(e);
}

private void OnCaptionPropertyChanged(DependencyPropertyChangedEventArgs e)
{
    txbCaption.Text = Caption;
}

The implementation of the DependencyProperty is complete. You can either call it from XAML:

<local:MyUserControl Caption="My First Dependency Property Example" />

or from Code behind:

MyUserControl myUserControl = new MyUserControl();
myUserControl.SetValue(MyUserControl.CaptionProperty, "My First Dependency Property Example");

Published by on under .Net | Silverlight

Splash Screens are always helpful while starting the application. At the time of loading application code & data from backend, it is always good to show a splash screen to the end user. It actually gives a look & feel of loading something and that time the user will see the first UI on his desktop. In .Net 3.5 SP1, this is really simple. Just do the following to add a simple basic splash screen to your application.

1. Create a PNG image & add it to your project. PNG images are better choice rather than BMP images because, they are lighter in size and you can also create a transparent PNG image.

2. Now right click on that image & click properties from the solution explorer of Visual Studio 2008 SP1.

3. Here you will find an option named “Build Action”. Select “SplashScreen” from the dropdown.

4. Save the project, build it & run the application.

Now you will see the image (Splash Screen) before rendering the actual application. After completion of rendering of the main window, the Splash Screen will automatically close. This way, it improves the startup experience of the WPF application.

Published by on under Tips | WPF

Microsoft provides a tool named “MakeCert.exe” which helps us to create a temporary SSL Certificate for development environment. This tool comes with Visual Studio & also with Windows SDK. If you installed Visual Studio, you can find it in this location: “C:\Program Files\Microsoft Visual Studio <VERSION>\SmartDevices\SDK\SDKTools”. If you installed Windows SDK, you will get it here: “C:\Program Files\Microsoft SDKs\Windows\<VERSION>\Bin”.

Now open Command Console (“cmd.exe”) & change your current directory to one of the location specified above. Type the following in Command Prompt & hit enter:

makecert -b 01/01/2009 -e 01/01/2020 -n "CN=Developers" -pe -r -sk "Microsoft Cryptographic Provider" -ss "Microsoft Cryptographic Store" c:\developerCertificate.cer

This will create a test certificate (valid from 01/01/2009 to 01/01/2020) named “developerCertificate.cer” in your ‘C’ drive, which you can use for development environment. You can change the validity period by changing the begindate (-b) & expirydate (-e). You can also change all the parameters specified above.

Here is the list of the parameters mentioned above:

Parameter Description
-b Begin Date
-e Expiry Date
-n Certificate Subject Name
-pe Mark Generated Private Key as Exportable
-r Configures MakeCert to create a self-signed root certificate
-sk Subject’s Key Container Name
-ss Subject’s Certificate Store Name
Published by on under Web |

Silverlight 3, though it is in beta stage, but it came up with lots of new features. Some of them are mentioned below:

  • Silverlight 3 now supports H.264 video formats & AAC audio formats. Now it also supports RAW audio/video pipeline
  • It now supports GPU Acceleration by adding a parameter (EnableGPUAcceleration = "true") in the Silverlight object
  • It now supports 3D functionalities. You can now add Perspective view to the element level
  • Various Effects has been introduced in Silverlight 3 using Pixel Shader API (e.g. Blur, DropShadow etc)
  • Various Animations (like: bouncing, transition) are now part of the Silverlight 3
  • A user can start a Silverlight out-of-browser "application" either by right-clicking on the Silverlight element or by clicking on a button within the application itself
  • Silverlight now supports custom dialogs. By using the SaveFileDialog you can now write contents outside the sandbox
  • It now supports local messaging across multiple silverlight plugins
  • XAP compression has been improved
  • Lots of new controls (like: DockPanel, WrapPanel, Label, ViewBox, TreeView, ExpanderControl, AutoCompleteBox) were added in this version. New controls in the Silverlight Toolkit are also available
  • DataPagination has been added in Silverlight 3
  • Using NavigationFramework you can now navigate to different view of the application. You can now integrate the browser back/forward functionalities with this framework
  • Binding of elements are now available by which you can update the UI without any code. Data validation in binding is also available in this release
  • AssemblyCaching is now available by which you can download the external assemblies only once & later you can use them from the cache. This will improve the application load time during next load
  • In Silverlight 3 Network monitoring API has been introduced, by which you can check whether the application is connected to the network or not
  • Now binary XML format is also supported in addition to the text XML which will improve the performance in the messaging area

Cheers :)

Published by on under Silverlight | Web