Follow us on X (Twitter)  Like us on Facebook  Connect with us on LinkedIn  Subscribe to our YouTube Channel  Subscribe to our WhatsApp Group

Silverlight 4 Printing API Demo Silverlight 4 now supports printing functionality using the Printing APIs. Using the APIs, you can now print your whole application screen or a portion of the application. Also, you can customize the look while you printing your part/full application.

 

In this post, I will step you guys to the depth of the printing API. Don’t forget to share your thoughts. Suggestions are always welcome. This will help me to improve my articles.

 

Published by on under .Net | Silverlight

Microsoft has just released the Silverlight 4 RC with several changes in the Silverlight runtime & in the Silverlight tools. Though there are couple of changes since Silverlight 3 & since Silverlight 4 Beta but it supports most of the Silverlight 3 applications by using Quirks mode. In some cases your earlier application will break or behave differently.

In this post I will describe you both the breaking changes in Silverlight 4 since Silverlight 3 & Silverlight 4 Beta. But before going to the discussion on the breaking changes, let me tell you what is Quirks mode. Quirks mode is a behaviour by which your previous application will work on the new runtime. Simple example is that, if you have Silverlight 3 compiled application it will try to run in Silverlight 4 (some cases it will fail) using quirks mode but if you compile the same application in Silverlight 4 it will not use the quirks mode and through errors on the changes.

 

What’s new in Silverlight 4:

  • XAP Signing
  • Custom Chrome Window
  • WebCam/Mic Configuration Preview
  • Text position and Selection API
  • Pinned full screen mode on secondary display
  • Support for Private Browsing
  • RichTextBox XAML clipboard format
  • Elevated apps doesn’t have Sockets Security Restrictions
  • Support for querying printer page size and printable area
  • XmlnsPrefix & XmlnsDefinition attributes has been added

 

Breaking Changes since Silverlight 3:

So, lets start with describing the breaking changes in Silverlight 4 since Silverlight 3.

  • Mouse Wheel Support - Silverlight 4 controls (ListBox, TextBox, ComboBox, ScrollViewer, Calendar, DatePicker, DataGrid) now have support for Mouse Wheel.
  • Shared BitmapImage Source – Now Silverlight 4 will render the images properly if more than one Image controls are sharing the same BitmapImage source.
  • ImageBrush.ImageSource returns ImageSource – ImageBrush.ImageSource in Silverlight 4 now returns ImageSource instead of UriSource which could be WritableBitmap or BitmapImage.
  • Keyboard Navigation in TabControl – Keyboard navigation in TabControl was a feature in Silverlight 3 having an issue with the TabItem activation. Previously pressing Up Arrow activated the next TabItem and pressing Down Arrow activated the previous TabItem. In this release they fixed it to properly activate the TabItem. In Silverlight 4 if you press Up Arrow it will activate the previous TabItem & pressing Down Arrow will activate the next TabItem.
  • Automation focus in DataGridCell - DataGridCell now receives automation focus when currency changes in the DataGrid, rather than focusing on the other part of the DataGrid.
  • Hit Test while Toggling Full Screen Mode – While toggling full screen mode Silverlight 4 will now rerun hit testing. This allows controls that were under the mouse before toggling to update the MoouseEnter state if necessary.
  • Whitespace handling with Span tag – TextBlock and RichTextArea now accepts text content & creates implicit runs generating whitespaces between inlines separated by CRLF.
  • DisplayMemberPath & ItemTemplate recreates all containers – Silverlight 4 now recreates all containers by invalidating them while there is any change in DisplayMemberPath or in ItemTemplate properties of the ItemControl.
  • New XAML Parser – Silverlight 4 now includes all new XAML Parser along with the previous XAML Parser. As per the runtime version detected in the application manifest it will parse the XAML in the appropriate parser. Apart from that, it has now additional benefits like “Better XAML compatibility”, “Greater parsing correctness & consistency”, “Better feedback error mechanism”, “Performance improvement”.
  • Panels Clear() method calls InvalidateMeasure – If you call the Clear() method of the Silverlight 4 panel it will now explicitly call InvalidateMeasure.
  • Virtualizing Stack Panel now scrolls by 3 lines – Mouse Wheel scroll in Silverlight 4’s Virtualizing Stack Panel will scroll by three (3) lines instead of one (1) line.

 

