Monday, January 30, 2012

Telerik Chart Item in Metro Style

Recently all the sites and apps have started following the Metro UI. Even I like it as it looks elegant and simple. So I thought of giving my old Telerik chart application a metro theme. However, as the site says, I did not had the Telerik.Windows.Themes.Metro.dll, I could not add the theme just by writing one line of code.  So I thought of creating it on my own.  At first it looked tough for me to rip down the super glossy, rich and otherwise super cool UI of Telerik Charts into Solid fills and non glossy UI to match the Metro standards. Not because it was difficult but it was hard for me to disturb the richness of the Telerik charts :) Phew! This is how I finally did it...
All you have to do is delete the gloss in the charts. This is usually done by adding an extra basic UI element with a partially transparent gradient fill. For eg. If you take the Pie chart...this is the extra circle that gives the gloss effect. 
You may not be able to able to remove this layer by styling the entire Pie chart. For this you will have to style a single Pie Element or Slice. You may search in the Assets panel of your expression Blend for a Pie slice or may add this


<telerikCharting:Pie HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="100"/>

Once added right click on the Pie and select the Edit Template->Edit a copy option. Once the template for the Pie opens up you will see the basic elements of style used in the slice. You will find that there is an ellipse on top of the “PART_DefiningGeometry”. This ellipse must be having the transparent gradient. Remove this ellipse or collapse this ellipse. 
Now apply this style to your SeriesDefinition...your metro UI will be applied.
To apply the style from code behind use this


Code:
SeriesMapping pieSeries = new SeriesMapping();
pieSeries.SeriesDefinition = new PieSeriesDefinition();
pieSeries.SeriesDefinition.ItemStyle = App.Current.Resources["PieStyle1"] as Style;


Here is what the end product will look like. I have added few bright colours in the PalleteBrushes collection to match the dark background. 
Here is the complete code to this style,

Code:
<RadialGradientBrush x:Key="PieMaskBrush" GradientOrigin="0.5,0.5">
      <GradientStop Color="#33FFFFFF" Offset="0.88"/>
      <GradientStop Color="#00FFFFFF" Offset="0.65"/>
      <GradientStop Offset="0.89"/>
     </RadialGradientBrush>
     <Style x:Key="PieStyle1" TargetType="telerik:Pie">
      <Setter Property="Template">
       <Setter.Value>
        <ControlTemplate TargetType="telerik:Pie">
         <Canvas x:Name="PART_MainContainer">
          <Canvas.RenderTransform>
           <TransformGroup>
            <ScaleTransform x:Name="PART_AnimationTransform" ScaleY="0" ScaleX="0"/>
            <TranslateTransform x:Name="PART_ExplodeTransform"/>
           </TransformGroup>
          </Canvas.RenderTransform>
          <VisualStateManager.VisualStateGroups>
           <VisualStateGroup x:Name="HoverStates">
            <VisualState x:Name="Normal">
             <Storyboard>
              <DoubleAnimation Duration="0.00:00:00.15" To="1.0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="PART_MainContainer"/>
             </Storyboard>
            </VisualState>
            <VisualState x:Name="Hovered">
             <Storyboard>
              <DoubleAnimation Duration="0.00:00:00.15" To="1.0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="PART_MainContainer"/>
             </Storyboard>
            </VisualState>
            <VisualState x:Name="Hidden">
             <Storyboard>
              <DoubleAnimation Duration="0.00:00:00.15" To="0.15" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="PART_MainContainer"/>
             </Storyboard>
            </VisualState>
           </VisualStateGroup>
           <VisualStateGroup x:Name="SelectionStates">
            <VisualState x:Name="Unselected">
             <Storyboard>
              <DoubleAnimation Duration="0.00:00:00.2" To="0" Storyboard.TargetProperty="X" Storyboard.TargetName="PART_ExplodeTransform"/>
              <DoubleAnimation Duration="0.00:00:00.2" To="0" Storyboard.TargetProperty="Y" Storyboard.TargetName="PART_ExplodeTransform"/>
             </Storyboard>
            </VisualState>
            <VisualState x:Name="Selected">
             <Storyboard>
              <DoubleAnimation Duration="0.00:00:00.2" Storyboard.TargetProperty="X" Storyboard.TargetName="PART_ExplodeTransform"/>
              <DoubleAnimation Duration="0.00:00:00.2" Storyboard.TargetProperty="Y" Storyboard.TargetName="PART_ExplodeTransform"/>
             </Storyboard>
            </VisualState>
           </VisualStateGroup>
          </VisualStateManager.VisualStateGroups>
          <Ellipse Clip="{TemplateBinding FigurePath}" Height="{TemplateBinding ItemActualHeight}" Style="{TemplateBinding ItemStyle}" StrokeThickness="0" Width="{TemplateBinding ItemActualWidth}"/>
          <Path x:Name="PART_DefiningGeometry" Data="{TemplateBinding FigurePath2}" Fill="Transparent" Style="{TemplateBinding ItemStyle}" Stroke="{x:Null}"/>
          <Ellipse Clip="{TemplateBinding FigurePath3}" Fill="{StaticResource PieMaskBrush}" Height="{TemplateBinding ItemActualHeight}" Width="{TemplateBinding ItemActualWidth}" Visibility="Collapsed"/>
         </Canvas>
        </ControlTemplate>
       </Setter.Value>
      </Setter>
     </Style>


