Get Microsoft Silverlight

Wednesday, December 31, 2008

Mix 10K Coding Challenge - Few Tips I have used to limit the code size



While developing for the MIX 10K coding challenge, the major challenge to face is to limit the code in 10K size. So I had to question each and every line of code that would it be possible to write this even with fewer bytes.
 Check out my application at http://2009.visitmix.com/MIXtify/TenKDisplay.aspx?SubmissionID=0044 Make sure to run the application in fullscreen mode.
 Here I am compiling a list of tips and features I used to reduce the code size. 
1.       Automatic Properties - Used this .NET feature to create the Tweet class which represents an RSS feed item from the search result   
public class Tweet {
  public string Guid { get;set; }
  public string Title { get;set; }
  public string Author { get;set;

    … ….

2.       Object Initializers
new Tweet {Title = element.Element("title").Value,
Author = element.Element("author").Value,
Guid = element.Element("guid").Value}};
3.       LINQ to XML - I have used this to read the XML stream from the search result handler.
4.       Collection Initializer - Collection initialize has used along with the LINQ query, which does a huge amount of job with fewer lines.
5.       Use 'Var' - Used to initialize a variable without specifying its type
 The bellow few lines do all the work to grab the RSS feed in to a collection variable which utilizes the features 3,4 and 5 above
XElement elements = XElement.Parse(e.Result);
var items = from element inelements.Descendants("item")
select new Tweet { PrevZ = double.NaN, Title = element.Element("title").Value
 6.       Anonymous functions - This save you some bytes. Bellow line I have used to toggle between the Fullscreen modes when the user clicks on a checkbox named 'chkFullScreen'
chkFullScreen.Click +=delegate{Application.Current.Host.Content.IsFullScreen = !Application.Current.Host.Content.IsFullScreen; };
 7.        Remove all Private keywords - Default member accessor is 'Private' so you don’t need to specify that :)
8.       Remove all unused 'Using' statements - Easy ways to check – When you finish coding, removes all the ‘using’ statements and then correct the compile error
Some other editing tricks (This can make the source code un-readable too).
  Reduce the Tab size to zero
  Remove all white spaces
  Make the entire source code into few lines.
  Put all the source code in to a single source file 
  Single character variable names.

I haven’t used much of these editing tricks. The code was just 8.96KB. So I kept the source readable and in 4 separate files.

Mix 10K smart coding challenge


The Mix conference 2009 has organized a coding challenge on Silverlight/WPF with a restriction of using only 10Kb of source code. You can see the gallery of submissions at http://2009.visitmix.com/MIXtify/TenKGallery.aspx. Please visit and cast your vote for the entries you like, You can see my entry here.

My application allows you to search the twitter feeds over the internet using Twitter Search APIs(basically same as what you can see at http://search.twitter.com/) What I am trying to acheive here with silverlight is just another way to visualize the search data along the time line travelling towards the negative Z-space. One more interesting feature I wanted to add to this in the future version would be to give the ability to navigate through the Z-space with mouse scroll to see the older results. This same kind of UX(user experience) can be used to view any sort of time based feeds like blog feeds or search results. Architecturally the application is utilizing the following major features
1) DataTemplate
2) MVVM Pattern-Used mainly an ObservableCollection as the ViewModel to keep the UI notified on all the data change events.
3) Custom Panel - I have used a special panel called Space panel which arranges the items in a way to give a Parallax effect(2.5D)
4) LINQ - More specifically LINQ to XML to parse the incoming search data and other data processing.
Class diagram shown the Entity class and the Panel