Breaking Changes since Silverlight 4 Beta:

If you were exploring Silverlight 4 Beta this section will be most important for you. There are some changes in both the runtime & tool since the beta release. So before starting with that please read the same carefully.

  • Removed TextSelection.CanInsert – TextSelection.CanInsert is now no longer available in Silverlight 4.
  • RichTextArea changed to RichTextBox – RichTextArea now renamed to RichTextBox.
  • RichTextBox.TextDecorations no longer exists – RichTextBox.TextDecoration is not available now. Instead of it you can use Inline.TextDecorations.
  • Default value to RichTextBox.TextWrapping – Silverlight 4 now has a default value of RichTextBox.TextWrapping to Wrap. If you don’t want to wrap your content you have to explicitly set it to NoWrap.
  • HtmlBrush renamed to WebBrowserBrush – In Silverlight 4 HtmlBrush now renamed to WebBrowserBrush.
  • COM Interoperability – COM Interoperability types are now moved to System.Runtime.InteropServices instead of System.Windows.Interop namespace.
  • WebCam/Output Protection Support – There has been a huge changes in the webcam/output protection support:
      • CanEnableHDCP renamed to CanEnableHdcp
      • CanEnableCGMSA renamed to CanEnableCgmsa
      • VGA, DVI, HDMI, LVDS, SDI, UDIExternal, UDIInternal also renamed to similar naming convention
      • VideoFormat.Height and VideoFormat.Width renamed to VideoFormat.PixelHeight and VideoFormat.PixelWidth respectively
      • AsyncCaptureImage call now changed to CaptureImageAsync
  • NotificationWindow – NotificationWindow.Visible property has been changed to NotificationWindow.Visibility
Published by on under .Net | News
You guys all know that Microsoft Visual Studio 2010 will be launch on 12-April-2010 worldwide and currently it is in Release Candidate (RC) state. I am exploring it for a while since Beta 2 & found it really useful than the earlier versions. There are lots of features added into the account of Visual Studio 2010 which will improve the productivity of application development. Developers can use it for faster coding, collaborating among the whole team & more. In this post I will describe the new features of Visual Studio 2010 which I already explored. I think this will be beneficial for all.
image