The only thing that is not metro is the LegendItem. It is not giving the entire chart a metro look. Let's style the Legend as well :) You can check my nextpost to see how to style the Legends. Keep watching this space for more!!

Friday, January 27, 2012

Adding a Marker point on Telerik chart


I was thinking how to add a marker on a telerik chart. After doing a lot of research I found that there is a layer in the ChartArea to add MarkedZones. However, this did not allow me to add a marker image and it had entirely a different usage. Please check the telerik site  to know more about the MarkedZones. There might be other ways to do what i wanted to, but this is the approach which i took...
A marked zone is actually a rectangle which takes up the chart coordinates and creates a rectangle using them.  So, all we have to do is create a rectangle with the x and y points of the chart and fill the resulting rectangle with an image brush.Simple!!! :)
Here is the code to create a MarkedZone on chart item Click

Code:
 MarkedZone markedZone = new MarkedZone();
            markedZone.StartY = e.DataPoint.YValue;
            markedZone.EndY = e.DataPoint.YValue + ((Axis)(((((ChartArea)(sender)))).AxisY)).ActualStep;
            markedZone.StartX = e.DataPoint.XValue;
            markedZone.EndX = e.DataPoint.XValue + ((Axis)(((((ChartArea)(sender)))).AxisX)).ActualStep;
            BitmapImage bitmap = new BitmapImage(new Uri("/Pointer.png", UriKind.RelativeOrAbsolute));
            ImageBrush imageBrush = new ImageBrush();
            imageBrush.AlignmentX = AlignmentX.Left;
            imageBrush.AlignmentY = AlignmentY.Bottom;
            imageBrush.Stretch = Stretch.None;
            imageBrush.ImageSource = bitmap;
            markedZone.Background = imageBrush;
            LineChart.DefaultView.ChartArea.Annotations.Add(markedZone);



All I have done is create a rectangle using the coordinates and used image brush to fill it... the result was like this.

Now that our pointer is in place lets work to make it look beautiful. As you can see the pointer is just behind the label or item point mark. It is because the layer for marked zone(PART_AnnotationLayer) is below the layer for the item point mark(PART_LabelsPanel). All we have to do now is change the layers by styling the chart area. You can see how it is done here. Once that is done here is what it looks like..

Tuesday, January 24, 2012

Preloader in Silverlight (Part III) : Bottle filling up animation

Many a times we come across a situation where we need to create an attractive preloader which resembles filling up of a bottle. For eg. If you have a site for some beverage company, it makes complete sense to create its preloader in the form of a bottle filling up to the top. This will be equally creative and will keep the users attention while your service is busy doing the usual data pick up tasks.


Creating a bottle filling up animation is quite simple. All you have to do it show the user that something is going up the bottle. Though you may choose several ways to show this, I choose the simplest way of changing the color of the liquid (path) inside the bottle from transparent to yellow.


First we need an empty bottle. You may get a png empty bottle image for this. I have created a path for this. It is easily created in Expression Design. You may check out my last post to see how we can create complex paths. My path will look like this,




Once my bottle was ready i created one more path in the shape of the bottle till the neck which had a Z-Index lesser than the bottle. This path will act as my liquid inside.


To create a liquid rising effect I filled the path with a LinearGradientBrush, with one gradient stop completely transparent and other gradient stop with a golden yellow color. I just changed the gradient stops gradually which gave the liquid rising effect.




The whole animation was as simple as changing the color stops. J


All you need to create an animation is just imagination. You may download the application from here



To cut an image in Microsoft Expression Design

Expression Design is an amazing tool to create designs and images. However, people in the industry say it’s nowhere close to Adobe Photoshop. I would say though it is not as strong as Photoshop but it has some really cool features. We can very well design a complete site in it. I use this tool to design everything from e-cards to images for a complete website. Best part of it is to export the design elements in the form of XAMLs. We can very well copy these paths and create lite Silverlight applications which can be configured.


The only thing that I find very difficult to do in Expression design is cutting a complex image which is really very useful at times. I have tried a lot to do it many a times and end up going to a Photoshop guy to get it cut for me. But recently I have found a way to cut images in Expression design. I find it interesting and easy.


For example if you want to cut a bird from an image(I am using a nice bird wallpaper :)) you may do it the following simple steps,