My initial reaction to 10K code size restriction was that it would be too less to write this application. But you know, surpisingly with all the richness and power of .NET3.5(Specifically XAML,C#(ver3.0) and LINQ) we can write a moderately rich interactive application with just 10K of code. All the tips and tricks I have used to limit the code in 10Kb will be posted to you in my next blog.

Friday, December 26, 2008

Paginated ObservableCollection

ObservableCollection class makes the collection binding very easy in Silverlight or WPF. This special collection is aware of the binding infrastructures and notify them whenever some changes happens to the collection.


I have often come across the requirement to have  pagination enabled on collections. When we bind a Collection with many items inside to an ItemsControl, the visual will be created for each and every items. But as we can see that there is no big significance in displaying all the data with a huge vertical scroll bar(or similar mechanism) in it. So pagination is the typical user experience strategy we use in this kind of scenarios. Architecturally we can achieve the pagination mainly in three different ways
  1. Making the UI Control or Panel aware of the virtualization, so that the visuals wont create at the time of binding. But as an on demand visual element creation. VirtualizingPanel concept in WPF is actually helps to achieve this idea. For more details about WPF virtualizaiton panels, go here and here - In terms of MVVM pattern this will be implemented at the View side.
  2. Making the collection aware of the pagination and that special collection always gives a subset of items to the UI for making the visuals. In terms of MVVM pattern this solution is implemented as ViewModel
  3. Last and most commonly used way in the web technology - Typical DB/Back end/Web service side pagination where the pagination is controlled in the query side. This is best way for handling huge data like what we see in most of the typical websites out there. Typically the implementation is part of the Model
Paginated ObservableCollection
   I have created a PaginatedObservableCollection as an experiment to achieve the UI vitalization based on the point (2) of the above list. And this special generic Collection is derived from ObservableCollection. This has mainly two properties 
  • PageSize - to store the number of items that can be shown in a single page 
  • CurrentPage - the page number of the current page which the UI is showing in a particulr time.
This collection internally keeps the original items in a private List and based on the above two properties the PaginatedObservableCollection returns a subset of the items inside the list.You can use this new Collection in the same way as you use any ObservableCollection and the two properties are also databindable to the UI to control the collection behaviors.

See a running demo in Silverlight here.


You can find the source code in CodePlex  - http://www.codeplex.com/PaginatedCollection , Feel free to give your suggestions comments to improve this. Source code include  WPF and Silverlight sample code


The current version of source code is not a thread proof implementation, but this can be taken as a starting point to make a working application to get this feature. There are some good articles about Observable collection in the multi-threading environment by Tamir and Beatriz

Wednesday, December 03, 2008

XAML Balloon Comments - Expression Blend Tip

It is often a requirement in Silverlight and WPF that to create Balloon kind of UI for Toolip popups. It can be done in many ways. I am listing out few of the common Balloons you might be interested in.




  <Grid            <Grid.RowDefinitions>

                <RowDefinition Height="*"/>

                <RowDefinition Height="30"/>

            </Grid.RowDefinitions>

            <Rectangle RadiusX="10" RadiusY="10" Stroke="#FF000000"/>

            <Path Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" HorizontalAlignment="Left" Margin="30,-1.6,0,0" Width="20" Grid.Row="1"

                Data="M22.166642,154.45381 L29.999666,187.66699 40.791059,154.54395"/>

            <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="14" Text="Hello World" TextWrapping="Wrap" FontWeight="Bold"/>

        </Grid>




This Balloon doesnt change its corner Radius when you resize. And also doesn't change the size of the Tip when you resize. The Tip has its height always be 30 since the Grid Row height is 30. You can tweak the constants in the XAML apporpriately to make it looks proper for your scenarios.




<Path Stretch="Fill"="2" Data="M10.5,0.5
L108.60157,0.5 C109.98227,0.5 111.29763,0.77982046 112.49402,1.2858505
114.88678,2.297905 116.80367,4.2147827 117.81572,6.6075516 118.32175,7.8039356
118.60157,9.1192895 118.60157,10.5 L118.60157,51.442939 C118.60157,52.823647
118.32175,54.139003 117.81572,55.33539 116.80367,57.728154 114.88678,59.645032
112.49402,60.657088 111.29763,61.163118 109.98227,61.442938 108.60157,61.442937
L22.30129,61.681242 11.674737,79.949581 10.48383,61.465811 10.209005,61.465811
C8.8282947,61.465812 7.8039303,61.163115 6.6075497,60.657088 4.2147805,59.645032
2.2979068,57.728154 1.2858486,55.33539 0.77982051,54.139003 0.5,52.823647
0.5,51.442939 L0.5,10.5 C0.5,9.1192895 0.77981997,7.8039356 1.2858486,6.6075516
2.2979069,4.2147827 4.2147808,2.297905 6.6075497,1.2858505 7.8039303,0.7798233
9.1192894,0.5 10.5,0.5 z"
Stroke="#FF000000"/>





If you combine the Rectangle and Path in the above Balloon you will get a single Path. But the issue here is that when you resize this Path along with  your contents the corners and the Tip wont look exactly the same, both will  get stretched on the direction of resize. But this can be useful in many scenarios.

 

 

 

Sunday, November 30, 2008

Interactive Silverlight Greeting Card

For the last couple of days I was trying to make an animated e-card using Silverlight. So here is the final result. The speciality of this card is that when we move the mouse over the card we can see it as if it is a 3D object and get the perspective view of the objects(Papervision 3D?). All the Trees and Mountains are Path objects and the particles falling down are random sized ellipses. I have used Microsoft Expression Blend to do most of this work


The important part of this Silverlight appplication is a Custom Panel called SpacialArrangePanel. This panel will arrange its children based on two Attached Dependancy Properties.
1) HangingPoint - A point determines its X and Y position in the space
2) ZDistance - A double value determines how far the object is in the Z-plane.