Multi-targeting Application Development:
Using Visual Studio 2010 you can not only develop applications for the .Net 4.0 but also can use it for the development of earlier versions of the framework. While creating a new project in the IDE you will see the option to select between different types of .Net Framework (i.e. 2.0, 3.0, 3.5 & 4.0).
image 
Depending upon your choice it will filter the project templates in the New Project dialog. If you select “.Net Framework 4.0” it will show all the project types but if you select “.Net Framework 2.0” it will only show the projects supported by .Net Framework 2.0.
image 
Not only this, as Visual Studio 2010 builds on top of Windows Presentation Foundation (WPF), you will find it more useful while searching for a specific project type. Suppose, you want to develop an application for your client in WPF & you are finding it very difficult to search within a huge collection of project types. Don’t worry. There is a “Search Box” right to the dialog for you to help finding the same. Just enter the keyword (in this case “WPF”) & see the magic. While typing, it will auto filter based on the keyword you entered.
image
Faster Intellisense Support:
Visual Studio now came up with faster intellisense support. It is now 2-5 times faster than the earlier versions. The IDE will now filter your intellisense as you type. Suppose, you want to create an instance of “WeakReference” & due to the search algorithm of the VS2010 IDE, you don’t have to write the full word of the Class. Just type “WR” and it will automatically filter out that & show you “WeakReference” in the intellisense. Try it out.
image
Editor Zoom Functionality:
You will find this feature useful while you are showing some presentation or doing a webcast. Earlier VS2010 you have to open the options panel & then you have to change the font size of the editor, which was little bit troublesome. Now that issue is gone. You don’t have to follow where to go to change the text size. While inside the editor window, just press the control key (CTRL) and use your mouse wheel to increase/decrease the zoom level.
image
Faster Assembly loading in “Add Reference”:
In Visual Studio 2010 loading of assemblies in the “Add Reference” dialog is pretty fast. In earlier versions, it freezes the dialog for some time to load all the assemblies. In 2010 IDE, by default it focuses on the “Project” tab & in the background loads the other tabs. In case it is opening the dialog focusing on the “.Net” tab you will notice that instead of loading all the assemblies at a time, it loads those in a BackgroundThread. Thus improving the loading time a bit faster.
image
Detach Window outside IDE:
Are you working on dual monitor? If so, you will find this feature very useful. VS2010 IDE now supports detaching Window outside the editor. Suppose, you want to detach your “Error”, “Output”, “Solution Explorer” or “Properties” window in the second monitor while working in the editor in the first monitor, you can do that now. Thus it gives you more space in the editor & separating your important windows outside the IDE.
image
Reference Highlight:
Another feature of Visual Studio 2010 IDE is the reference highlight. By this feature, it will highlight you all the call to that method or member variable, which you can find easy enough to search all the position of the reference wherever it has been called.
image
Faster Code Generation:
Before discussing about this feature with you, let me ask you a question “Are you using TDD i.e. Test Driven Development?”. If so, you will find this feature not only useful but very much attractive. So, what is that? Wait, lets ask yourself another question “How to write code while doing Test Driven Development?”. Thinking? Right, you have to implement the skeleton of the class & methods first and then you have to write the UnitTestcases to implement the actual logic. VS2010 came up with the excellent feature of generating codes for you. Have a look into the following snapshot:
image
As you can see, I don’t have a class named “Person” in my project and hence it is marking it as UNKNOWN by highlighting it in Red. If you look into the first snapshot in depth you can find out that though the class is not present in my namespace or even in the project, it is creating the class reference in the intellisense. Great, right? Wait a minute. If you now place you cursor on top of “Person” and press F10 while holding down ALT+Shift, you will see a dropdown comes up in the screen with two menu item asking you to either generate the class for you or generate a new type.
The first option you can find it easy. If you chose that, it will generate a class file named “Person” for you in the project. Lets go for the second choice where you will get more options & will find it much more interesting. This will open up a new dialog “Generate New Type” for you. There you can chose which access modifier you need (private/public/protected/internal), you can chose different types of code to generate (enum/class/struct/interface), you can also modify the location of the class file. You can either put it in the same project or you can chose a different project available in the solution. Not only that, you can also create a new file for the class or append the class in another file. In short, this feature gives you various options to customize.
image
Same thing is applicable while generating methods. Have a look into that.

Box Selection:
This is another nice feature of Visual Studio 2010. Let’s describe this using an example. Suppose, you declared some properties as public & in near future you want to mark them as internal. How can you do this? You will go and replace the access modifier one by one to internal. Am I right? Yup, in Visual Studio 2010 you can do this work very easily. Press Alt+Shift and draw a Box Selection using your cursor which will look like the first snapshot. Then type the desired characters to replace the text within the selected boundary.
image
Here in the example, the public keywords of the properties has been marked using the Box Selector and when typing, it is actually changing in all the lines. Have a look into the second snap where I am typing “internal” to replace “public” and that’s populating in all the lines where I marked.

Easy Navigation:
It is very easy now when you want to navigate to your specific code. As Visual Studio 2010 is built on top of WPF hence it has now proper filtering as and when you type. Press CTRL+, to open up the “Navigate To” dialog and this will show a list of matching criteria once you start typing in the “Search terms” field.
image
Better Toolbox Support:
Visual Studio now came up with better Toolbox support. You can now search Toolbox Item very easily. Just type the desired name of the Toolbox Item and the IDE will jump into the focus of matched element. Pressing TAB will bring the focus to the next matching element.
image
Breakpoints:
It has now a better feature in terms of Bookmarks. A team can now collaborate bookmarks between them by using the import/export bookmarks. You can now pin the debug value so that you can access it in later point of time, also you can now add a label to your bookmark.
image
Lets give a brief idea on this. Suppose, you are debugging your module & while debugging you found an issue in another’s module and want to let him know that there is a bug in his code and creating issues in your module. Just sending out an information requires debugging to the code again & finding out the issue by the another team member. Now in VS2010 IDE, you can now pin the debug value and export that bookmark with proper comments as an XML & send it out to your another team member. Once he imports it to his IDE, he can see the bookmark with the debug value available from the last session. From this point he can debug the root cause instead of finding out the area again. This is very useful in terms of collaborating debug information with the team.
image
The only thing that I don’t like here is, the XML which uses line number to store the breakpoint information. If the code has been modified in the other member side, it will not work correctly. The only requirements of the import/export to work correctly is “There should not be any modification in the shared code file”.