1.       Export the image in Expression Design canvas. You may use Ctrl+E or simply drag the image on to the canvas.


2.       Right click the Pen tool to open up the various options available. And find the Polyline  or B-Spline tool. A Polyline will typically create straight line paths and the B-Spline will create curved paths.





3.       For now use the B-Spline and create anchor points around the desired object, in my case the bird. By this you are basically tracing the image.


4.       If you will color the traced path with a solid color it will look like this.





5.       Now choose an image fill from the color pallet.


6.       Click on the import button in the pallet to choose the parent image, in my case the bird image.
7. On replacing the image in it, the path will be filled with the image brush.




8.       Now simply adjust the image by giving transforms to the image brush.




9.       You may adjust the height and width percent according to your path. Adjust the X and Y transform to get it to the desired position.


10.   Export this and your image is ready J

Tuesday, February 9, 2010

Preloader in Silverlight (Part II)

In my previous post I showed you how to create simple preloader. Let’s take it to the next level and create a circular preloader. Circular preloaders are very common and can be seen everywhere. You can Download Source Code here and use it as a usercontrol in your project or add it as a new project. Now keep your users busy watching your animation while you are busy fetching data! Keep watching this space for more such preloaders.


Sunday, January 17, 2010

Slide Show in Silverlight


When my friends come and ask me how to start with Silverlight, I always point them to http://silverlight.net/ But when they ask me to give them some kind of a task so that they can have hands on, then I always tell them to make a simple slide show. Slide show is a thing which is very easy and which can be made equally complex. I find that from the making of this simple show to its conversion to a complex carousel, we get to learn Silverlight and in turn gain confidence over it.


For a beginner it’s always good to start with some static images put in some layout element, when we explore further to see what will be the best container for a stack of images we in turn explore different layouts. Then to make things look better and to add a Silverlight touch to it, I tell them to add little animations on mouse over and out events. Then I tell them to add few buttons and control the slide show using them. By now they ask me how they can do the entire thing dynamically. Then a series of events and changes are done on the same old slide show and in the end a wonderful carousel is made. If you are a beginner in Silverlight then I would suggest you to start learning it by making a slide show. People have made thousands of slide shows but each has a different touch. Here is my version for you to start with.


In this I am locally maintaining an XML that has links to images of some cute dogs. I am reading this xml and then displaying them in the age old filmstrip fashion. To read the xml I have used Linq. The slide show is controlled by a pair of forward and backward buttons.







So, now when everything is all set, why don’t you Download Source Code and get started!

Sunday, January 10, 2010

Reading xml from a SharePoint server

Every now and then we have to send and receive data through an xml or an RSS feed. Some of these xml files can be kept somewhere at the server or can be kept locally. If the xml is stored at a different location then you have to write a web service that would call it and put a Client access policy there. I had a requirement to read an xml file stored at a sharepoint server. Here is how I have done it without web services.
List<string> itemDetailsList = new List<string>();
 
List<string> itemTitleList = new List<string>();
 
List<string> itemSourceList = new List<string>();
 
private XNamespace z = "#RowsetSchema";
 
public MainPage()
 
{
 
InitializeComponent();
 
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
 
}
 
void MainPage_Loaded(object sender, RoutedEventArgs e)
 
{
 
//this xml path will be kept at a SharePoint server and the uri will have the address of the SharePoint Server.
 
Uri absUrl = new Uri("http://yourSite/_vti_bin/owssvr.dll?Cmd=Display&List=%7BCA37%2D7F%2D408CBF6%2D059D&XMLDATA=TRUE", UriKind.RelativeOrAbsolute);
 
WebClient xmlClient = new WebClient();
 
xmlClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(xmlClient_DownloadStringCompleted);
 
xmlClient.DownloadStringAsync(absUrl);
 
}
 

 
void xmlClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
 
{
 

 
if (e.Error == null)
 
{
 
XDocument doc = XDocument.Parse(e.Result.ToString());
 
var docNode = from item in doc.Descendants(z + "row")
 
select new
 
{
 
ItemTitle = item.Attribute("ows_NameOrTitle") == null ? string.Empty : item.Attribute("ows_NameOrTitle").Value,
 
ItemDetails = item.Attribute("ows_Details") == null ? string.Empty : item.Attribute("ows_Details").Value,
 
ItemSource = item.Attribute("ows_RequiredField") == null ? string.Empty : item.Attribute("ows_RequiredField").Value
 
};
 
foreach (var itemContent in docNode)
 
{
 
itemTitleList.Add(itemContent.ItemTitle);
 
itemDetailsList.Add(itemContent.ItemDetails);
 
itemSourceList.Add(itemContent.ItemSource);
 
}
 
}
 
else
 
{
 
MessageBox.Show("error while reading from the server");
 
}
 
}