There is another DependancyProperty in the Panel called CameraPoint, which has been hooked to the Mouse Move points so that the mouse pointer acts as an Eye/Camera view point of the Panel.

I have added the InitParams query string in the HTML so that this card can be customized to use special Message and Name on it. Just change the Greeting and YourName parameters in the bellow HTML.

 <div id="silverlightControlHost">

        <object data="data:application/x-silverlight,"

            type="application/x-silverlight-2" style="width: 840px; height: 353px">

            <param name="source" value="http://ria-labs.com/silverlight/samples/xmascard1/XMasCard.xap"/>

            <param name="InitParams" value="Greeting=Merry Christmas,YourName=Jobi Joy"/>           

            <param name="minRuntimeVersion" value="2.0.31005.0" />

            <param name="autoUpgrade" value="true" />

            <a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;">

                <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/>

            </a>

        </object>

    </div>



And here is the Source code

Saturday, November 15, 2008

Concave cornered Rectangle - Expression Blend Tip


An expression blend tip to create a Path looks like a concave cornered rectangle.  Put a Grid with 5*5 rows and columns. and add 4 ellipse and a rectangle as in the following XAML.

<Grid x:Name="grid" >
    <Grid.ColumnDefinitions>
     <ColumnDefinition Width="0.1*"/>
     <ColumnDefinition Width="0.1*"/>
     <ColumnDefinition Width="0.6*"/>
     <ColumnDefinition Width="0.1*"/>
     <ColumnDefinition Width="0.1*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
     <RowDefinition Height="0.1*"/>
     <RowDefinition Height="0.1*"/>
     <RowDefinition Height="0.6*"/>
     <RowDefinition Height="0.1*"/>
     <RowDefinition Height="0.1*"/>
    </Grid.RowDefinitions>
    <Rectangle Fill="#FF000000" Grid.Column="1" Grid.Row="1" Grid.RowSpan="3" Grid.ColumnSpan="3" StrokeThickness="0"/>
    <Ellipse Fill="#FFEA0000" VerticalAlignment="Stretch" StrokeThickness="0" Grid.Row="0" Grid.Column="0" Grid.RowSpan="2" Grid.ColumnSpan="2"/>
    <Ellipse Fill="#FFEA0000" StrokeThickness="0" VerticalAlignment="Stretch" Grid.ColumnSpan="2" Grid.RowSpan="2" Grid.Row="3"/>
    <Ellipse Fill="#FFEA0000" StrokeThickness="0" VerticalAlignment="Stretch" Grid.ColumnSpan="2" Grid.Row="3" Grid.RowSpan="2" Grid.Column="3"/>
    <Ellipse Fill="#FFEA0000" StrokeThickness="0" VerticalAlignment="Stretch" Grid.Column="3" Grid.ColumnSpan="2" Grid.Row="0" Grid.RowSpan="2"/>
   </Grid>