IntelliTrace:
Visual Studio has now the feature called “IntelliTrace” by which you can trace each step of your debug points. This is very useful when it comes to a larger UI where you can find the calling thread information in the IntelliTrace Window.
image 
There are more features like better TFS Support, in-built support for Cloud development, modeling, reports etc. which I have not explored till now. Once I explore those, will post it as a separate thread. So for now, go ahead and learn Visual Studio 2010 features and get familiar with it for productive development.

Published by on under Tips | VisualStudio

Microsoft has released two hot fixes till now for Visual Studio 2010 RC crash related to intellisense. The people who are currently using Visual Studio 2010 RC in a machine having UI Automation 3.0 APIs, touch screen, screen reader etc. have to download & install the following two HotFixes:

Click here to get the first Fix for Visual Studio 2010 RC

Click here to get the second fix for Visual Studio 2010 RC

If you need any more information on the fixes then get it here at MSDN Blog.

Published by on under News | VisualStudio

In this post I will talk for one of the new feature in C# 4.0 – Named and Optional Parameter. Actually these are not a single feature but two different feature. You can get more benefit if you work with them together. So, what are those? Named parameter is a way to provide an parameter to the method using the name of the corresponding parameter instead of its position in the parameter list. Whereas, optional parameter allows you to omit arguments to member invocation.

Published by on under .Net | C# 4.0
Hi folks, as all of you know that Silverlight 4 is now going to come out as “Go-Live” license within a few months and also in the mean time there are some wishlist coming for Silverlight 5, hence I am writing this post to collect those most wanted features requested by the community. Please contribute your wishlist for Silverlight 5 here (as comment) and I will update that list regularly.
  • Sophisticated Authentication & Security (includes client certificates as credentials for web service call) - [Vote] – alexander.biskop
  • More encryption algorithm - [Vote] – alexander.biskop
  • More flexible way to do localization in DataForm/DataGrid - [Vote] – sladapter
  • Application patching functionality - [Vote] – Haathen
  • Better Local Messaging API - [Vote] – ksleung
  • Better drawing API - [Vote] – ksleung
  • Support for Report Viewer - [Vote] - mlonny
  • Real time printing support - [Vote] – ksleung
  • Support for iPod/iPhone - [Vote] - microsoft_kc
  • Android support - [Vote] – ksleung
  • Better 3D support like WPF - [Vote] - microsoft_kc
  • An embedded database component like SQL-CE that can be used in OOB mode - [Vote] – Joeyw
  • Better support for WritableBitmap - [Vote] – Joeyw
  • Vector Printing - [Vote] – Joeyw
  • Support for IObservable for databinding - [Vote] – Joeyw
  • Rich Text Editor which allows Word Wrapping around images or other elements - [Vote] - Erwin Beckers
  • BMP and GIF image support - [Vote] - Erwin Beckers
  • More advanced controls like Outlook Agenda/Calendar control - [Vote] - Erwin Beckers
  • Transparency Support in Out-Of-Browser Mode - [Vote] - microsoft_kc
  • Improved SaveFileDialog with DefaultName option - [Vote] - Neha
  • ChildWindow with NON-modal support - [Vote] - Amantha
  • Flash video playback - [Vote] - Erwin Beckers
  • A working webbrowser control in a non-out-of-browser scenario - [Vote] - Peter Gfader
  • Support tooltip better for transparent, init delay, show delay, tiling image brush - [Vote] - Anonymous
Your suggestions for Silverlight 5 feature requests are welcome to publish here. Cheers…
Also, you can post them & vote in Silverlight Uservoice.
Published by on under Silverlight | Web

I think this is now-a-days a common issue for all the developers who are currently exploring both Visual Studio 2010 RC and Silverlight 4 Beta. Microsoft has removed the bits of Silverlight in the RC version of Visual Studio 2010. To work with that lots of people are now asking the same question.

Today I found a link which is written in a different version. I thought to share this thru my blog which may help the fellow developers (who are keeping a eye to my blog posts) to explore both simultaneously. Here is the original link of the post: http://sorokoletov.com/2010/02/hate-2-wait-silverlight-4-beta-2-vs-2010-rc/

Use the below link to translate it in English: http://tinyurl.com/SL4inVS2010RC-en

If you follow the steps provided in that blog post, you can install the Silverlight 4 Beta in your Visual Studio 2010 RC environment & start working on it till Microsoft releases the RC version of Silverlight. Go ahead and enjoy.

Remember: WCF RIA Services doesn’t work with this hack. I strongly recommend you to work with Visual Studio 2010 Beta 2 & Silverlight 4 Beta.

Published by on under Silverlight | SilverlightTips
Introduction:
Do you know that you can easily customize the Visual Studio 2010 start page? Yes, this is true. This uses a XAML page which you can modify easily if you have a knowledge in XAML. Redesign your page with your brand & look, impress your users (mainly your team) with the new look.
image
Why should I do this:
Now before reading the steps question may arise in your mind “Why should I do this? I don’t care what the look is.” Yup, this is right but thing in some point of view where you want to show some sort of information/news tracker on the best coding practises your team should follow or you may want to show the pending tasks of the team in the start-up page or you may want to redesign that page with custom templates to meet your company brand or something else.
How can I do this:
How I can do this? First of all, go to your “My Documents\Visual Studio 2010\StartPages”. There you will find a project named “StartPage” with an additional XAML file named “StartPage.xaml”. This xaml page is your Start Page of the Visual Studio 2010. Remember that this is user specific file & have to deploy for all users.
Before doing anything take a backup of the same. Now open the StartPage project file which will load the xaml in your Visual Studio IDE. Modify it according to the look & feel you want. Save it & you will immediately see the effect in your startup page.
Not only this. You can also chose different XAML files for your Startup XAML page. Create a separate XAML file with your design in the same directory as mentioned above. Open your Visual Studio 2010. Go to Tools –> Options –> Environment –> Startup.
image
Select the “Custom Start Page” from the drop down that you have created. Hit “OK” to see it immediately in your start page. Remember that for security reason you can’t change the path as this executes under the trusted privileges of the user only & also uses some references to the Visual Studio UI assemblies.
Published by on under Tips | VisualStudio
Microsoft just released Visual Studio 2010 Release Candidate (RC) & is now available for MSDN Subscribers. It will be available publicly by this Wednesday, 10th February 2010. If you are a MSDN Subscriber, you can download it from MSDN site: http://msdn.microsoft.com/en-in/default(en-us).aspx
Visual Studio 2010 RC has a “Go-Live” license, means you can develop softwares/applications using it & publish it. As you all know the features of Visual Studio 2010 in the Beta release, but I am again posting the link of Visual Studio RC features & walkthrough guide here so that it will be beneficial for the new users.
Go here & have a look into the Visual Studio 2010 RC features and walkthrough guide: http://msdn.microsoft.com/en-us/vstudio/dd441784.aspx
One update regarding the RC release is it doesn’t support Silverlight 4 but you can load/create Silverlight 3 projects using that. According to Scott in his Blog Post: “Silverlight 3 projects are supported with today’s VS 2010 RC build – however Silverlight 4 projects are not yet supported.  We will be adding VS 2010 RC support for SL4 with the next public Silverlight 4 drop. If you are doing active Silverlight 4 development today we recommend staying with the VS10 Beta 2 build for now.” Hence, those who are actively working on Silverlight 4 should work on Visual Studio 2010 Beta 2 instead of upgrading to the Release Candidate.
Complete this survey for Visual Studio 2010 and .NET Framework 4 Release Candidate: https://mscuillume.smdisp.net/Collector/Survey.ashx?Name=VS2010-RC
Last but not least, if you have any issue working with the RC version of Visual Studio 2010 or if you find any bug or if you have any future suggestions please never forget to report it at Microsoft Connect site: https://connect.microsoft.com/VisualStudio
Published by on under .Net | News