Do the Subtract Path operation by selecting menu option Object -> Combine -> Subtract
Now you will get a Path object as bellow XAML.

<Path Fill="#FFA1A1A1" Stretch="Fill" Stroke="#FF000000" StrokeThickness="1" 
Width="50" Height="50" Data="M17.200002,0L120.4,0 120.4,2.3066998E-06C120.4,6.7378696,128.10079,12.200001,137.60001,12.200001L137.60001,85.400003C128.10077,85.400003,120.4,90.862138,120.4,97.6L17.200002,97.6C17.200002,90.862151,9.4993697,85.400003,0,85.400003L0,12.199999C9.4993663,12.200015,17.200002,6.7378725,17.200002,0z"/>

The above can be achieved in many different ways. You can use Expression Design or Adobe illustrator to generate a Path like this.
And if you are looking for a custom shape like this, you can create that by deriving a class from System.Windows.Shapes.Shape by doing some similar Geometry operations. Then we can define some dependency Properties for controlling the Concave radius too.

Thursday, September 11, 2008

WPF Clock


I had written a blog a long time back on creating a simple WPF clock. It was actually one my first few sample applications that I built when I got to fiddle with Expression Blend for the first time. Only today I noticed that the hyperlink to the Source code on the blog was actually broken for a long time and there are still quite a few asking me for the source code. So I am posting the same here with out even looking in to what I have done 1.5 years back :). Ofcourse I had to convert the source to VS2008(.NET3.5)
Download the Exe Here

Thursday, September 04, 2008

Desklighter - A handy tool for Silverlight

As a silverlight developer I have often come across the need to demonstrate my work to others and post it to the Silverlight community. The options we generally use are listed below

1)You can just share the entire source code as a zip.
But do you think most of the guys out there have the patience to download-compile-run the code? And sometimes you dont want to share your source code with the public.

2)Upload the application to a webserver
But you need to have a webspace and ofcourse the website should support Silverlight. People always need connectivity to the website to run your sample.

3)A new way to share Silverlight
Imagine that you could create an EXE out of Silverlight application and send that across your guys and get some comments to improve your work. This makes a silverlight application 'Offline' Sounds like a good idea?
So Desklighter is your tool to do that. Deskllighter is a free tool from identitymine

Sameer has a great post explaing more details about the desklighter

How does it work?

I just tried to convert Silverlight sample created in my previous Marquee Blog.

The conversion is as simple as the screen shot bellow. I have pointed my xap file path to desklighter tool and clicked on the 'Convert' button, I am done!. Check out the MarqueeTest.EXE file I got.




Desklighter is an application which is writen in .NET2.0 and it contains a small TCP server and a Webbrowser control, in other words it contains a small server as well as a browser.

Monday, August 18, 2008

Silverlight Marquee Control

My previous post describes about making a Custom marquee control in WPF. Here is what I tried the same using Silverlight. Silverlight is getting really mature with its latest releases, it has come pretty close to WPF in most of the scenarios.
There is a difference with the way you create the Generic.xaml for writing the default look. You have to manually add the Generic.xaml to the project and set the build action as Resource file. See this blog for a detailed explanation of this. And the XAML code is still the same as what we wrote in WPF. The following code has to be added to the constructor so that whenever the control gets instantiated the default style will be associated with that.
public Marquee()
{
   DefaultStyleKey = typeof(Marquee);
 }
The rest of the code is pretty much the same as WPF. I have added a Duration dependency property so that end user will be able to change the speed of the animation at run time. And subscribed to the mouse enter and leave so that animation will just stoped if the mouse is on top of the control.

Live Demo Url
Source Code can be downloaded
here

Friday, August 15, 2008

WPF Custom Controls - Marquee control

WPF and Silverlight have the cool idea of 'Lookless controls' which means you can skin a control in whichever way you like. Or in other words the UI rendering logic of a WPF control lives totally in a seperate world than the control's functionality. This enables a WPF applications capaibility to dress up in totally different skins and layouts at the run time.
So let me explain the creation of a simple custom control by taking the example of a Marquee control. Hope you are well aware of the HTML Marquee tag. I am explaining the CustomControl concept of WPF with Marquee control as an example.