In this post I will discuss on how to create a Silverlight arrow. This will be beneficial for implementing Silverlight presentation where you can add some arrows to point to some blocks. This is simple enough to implement & will be beneficial for the beginners.

Create a Silverlight project. Now add a public class “Arrow” in it. Inside the Arrow.cs you have to add three lines (one is the base line, second is the left arrow head & the third is the right arrow head). Next you have to add those three lines inside a Panel.

Let’s start with creating the simple arrow in step-by-step process. First step is to create the base line of the arrow. Create a Line and set it’s (x1, y1) & (x2, y2). This will create the line.

private static Line CreateBaseLine(double startX, double startY, double length, Brush lineBrush, double thickness)
        {
            Line arrowLine = new Line();
            arrowLine.Stroke = lineBrush;
            arrowLine.StrokeThickness = thickness;
            arrowLine.X1 = startX;
            arrowLine.X2 = length;
            arrowLine.Y1 = startY;
            arrowLine.Y2 = startY;
            return arrowLine;
        }
Now lets create the left arrow head. The approach to it is same as creating the base line. Here only you have to pass the instance of the base line for calculating the (x1, y1).
private static Line CreateLeftArrowHead(Brush lineBrush, double thickness, Line arrowLine)
        {
            Line arrowLeft = new Line();
            arrowLeft.Stroke = lineBrush;
            arrowLeft.StrokeThickness = thickness;
            arrowLeft.X1 = arrowLine.X2 - 10.00;
            arrowLeft.X2 = arrowLine.X2;
            arrowLeft.Y1 = arrowLine.Y2 - 10.00;
            arrowLeft.Y2 = arrowLine.Y2;
            return arrowLeft;
        }
Creation of right arrow head is also similar to the one I mentioned for creating the left arrow head. The difference here is the y1.
private static Line CreateRightArrowHead(Brush lineBrush, double thickness, Line arrowLine)
        {
            Line arrowRight = new Line();
            arrowRight.Stroke = lineBrush;
            arrowRight.StrokeThickness = thickness;
            arrowRight.X1 = arrowLine.X2 - 10.00;
            arrowRight.X2 = arrowLine.X2;
            arrowRight.Y1 = arrowLine.Y2 + 10.00;
            arrowRight.Y2 = arrowLine.Y2;
            return arrowRight;
        }

Here instead of creating two separate methods for creating the two arrow heads you can just create only one method & pass the calculated (x1, y1) & (x2, y2). This is the simple approach mentioned here to give an idea to the beginner to create an arrow. It can be modified to implement some complex arrows like Horizontal, Vertical or even better Connected Arrows.

Download Sample Application: Silverlight Arrow Demo

Published by on under .Net | Silverlight

Microsoft Community Techdays is going on in India. It already started in 12 cities across India for Developers & IT Professionals. This will cover a big content on .Net 4.0, Visual Studio 2010, Silverlight, Cloud Computing, Windows 7 and SQL Server. Go ahead & learn the technical skills from the experts.

Visit the Community Techdays site and register yourself for your active participation. Chose any one of the event (Online or In-Person) which best suits you.

Published by on under News |

Mozilla released their final version of Firefox 3.6 with additional features. Some of it’s top features are:

  • Private Browsing like Internet Explorer 8
  • Nice Password Manager
  • Fastest Browsing Speed
  • Anti-Phishing & Anti-Malware support
  • New Session Restore
  • Easy Customization of add-ons
  • Improved Tab Browsing
  • New Personalized Themes
  • Improved Favourite Toolbar

To check all other features of Mozilla Firefox visit the Firefox Features site. If you are not using that yet you can download it from Firefox Download site.

Published by on under News |

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