Step to Create a custom control with VS2008

The above step will give you the class file and Generic.xaml added to the project.

Who is your control Parent?
First I should choose the base class from which my control has to derive from. I am seeing the Marquee as a control which holds up a content element always and the content gets scrolled horizontally. So I can say that ' Marquee control has a Content' so lets write that statement in C#.
public class Marquee : ContentControl

What is the default look of your control?
Next step is to define the visual elements which builds up the default look. My idea here is to put a Canvas and make the content scroll inside the canvas using DoubleAnimation on Canvas.Left attached property. So the default template can be writen as shown in the XAML.
   <Style TargetType="{x:Type local:Marquee}">
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="{x:Type local:Marquee}">
                <Canvas>
                  <ContentPresenter  x:Name="PART_Content"/>
                </Canvas>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>
 
You can see from the XAML that the ContenPresenter is having a name so that we can find the reference of this control inside the control logic. So here we are making a mutual contract between the Control logic and the UI logic that we will always expect a control named PART_Content in the control template. So anybody who is goinging to re-template this would be considering this fact.
Using the following code we can find the instance of the above metioned contentpresenter

public override void OnApplyTemplate()
{
  _contentPresenter = Template.FindName("PART_Content", this) as FrameworkElement;

Marquee Logic Implementation

private void Animate()
{
   if (IsLoaded)
   {                            
     _doubleAnimation.From = this.ActualWidth;
     _doubleAnimation.To = -_contentPresenter.ActualWidth;
 
     _doubleAnimation.RepeatBehavior = RepeatBehavior.Forever;
     _doubleAnimation.Duration = Duration;
     Storyboard.SetTargetProperty(_doubleAnimation, new PropertyPath("(Canvas.Left)"));
     _storyBoard.Children.Add(_doubleAnimation);               
 
     _storyBoard.Begin(_contentPresenter,true);                
   }
}
The animation code has taken the actualWidth of the content and animate the Canvas.Left from control's rightside to left.

Sample Application
Check out the XBAP application - LIVE DEMO running this marquee. One marquee with a TextBlock as its content and another with an ItemsControl as its content.
<lib:Marquee Duration="00:00:10" RenderTransformOrigin="0.5,0.5" HorizontalAlignment="Stretch">       
   <TextBlock FontSize="18" FontWeight="Bold" Foreground="#FF000000" Text="Sample Marquee Text" />
</lib:Marquee>
 
<lib:Marquee Duration="00:00:10" RenderTransformOrigin="0.5,0.5" HorizontalAlignment="Stretch">
   <ItemsControl x:Name="lstPhotos" ItemsTemplate="{StaticResource someCoolTemplate}"/>
</lib:Marquee>
 

Friday, August 08, 2008

Silverlight DeepZoom + AndreaMosaic

Take a look at the Deepzoom page composed by Rob Burke using AndreaMosaic and Silverlight Deepzoom. This is such a great idea and to me this is going to be the major use of Silverlight Deepzoom technology. I am not sure that how many other software available out there which does photo mosaic.
So I just tried to do one by myself. Bellow are the steps I followed
1) Installed AndreaMosaic and just follow the steps to create a photo mosaic file. You have to play little bit around the tool to undertsand what exactly is happening.
2)Open the DeepZoom composer (Can be downloaded here) and arrange your photo mosaics in the order
3)Export the Deepzoom project to silverlight project
4)Publish that to Silverlight Streaming service

Original Photo

and the bellow deepzoom Silverlight(multiscale image) has around 1000 images in it. Check this out by drag and scroll your mouse. Or check out theStreaming version here

Friday, August 01, 2008

Podder Skinning - Another WPF Contest

For the last two weeks I was a little busy with the WPF work for the Podder Skinning Contest by Josh Smith. Josh had a great WPF application architectured to support complete UI skinning. So all I had to do was to make some controls hooked up to his Model / Commands, and give it the look - that is the beauty of XAML/WPF. There are a series of posts he had made on theCode project explaining it really well
The WPF Podcatcher Series - Part 1 (Introducing Podder)
The WPF Podcatcher Series - Part 2 (Structural Skinning)
The WPF Podcatcher Series – Part 3 (The Podcast Management Conundrum)
The competition was annouced few months back but I was not sure about my time and availability and also I was not relieved from the hang over created by the previous contest - This needs more time out of my family:). Then I heard Josh has extended the deal line to Aug 4th. This time I decided to give it a try in two weeks .



And here is the Source Code

All my ideas were around the Aero glass feature of Vista. The window will be fully resizable to any size and all the controls will resize accordingly. As far as the tools concerned I have worked almost 70% of my time with Expression blend and 20% on VS2008 and rest with Expression Graphic Design for some PNGs. For the first time I tried using expression design for creating the icons. It works really great. :)

There are still some more features to be finished, but I am leaving it for the time being. One of them is the Next and Back button not hooked up. It seems there is no ready to hook command/Property for this.

Wednesday, July 23, 2008

Finally the cool prizes have arrived!

I received the prizes of the WPF Contest held by Lab49. There are really some exciting items for a programmer on MS technologies.
1) Vista Ultimate
2) VS2008
3)Expression Blend
4)An 8GB zune player. etc



Thursday, July 10, 2008

A Cool Control Template for WPF Button




JellyButton_Theme.XAML

Few days ago I happened to see this blog It shows a step by step instruction to create a nice glassy button in photoshop.
Here is what I tried in expression blend to customize(control template) a button with the same look in mind. I have used few ellipses and 2 grid panels to make this effect. There is a Trigger functioning on it to show the interactions of the Press and Release action.

Check out the XAML file to see the WPF button in action. You can open the XAML file in Internet Explorer if you are running in Vista.
UPDATE : You can also check out my other blogs on Theme
Check out the Silverlight version of the above here

Tuesday, April 22, 2008

A Simple Radial Panel for WPF and SilverLight

Geometry was one of the coolest topics in school for me. Probably because it uses a lot of figures to convey the concepts. Here I am trying to explain how we can leverage the Layout system in WPF and Silver light by taking an example of creating a Radial Panel. A RadialPanel lays out its children in a circular fasion. So before going in to the technical details, let us see how this problem get solved algorithmically.If you are asked to arrange a bunch of items in a circular path, what all things would you consider?.
1) How much space do I have? – Say X * Y rectangular area is the available size.
2) I will draw an approximate Circle (Or ellipse) inside the X*Y space. Assuming that the Radii are ‘Rx and Ry'
3) How many items are there to arrange? Say N – number
4) I know that 360 degrees are the total angular space for a circle. So angular distance between each item will be 360/N degrees.
6) I can calculate the coordinate point to which an item should be placed. That is by doing the following simple trigonometry operation. The coordinate point will be at Rx * Cos (Angle), Ry*Sin (Angle).
The math can be visualized from the figure bellow.




It is so interesting that WPF has kept the custom panel implementation in such a way that we can easily code the above steps directly in to code. First of all you have to create a class derived from the System.Controls.Panel. The two methods we need to override are

protected override Size MeasureOverride(Size availableSize) - In this pass you can do the following.


  1. Iterate the collection of children that are part of layout, call Measure() on each child element.

  2. Compute the net desired size of the parent based upon the measurement of the child elements.

protected override Size ArrangeOverride(Size finalSize) -



  1. Iterate the collection of children that are part of layout, call Arrange() function on each child element.

  2. Compute the net final size of the panel based upon the arrangement of the child elements.

Here is the implementation of the RadialPanel. Hope the comments in between explains the relvance of each step.


    public class RadialPanel : Panel

    {

        // Measure each children and give as much room as they want 

 

        protected override Size MeasureOverride(Size availableSize)

        {

            foreach (UIElement elem in Children)

            {

                //Give Infinite size as the avaiable size for all the children

                elem.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));

            }

            return base.MeasureOverride(availableSize);

        }

 

        //Arrange all children based on the geometric equations for the circle.

        protected override Size ArrangeOverride(Size finalSize)

        {

            if (Children.Count == 0)

                return finalSize;

 

            double _angle = 0;

 

            //Degrees converted to Radian by multiplying with PI/180

            double _incrementalAngularSpace = (360.0 / Children.Count) * (Math.PI / 180);

 

            //An approximate radii based on the avialable size , obviusly a better approach is needed here.

            double radiusX = finalSize.Width / 2.4;

            double radiusY = finalSize.Height / 2.4;

 

            foreach (UIElement elem in Children)

            {

                //Calculate the point on the circle for the element

 

                Point childPoint = new Point(Math.Cos(_angle) * radiusX, -Math.Sin(_angle) * radiusY);

                //Offsetting the point to the Avalable rectangular area which is FinalSize.

                Point actualChildPoint = new Point(finalSize.Width / 2 + childPoint.X - elem.DesiredSize.Width / 2,finalSize.Height / 2 + childPoint.Y - elem.DesiredSize.Height / 2);

 

                //Call Arrange method on the child element by giving the calculated point as the placementPoint.

                elem.Arrange(new Rect(actualChildPoint.X, actualChildPoint.Y, elem.DesiredSize.Width, elem.DesiredSize.Height));

 

                //Calculate the new _angle for the next element

                _angle += _incrementalAngularSpace;

 

            }

 

            return finalSize;

        }

    }


And finally the XAML file and its preview has shown bellow from VS2008 , And you can use the same Panel class in a SilverLight2.0 project with the same XAML usage .


The following screen shows all the System.Media.Colors in an ItemsControl which intern has RadialPanel as its ItemsPanel.

The XAML for this is pasted bellow.

<Window x:Class="WPFSample.Window1"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:local="clr-namespace:WPFSample" 

    Title="Window1" >

    <Window.Resources>        

        <ItemsPanelTemplate x:Key="radialTemplate">

            <local:RadialPanel />

        </ItemsPanelTemplate>        

        <DataTemplate x:Key="enumTemplate">

                <Rectangle Width="20" Height="20" Fill="{Binding Name}" ToolTip="{Binding Name}" Stroke="#FF000000"/>

        </DataTemplate>

    </Window.Resources>

 

    <ItemsControl Name="itemsControl" ItemTemplate="{DynamicResource enumTemplate}" ItemsPanel="{DynamicResource radialTemplate}"/>

 

</Window>


You will also need this in the code behind to set the ItemsSource property of the ItemsControl.

 itemsControl.ItemsSourcetypeof(Colors).GetProperties();



For more details about the WPF Panel concept, I recommend you to read Dr.WPF’s ItemsControl: 'P' is for Panel

Sunday, March 16, 2008

WPF Finance Contest Results Announced

I would like to share a good news that I have been selected as on of the finalists in the WPF contest , You can see the results and the download the entries here

The Grand Prize winner : Szymon Kobalczyk
Finalists :
1) Jacob Carpenter
2) Jobi Joy - thats me:)
And the Honorable Mention went to Paul Hounshell

Wednesday, March 12, 2008

WPF Finance Application

Here are some videos and screenshots of the application I build for the WPF Finance Contest.





This Application will function as both Stock Ticker and Stock Analyzer tool. This has been designed to change Themes and Colors at run time.


Stock Ticker
The Application starts running as a Stock Ticker at first and shows up as the topmost window; user can move the ticker window by dragging the Clock on the left side of the window. User can right click on the Ticker Symbol to flip them and see the Intra-day line Chart.
While in the Analyzer mode you can drag and drop Symbols to the Stock Ticker and the Scrips will get serialized and saved for the next session.
Stock Analyzer
By Clicking on a small arrow (Expander) at the bottom of the ticker, the user can switch in to the Analyzer mode. Now you can drag symbols from the ticker and drop on to the expanded area or Search symbol in the left pane and analyze. You can drag many chart symbols in to the Analyzing area and the Summary details will be displayed. Just click the mouse on any area inside the Line charts to see that day’s HLOCV values. At any instance the mouse over on any Scrip will highlight any other instance shown up in the screen. We can add/remove any number of items in to the stock ticker.
The chart can be zoomed to a specific date range by the two sliders at the bottom.