Monday, 27 August 2012

Creating Charts with the Google Chart API


I've always wondered how the phrase "A picture is worth a thousand words" came about. I like to think that it was coined by some mid-level manager viewing a sales figures report that consisted of metrics from the past 1,000 days. After scanning this long list of numbers, he found, at the bottom of the page, a line chart that summarized the numbers, and uttered that now well-known adage. Charts and graphs provide a succinct synopsis of large amounts of data. With charts a person can quickly spot trends, compare different resultsets, or recognize patterns.

2008 Sales by Quarter There are many ways to create charts in an ASP.NET web page. You can use the classes in the System.Drawing namespace to programmatically generate charts; you can use the Microsoft Office Web Components (OWC). There are also open-source charting tools and a plethora of third-party components, as well.

Microsoft has even entered the game and introduced Microsoft Chart Controls for the .NET Framework 3.5 SP1.
This article looks at how to use the Google Chart API to create charts. The Google Chart API is a free service from Google that enables web developers to generate chart images on the fly by creating an <img> element with a src attribute that points to a URL that includes the chart data, labels, and other information in the querystring. For instance, the chart on the right is available at the URL,30,70,25&chl=Q1|Q2|Q3|Q4&chtt=2008%20Sales%20By%20Quarter.

Read on to learn how to use the Google Chart API in your ASP.NET website!

An Overview of the Google Chart API

The Google Chart API allows developers to generate various types of charts on the fly. The Google Chart API is hosted as a URL on Google's web servers and when a properly formatted URL is sent, an image of a chart is returned. The chart's details - the colors, title, axes, data points, dimensions, and so forth - are specified via the URL's querystring. The resulting image can be displayed using an <img> element or may be stored on your web server's file system or in a database for later use, if needed. Best of all the Google Chart API is free to use and does not require any sort of account or sign up process! The base URL for the Google Chart API is: The parameters that define the chart's layout follow after the ? character. There are a variety of parameters that you can specify through the querystring. The only required parameters are the chart size (chs), the chart data (chd), and the chart type (cht). The following table summarizes some of the more germane parameters:
Google Chart API Options
chtThe chart type. Google offers around a dozen different chart types, including line charts, bar charts, pie charts, and others.
chsThe chart size. This value is expressed as chs=WIDTHxHEIGHT, where WIDTH and HEIGHT are the number of pixels wide and tall to draw the chart. E.g., chs=250x100. The maximum height and width is 1,000 pixels, and the product of the height and width cannot exceed 300,000 pixels.
chttThe chart title.
chdThe chart data. When using this parameter you must specify the data format. The Google Chart API allows for different data encodings. The simplest to use is text encoding and is denoted by the letter t. Following the encoding place a colon (:) and then a comma-delimited list of data point values. The default text encoding requires that the data points be floating point values between zero (0.0) and one hundred (100.0). To correctly scale the data convert each data point into a percentage of the largest data point. Ergo, the largest value will have a value of 100.0, whereas the others will be expressed in terms of a percentage of the largest - 50.0 for one that's half as large as the largest, 25.0 for one that's 25% of the largest, and so forth. To render a chart with data points of 10, 20, and 8, you'd send: chd=t:50,100,40. Note the t:, which indicates that the data is formatted using text encoding.
You can alternatively use the text encoding method with data scaling, which allows data points of any positive or negative floating point number. With this approach you must specify a scaling parameter (chds). The examples in this article use the default text encoding, limiting all data point values between zero and one hundred.
Using the above information you can tinker with creating your own charts using the Google Chart API. For instance, the following URL generates a line chart that's 300x200 pixels in dimension with data points 43, 23, 12, 62, 34, and 39, and a title of, "Monthly Traffic":,37.1,19.4,100.0,54.8,62.9&chtt=Monthly%20Traffic. Note that the data points sent in the chd parameter are not the literal data points - 43, 23, 12, 62, 34, and 39 - but are instead the percentages of the largest data point. In other words, the literal data point x is turned into the percentage data point by doing (x / maxDataPoint) * 100. For example, literal data point 43 turns into 43/62 * 100 = 69.3.
Put this URL in an <img> tag like in the markup below:
<img src=",37.1,19.4,100.0,54.8,62.9&chtt=Monthly%20Traffic" />
And you get the following results:

Pretty snazzy, eh? Granted, the chart is very simple, but creating it took about 1.5 seconds of effort. Not a bad trade-off. And if you spend some time exploring the Google Chart API options you'll find parameters that you can use to specify colors, add axes, labels, and other standard chart accouterments. For example, we can include numerical values on the Y axis to illustrate the number of hits and date values along the X axis by updating the URL to use the following querystring: ?cht=lc&chs=300x200&chd=t:69.3,37.1,19.4,100.0,54.8,62.9&chds=0,62&chtt=Monthly%20Traffic&chxt=x,y&chxl=0:|1st|7th|14th|21st|31st&chxr=1,0,62. And here are the results:

Generating a Google Chart From Database Data In An ASP.NET Page

With a little bit of work it is possible to generate a chart based on database data using the Google Chart API. We simply need to construct the appropriate querystring based on the data to be plotted, the type of chart, and the X and Y axis labels (if any). The remainder of this article looks at building the querystring in an ASP.NET web page for a database query that returns sales amount per month for the Northwind Traders company. You can download the complete working code at the end of this article. The first step is to create the query that returns the data to plot. My demo uses the Northwind database, which maintains information on products, customers, orders, and so on. For this demo I decided to chart the gross sales per month for a given year. The following query returns this information for a specified year:
SELECT MONTH(o.OrderDate) AS MonthVal, SUM(od.UnitPrice * od.Quantity) AS Total
FROM Orders AS o
    INNER JOIN [Order Details] AS od ON
        od.OrderID = o.OrderID
WHERE (YEAR(o.OrderDate) = @Year)
The Northwind database has sales for the years 1996, 1997, and 1998. If you pass in one of these values for the @Year parameter you'll get results like:

The demo specifies the above query in a SqlDataSource control and displays the results on the page in a GridView control. The GridView has been customized to display the results of the Total column formatted as a currency and to format the MonthVal column values as the three-letter month name abbreviation. This MonthVal formatting is handled by a helper function in the code-behind class, DisplayMonthName, which takes in the month as an integer input (1, 2, ..., 12) and returns the formatted value ("Jan", "Feb", ..., "Dec"). I also added a DropDownList control to the page for the user to specify the value of the @Year parameter; the DropDownList has the hard-coded values 1996, 1997, and 1998.

The gross monthly sales for 1997 are displayed in a GridView control.
In addition to the SqlDataSource control, GridView, and DropDownList for the year, the page includes an Image Web control for displaying the chart.

 The Image control's ImageUrl property is programmatically set to the appropriate URL in the code-behind class. This is handled in the DisplayChart method. This method starts by constructing the base portion of the URL - the chart type (cht), chart size (chs), and chart title. The chart type and size are dictated by values selected by the user via two DropDownList controls.

Protected Sub DisplayChart()
   'Build up the chart URL
   Dim chartUrl As New StringBuilder("")

   'Add the chart type
   chartUrl.AppendFormat("cht={0}", Server.UrlEncode(ddlChartType.SelectedValue))

   'Add the chart size
   chartUrl.AppendFormat("&chs={0}", Server.UrlEncode(ddlChartSize.SelectedValue))

   'Add the title
   chartUrl.AppendFormat("&chtt={0}", Server.UrlEncode("Sales for " & ddlYear.SelectedValue))


Next, the SqlDataSource control's Select method is called, returning the results. These results are enumerated and their values are collected into a list of Decimal values (literalDataPointsList) and the labels for each data point - the three-letter month abbreviation - are recorded in a list of string (xAxisLabels). Once the literal data point values have been recorded they are re-expressed as percentages of the largest value and stored in a list of strings called relativeDataPointValues. The values in this list are then concatenated (delimited by commas) and assigned to the chart data parameter (chd). (For more information on using the Select method, read Programmatically Accessing Data using the Data Source Controls.)


   'Add the data points... First, get the data from the SqlDataSource control
   Dim dataPointsView As DataView = CType(dsChartData.Select(DataSourceSelectArguments.Empty), DataView)
   Dim xAxisLabels As New List(Of String)
   Dim literalDataPointsList As New List(Of Decimal)
   Dim maxValue As Decimal = 0

   'Read in the data points and store the maximum value
   For Each point As DataRowView In dataPointsView
      'Remove any cents from the amount

      'See if we have a new maximum
      If literalDataPointsList(literalDataPointsList.Count - 1) > maxValue Then
         maxValue = literalDataPointsList(literalDataPointsList.Count - 1)
      End If

      If ddlChartSize.SelectedIndex <> 0 OrElse literalDataPointsList.Count Mod 2 = 1 Then
      End If

   'Compute the relative data point values
   Dim relativeDataPointValues As New List(Of String)
   For Each point As Decimal In literalDataPointsList
      Dim relativeValue As Decimal = (point / maxValue * 100)

   'Add the points to the URL
   chartUrl.AppendFormat("&chd=t:{0}", String.Join(",", relativeDataPointValues.ToArray()))


Finally, the labels for the X and Y axis are specified. The Y axis extends from 0 to the maximum value returned by the query, whereas the X axis data points are loaded from the xAxisLabels list. Finally, the Image control's ImageUrl property is assigned the value of the URL that has been built up.


   'Add two axes

   'Add the range for the Y axis
   chartUrl.AppendFormat("&chxr=1,0,{0}", maxValue.ToString("0"))

   'Add the Labels for the X axis
   chartUrl.AppendFormat("&chxl=0:|{0}", String.Join("|", xAxisLabels.ToArray()))

   'Load the chartUrl "image" in the imgChart Image control
   imgChart.ImageUrl = chartUrl.ToString()
End Sub

The net result can be seen in the screen shots below. The first screen shot shows the gross sales for 1996 in a line chart; the second one shows the sales for 1997 in a bar chart.

The 1996 gross sales are shown in a line chart.

The 1997 gross sales are shown in a bar chart.


The Google Chart API offers a quick and easy way to generate a number of different chart types on the fly for your website. To generate a chart simply request the Google Chart API URL passing along details about the chart - its dimensions, data points, colors, labels, and so on - via the querystring. The Chart API returns an image which you can then display in an <img> element. With a little bit of work it's possible to generate this charting URL from an ASP.NET web page so as to display a chart based on database data. In this article we saw how to manually construct the URL; a future article will look at a custom control that supports declarative databinding and other nifty features.

A Google Chart API Custom Server Control


 Over the past week I built such a Web control. The Web control does not provide the full suite of Google Chart API features - it only allows for the creation of line, bar, and pie charts, and it only allows a single data series - but it makes creating and displaying data-driven charts as easy as drag-and-drop and point-and-click. This article shows how to use this free custom server control and highlights some of its more interesting aspects. You can download the compiled server control, its complete source code, and a demo application at the end of this article. Read on to learn more!

An Overview of the Chart Control in the skmControls2 Library

After writing last week's article, in which I wrote 50+ lines of code that showed how to use Google Chart API to display a chart based on database data, I decided there had to be an easier way to show a simple chart. Ideally, a developer could drag a chart control from the Toolbox onto an ASP.NET page, set a few properties to indicate things like the chart type, size, and color, and then specify the chart's data in a number of different ways:
  • By binding the chart to a data source control, such as a SqlDataSource or ObjectDataSource control,
  • Specifying hard-coded chart data statically in the page's markup, or
  • Specifying the chart data programmatically
A number of built-in ASP.NET Web controls implement this pattern. For instance, the DropDownList control has a variety of properties that can be used to specify its appearance, and the data displayed in the DropDownList can be specified statically, programmatically, or from a data source control. I wanted to build a similar control, but instead of emitting a drop-down list the control would instead output an <img> element with its src attribute set to the appropriate URL to generate the chart with the given data. I created a custom server control named Chart that is part of my skmControls2 library, a collection of custom server controls for ASP.NET version 2.0 and up. Other controls in the skmControls2 library include an enhanced GridView control, a data bound Label control, and a TextBox word and character counter control. You can download the latest version of the skmControls2 library, along with a demo application, at the end of this article.
The Chart control is used in the following manner: a page developer adds the Chart control to an ASP.NET page. She can then configure appearance-related properties like ChartType, Height, Width, LineColor, ChartTitle, and others. Next, the page developer would specify the chart's data as a series of data points. Each data point has two attributes:
  • Value - the data point value
  • Label - the text label associated with the data point
This series of data points is stored in the Chart control's Items collection. The values of the Items collection can be expressed in three different ways:
  • Statically - you can specify the data points through the declarative markup of the Chart control. For instance, to create a chart with data points labeled Q1, Q2, Q3, and Q4 with values 45, 21, 88, and 34, respectively, you could use the following declarative markup:
    <cc1:Chart ID="StaticChart" runat="server">
       <cc1:DataPoint Value="45" Label="Q1"></cc1:DataPoint>
       <cc1:DataPoint Value="21" Label="Q2"></cc1:DataPoint>
       <cc1:DataPoint Value="88" Label="Q3"></cc1:DataPoint>
       <cc1:DataPoint Value="34" Label="Q4"></cc1:DataPoint>
  • Programmatically - the Items collection is a collection of objects of type DataPoint. You can programmatically create these objects and add them to Items. Here's a snippet of code that adds the four data points shown above, but does so programmatically rather than statically.
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
       If Not Page.IsPostBack Then
          DynamicChart.Items.Add(New DataPoint("45", "Q1"))
          DynamicChart.Items.Add(New DataPoint("21", "Q2"))
          DynamicChart.Items.Add(New DataPoint("88", "Q3"))
          DynamicChart.Items.Add(New DataPoint("34", "Q4"))
       End If
    End Sub
  • Via Data Binding - you can bind the Chart control to a data source control and the Chart will treat each record returned by the data source control as a data point. To use this technique you must tell the Chart control what column in the data source control constitutes the data point value; you can optionally specify what column constitutes the label. Use the DataValueField and DataLabelField properties to provide this information.
ASP.NET server controls whose output depends on data and whose data can be specified through a data source control are referred to as data bound controls. All such classes extend the BaseDataBoundControl class, which defines the base functionality for such controls. Another class in the .NET Framework, DataBoundControl, fleshes out the BaseDataBoundControl class, implementing some of the essential data binding logic and adding the DataMember property. Consequently, the Chart control extends the DataBoundControl class. (This article does not explore the art of creating data bound server controls. For more information on this topic check out A Crash Course on ASP.NET Control Development: Building Data-Bound Controls.)
The DataBoundControl class includes a method named PerformDataBinding that is executed in cases where the control is bound to a data source control and this data is needed. The PerformDataBinding method is passed an object that implements IEnumerable, which is the data returned by the data source control's Select() method. Custom server controls that extend DataBoundControl typically override this method to provide the logic for rendering the underlying data. The Chart control overrides this method and uses it to populate its Items collection, as the following code snippet illustrates:
protected override void PerformDataBinding(System.Collections.IEnumerable data)
   ... Some code removed for bevity ...

   foreach (object point in data)
      DataPoint item = new DataPoint();

      if (this.DataLabelField.Length > 0 || this.DataValueField.Length > 0)
         if (this.DataLabelField.Length > 0)
            item.Label = DataBinder.GetPropertyValue(point, this.DataLabelField, this.DataLabelFormatString);
         if (this.DataValueField.Length > 0)
            item.Value = DataBinder.GetPropertyValue(point, this.DataValueField).ToString();
         item.Value = point.ToString();

When the Chart control is rendered it renders as an <img> element with its src attribute assigned the appropriate URL to render the chart using the Google Chart API. The precise HTML element that is rendered by a Web control depends on the value of its TagKey property. Because we need the Chart control to render as an <img> element (as opposed to a <span> or <input>) the TagKey property is overridden to return the appropriate element type:
protected override HtmlTextWriterTag TagKey
      return HtmlTextWriterTag.Img;
Whenever a Web control is rendered its AddAttributesToRender method is invoked, which is responsible for adding any attributes within the HTML element. The Chart control overrides this method so that it can translate the data in the Items collection (and the various appearance-related property settings) into the appropriate URL for the src attribute.
protected override void AddAttributesToRender(HtmlTextWriter writer)


writer.AddAttribute(HtmlTextWriterAttribute.Src, CreateChartUrl());

   ... Some Code Omitted for Brevity ...
As you can see from the above snippet of code, the src attribute is set to the value returned by the CreateChartUrl method. This method, shown below, constructs the complete Google Chart API URL and querystring based on the control's properties and the data in the Items collection.
protected virtual string CreateChartUrl()
   StringBuilder sb = new StringBuilder(500);
   // Add base Url

   // Add chart type

   // Specify chart height & width
   sb.AppendFormat("&chs={0}x{1}", chartWidth.Value, chartHeight.Value);

   // Add the title, if present
   if (!string.IsNullOrEmpty(this.ChartTitle))

   ... Some Code Omitted for Brevity ...
   // Specify data

   return sb.ToString();
The CreateChartUrl method starts by creating a new StringBuilder object and adds the value of the UrlBase property (the portion of the Google Chart API URL without the querystring values, It then adds the chart type parameter (cht), the chart dimensions (chs), and so on. The values for these parameters are pulled from the values of the control's properties. A number of other querystring parameter assignment statements have been omitted from the above snippet for the sake of brevity. The most important step is specifying the chart data (chd). The Items collection has a method named RenderRelativeCHDValues that returns the values in the collection in the format required by the chd querystring parameter. As discussed in last week's Creating Charts with the Google Chart API article the values for the chd parameter, when specified using text formatting, should be a comma-delimited list of values between 0 and 100 where the largest data point has a value of 100 and all other data points are expressed as a percentage of the largest. This computation is handled within the RenderRelativeCHDValues method.
The net result is that the Chart control renders an <img> element with an appropriate src attribute, just like we did in last week's article. But instead of having to create that src attribute ourselves, the Chart control does that for us. All we have to do is set a few properties and specify the data to plot.

Using the Chart Control in an ASP.NET Page

The download available at the end of this article includes the complete source code for the Chart control, as well as a demo ASP.NET website. To use the skmControls2 controls in an ASP.NET website, copy the DLL to the website's Bin directory and then add the following @Register directive to the tops of the .aspx pages where you want to use the controls:
<%@ Register Assembly="skmControls2" Namespace="skmControls2.GoogleChart" TagPrefix="cc1" %>
(Alternatively, you can add this @Register directive in the Web.config file so that you do not need to add it to every ASP.NET page that uses the controls. See Tip/Trick: How to Register User Controls and Custom Controls in Web.config.)
Next, add the following markup to the page:
<cc1:Chart ID="MyChart" runat="server" />
You can now go to the Design view and see its properties, bind it to a data source control, and so on.
(You can also add the control to your Toolbox in Visual Studio by: right-clicking on the Toolbox; selecting Choose Items; going to the Browse tab; and browing to the skmControls2.dll assembly. Once added to the Toolbox you can add the Chart control to a page by dragging it from the Toolbox onto the page's Design surface or declarative markup portion.)
The demo for download at the end of this article includes three Chart control examples. Two of them (GoogleChartDemo.aspx and GoogleChartDemo2.aspx) use AccessDataSource controls to display category sales data from the Northwind database. The following screen shot shows is from GoogleChartDemo2.aspx. There are two TextBox controls in which the user can filter the dates. Upon entering dates and clicking the "Refresh Data" button the page shows the results in a GridView control as well as in the Chart control. This functionality is possible without having to write a single line of code!

The Chart control, in action.
Note that in the line chart the names of the categories overlap a bit. You could fix this by increasing the width of the chart or by formatting the category names so that they only include the first few letters. GoogleChartDemo.aspx shows how to programmatically format the chart's data in this fashion.
The third demo (GoogleChartDemo3.aspx) contains a chart whose data is constructed programmatically. In particular, this third demo enumerates the files in the web application's root directory and sums up the total file size for each unique file extension. It then displays this data in a pie chart. As you can see by the screen shot below, there are four unique file extensions - .aspx, .vb, .config, and .png - with .aspx files comprising more disk space than all of the other file types combined.

This pie chart shows the total file size by file type in the web application.


The Google Chart API offers a free and easy way to generate charts - simply craft an appropriately formatted URL, put it in the src attribute of an <img> element, and, voila, you have a chart on your web page. Unfortunately, there's a bit of work involved in constructing the querystring. Rather than having to memorize the assorted querystring parameters or toil writing code to generate that query, it would be easier to use a custom server control that did all that for us. The Chart control in the skmControls2 Library is such a control and, as we saw in this article, is can be used to generate simple charts using the Google Chart API. Happy Programming!

Thank you 

original author By Scott Mitchell

Saturday, 25 August 2012

Learn TFS basic (Team Foundation Server) /What is Team Foundation Server?

What is Team Foundation Server?

With Visual Studio Team System (VSTS), Microsoft has made accessible an integrated set of tools, used by associate of the development team. Each associate play one or multiple roles. One can vary easily imagine roles of Business Analyst, Project Manager, Technology Solution Architect, Developer, tester and Release Manger. These roles use different tools which go with them. For example Developers over the years have used Visual Studio to create code and Project Managers use MS Project for creating, monitoring and controlling a project. All the tools utilize by diverse roles work on the same data which makes them integrated. These tools also need to access some services for managing the data. The data gathering and the general services are provided by a server component of VSTS which is called Team Foundation Server.

Team Foundation Server (TFS)
TFS is the spirit of VSTS. It drives the required data and provides required services to the diverse client applications. It let all the associate members to collaborate with each other. It is a server which includes some of the most excellent software technologies created by Microsoft like ASP.NET 2.0, Windows SharePoint Services, SQL Server 2005 etc.

Logical Architecture
TFS is a multilayered server. It is divided in the layers of Data Layer and Application Layer.

The data layer and the application layer can be on the same machine if the number of customers is less than 20.
Data layer is implemented in SQL Server 2005. When TFS is installed it generates quantity of database and tables for maintaining the data of the users, work items, source control and other resources. Being implemented on SQL Server 2005, data layer provides outstanding scalability and performance.
Application layer is implemented through set of services which are existing over the network. Most of them are configured as webservices which makes them possible to be right to use even over the Internet.

Physical Architecture
It is possible to generate single tier architecture for installations which do not require high scalability. It is suggested that for any non-trivial installation the data layer and the application layer should be on different servers to gather the scalability and reliability requirements. For meeting the requirements of teams which are geographically spread and coupled through internet, TFS provides the capability to use proxy to accomplish the requirements of remote users. Although proxy will be caching the source code, main source control where changes are allowed to be stored is where the main installation of TFS is. It is also recommended to have a separate build server since the build activity is very highly CPU rigorous. Keeping the main TFS and build server on same machine with frequent builds may hinder the act of TFS badly.

The main set of services offered by TFS is to improve group effort between multiple users.

Source Code Control (SCC)
SCC is the major contributor to Software Configuration Management. SCC in TFS includes normal version control, Branching, Merging, Shelving and Unshelving etc. TFS preserve the source control in SQL Server 2005. By default it allows multiple check-outs. We can set locks in such a way that either the locked files cannot be checked out or if they are checked out they cannot be checked in. TFS also supports check-in policies which make it mandatory on the team members to accomplish certain actions when they are checking in some source code.
SCC also works as a point of junction between the team project and the technological solution. Team project allows for architecture, association, watch and control of the project. The technological solution does not involve itself with project management or versioning etc. Every unit of source code to be generated is tagged with a work item. Work item store the management data about the technological unit. Storage and management of work items is done through SCC.
Project Portal
For every panel project TFS make a SharePoint portal site. This site contains sections for Process guidance, Reports and documents. It provides appropriate authorization to provider, person who reads and visitors. Through the process guidance we can learn about the process template that is selected for the project. Various reports provide the physical condition and growth of the project. Clients can have a come across at the reports even across the Internet for status monitoring.
Work Item Tracking
Work items are tagged collected data on behalf of some abstract entities like task, bug, Quality of Service Requirement etc. We need to monitor status of each of these entities. At the same time each work item and entity pair will belong to a user at any given moment. The user will work upon the entity like task or bug and then either set the status of the work item to close or re-assign it to some other user for further work on the entity. TFS keeps track of status of each work item and the user who owns that work item at that time.
Build Automation
 Each developer executes the application in his / her workspace on the local machine. After execution the code is checked in the source code control. The checked in code has to be built to ensure its interoperability with code created at other time, maybe, by some other developers. This build process should be carried out once in a while to ensure truthfulness of all the checked in code. TFS allows creation of build at pre-determined time using a component called Team Build. Team build schedules the build script created using MS-Build to be executed at the predetermined time.
TFS uses a separate data store to generate reports. There are number of predefined reports as per the process template which is fashioned by default. TFS uses SQL SERVER 2005 Reporting Service to create these reports. Each report indicates either of status of the project, quality of the software which progress of the project. These reports are based upon work items, source code, test results and builds. The status and progress of each is originally stored in the normalized tables in the database. TFS creates the non-normalized way in in the data warehouse for the use of creating reports. Reports Data Warehouse object model let developers to create custom reports in the form of .rdl files using report designer. These reports can also be made accessible through the reports site.

How to add Sound Effects, Music and Video to your Silverlight App.

Add three buttons to your Silverlight and three MediaElements control to our MainPage.xaml.

The first button is for playing music, second is for sound, and the third for video.

Copy and paste following code to MainPage.Xaml

    <Grid x:Name="LayoutRoot" Background="White">
        <Canvas Background="AliceBlue">
            <Button Click="Button_Click_Music" Canvas.Left="10" Canvas.Top="10" Width="80" Height="30" Content="Play Music"></Button>
            <Button Click="Button_Click_Sound" Canvas.Left="100" Canvas.Top="10" Width="80" Height="30" Content="Play Sound"></Button>
            <Button Click="Button_Click_Video" Canvas.Left="200" Canvas.Top="10" Width="80" Height="30" Content="Play Video"></Button>
            <MediaElement x:Name="MySoundFile" Source="aerobics.mp3" AutoPlay="False"></MediaElement>
            <MediaElement x:Name="MymusicFile" Source="dance.mp3" AutoPlay="False"></MediaElement>
            <MediaElement Width="300" Height="300" Canvas.Top="100" x:Name="MyVideoFile" AutoPlay="False" Source="seeVideo.wmv"></MediaElement>

Copy and paste following code to MainPage.Xaml.cs
    public partial class MainPage : UserControl
        public MainPage()
        private void StopAll()

        private void Button_Click_Music(object sender, RoutedEventArgs e)

        private void Button_Click_Sound(object sender, RoutedEventArgs e)

        private void Button_Click_Video(object sender, RoutedEventArgs e)

.Play() Method will Play your Mediaelement.

.Stop() Method will Stop your Media

AutoPlay="True" will set the media in play mode by default.

Convert to html page to PDF

The tool that really help me to do this is iTextSharp, a C# implementation of the iText open source java library for controlling PDF files, and the fact that you can use javascript within the PDF file . Below is the code that explain you how to use an ASPX page which manipulates and streams the PDF file into a zero-height, zero-width IFrame to keep away the user from manipulating the PDF in any way.  You also need to embed the JavaScript into the PDF, which will run once the document is loaded and pops up the Print dialog from Adobe Reader. 

The JavaScript for printing a PDF is not so complex, I embedded it into a function:

protected string GetMyAutoPrintJs()
    var script = new StringBuilder();
    script.Append("var kk = getPrintParams();");
    script.Append("kk.interactive = kk.constants.interactionLevel.full;");

    return script.ToString();

In the code-behind for the ASPX page that will stream the PDF and place the script inside the PDF file, I built this function:

protected void StreamMyPdf(Stream pdfSource)
    var outputMyStream = new MemoryStream();
    var pdfReader = new PdfReader(pdfSource);
    var pdfMyStamper = new PdfMyStamper(pdfReader, outputMyStream);
    //Add the auto-print javascript
    var writer = pdfMyStamper.Writer;

    var content = outputMyStream.ToArray();
    Response.ContentType = "application/pdf";

The PDFReader and PdfMyStamper classes are associated with the iTextSharp library. You can use the classes together to get the stream for output and also access to PDFWriter object that allowed me to add the JavaScript.

How to animate a rotating image in Silverlight

Each Silverlight element has a property called RenderTransform that is used to set the transform information that affects the loading position of the element.This article deals with rotating image in silverlight.

First, declare the image in our Page.xaml. To rotate the image around its center, set the CenterX and CetnerY to be the center coordinates of the image which. In my case the image I am using is 128x96 pixels so the center is set at CenterX=64, CenterY=48.

In Page.XAML replace <Grid></Grid> with the following:

<Canvas Background="Black">
    <Image x:Name="busyIndicatorLogo" Source="images/ busyIndicatorLogo.png">
            <RotateTransform x:Name=" busyIndicatorLogoTransform" CenterX="64" CenterY="48"></RotateTransform>

We perform the transform around the center of the image which is 64, 48 since the image is 128x96 in size. For each frame, we increment the angle by one.
namespace SilverlightApp
    public partial class Page : UserControl
        public Page()

            CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);

        void CompositionTarget_Rendering(object sender, EventArgs e)
            busyIndicatorLogoTransform.Angle += 1;
            busyIndicatorLogoTransform.Transform(new Point(64, 48));

Create an application that stores a file in Windows Azure storage

Windows Azure Platform

Here I am going to create a console application that uses the Windows Azure Storage Services API. This sample code will upload a file to the Windows Azure Blob service.
 To create an application that uploads a file to a blob

  • Go to Microsoft Visual Studio 2010.
  • Click the File menu, click New, and add new Project.
  • Within the New Project dialog, navigate to Installed Templates, Visual C#, and click Windows.
  • Click Console Application. Name the project as Storageapp. Don’t forget to choose .NET Framework 4 from the drop down list and click ok.
  • From the Storageapp Project menu, click Add Reference. Within the Browse to where your Windows Azure SDK reference libraries are installed, making sure to use the latest version. For example, C:Program FilesWindows Azure SDKv1.4 ef.  Select Microsoft.WindowsAzure.StorageClient.dll and click OK (Note: if you don't have latest version please install it from Micorsoft website).
  • Copy and paste the following code to contain the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace StorageApp
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.StorageClient;

    namespace Storageapp
        class Program
            static void Main(string[] args)
                    CloudStorageAccount mynewcloudStorageAccount;
                    CloudBlobClient mynewblobClient;
                    CloudBlobContainer mynewblobContainer;
                    BlobContainerPermissions containerPermissions;
                    CloudBlob blob;

                    // Use the local storage account.
                    mynewcloudStorageAccount = CloudStorageAccount.DevelopmentStorageAccount;

                    // If you want to use Windows Azure cloud storage account, use the following
                    // code (after uncommenting) and comment above code.
                    // mynewcloudStorageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;;");

                    // Create the blob client, which provides
                    mynewblobClient = mynewcloudStorageAccount.CreateCloudBlobClient();

                    // Get the container reference.
                    mynewblobContainer = mynewblobClient.GetContainerReference("mynewcontainer");
                    // Create the container if it does not exist.

                    // Set permissions on the container.
                    containerPermissions = new BlobContainerPermissions();
                    containerPermissions.PublicAccess = BlobContainerPublicAccessType.Blob;

                    // Get a reference to the blob.
                    blob = mynewblobContainer.GetBlobReference("mynewmyfile.txt");

                    // Upload a file from the local system to the blob.
                    Console.WriteLine("Starting file upload");
                    blob.UploadFile(@"c:mynewmyfilesmynewmyfile.txt");  // File from local storage.
                    Console.WriteLine("File is uploaded to " + blob.Uri);
                catch (StorageClientException e)
                    Console.WriteLine("Storage client cause an : " + e.Message);

                    // Exit the application with exit code 1.
                catch (Exception e)
                    Console.WriteLine("Error : " + e.Message);

                    // Exit the application with exit code 1.
                    // Exit the application.


  • Create a file on your local computer named c:mynewmyfilesmynewmyfile.txt .
  • blob.UploadFile(@"c:mynewmyfilesmynewmyfile.txt ");  // File from local storage.
  • Go to All Programs, click Windows Azure SDK v1.4, and click Storage Emulator.
  • On the Debug menu, click Start Without Debugging. Copy the URI displayed by the application to your browser, you can able to see the file saved in the local storage.
  • You can also store the file into Windows Azure storage account, instead of to your local storage account. In Program.cs comment the following code
  • // mynewcloudStorageAccount = CloudStorageAccount.DevelopmentStorageAccount;
  • And Uncomment the following code
  • mynewcloudStorageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;;");

please visit the following msdn link for more details:

Happy coding..

Do not use "using" for WCF Clients

Conventionally using() block disposes WCF clients wrongly when there's a communication exception, eg disconnecting network connection. It lift exception during the dispose and thus the resources held by the WCF client aren't released properly. This will result into memory leaks.
 C# and Wcf Performance
As we know that any IDisposable object must be disposed using “using” keyword. So, you have been using “using” to wrap WCF service’s ConnectionFactory and Clients like this:
using(var client = new ConClient()) {

Or, if you are doing it the hard and slow way (without really knowing why), then:
using(var factory = new ConFactory<IConService>()) {
var con= factory.CreateCon();

That’s what we have learnt while working in .Net? its not fully right?
When there’s a network related error or the connection is disconnected, or the service is expired before Dispose is called by the using keyword, then it results in the following exception when the using keyword tries to dispose the con;
failed: System.ServiceModel.CommunicationObjectFaultedException :
The communication object, System.ServiceModel.Cons.ServiceCon,
cannot be used for communication because it is in the Faulted state.
    Server stack trace:
    at System.ServiceModel.Cons.CommunicationObject.Close(TimeSpan timeout)
    Exception rethrown at [0]:
    at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
    at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
    at System.ServiceModel.ICommunicationObject.Close(TimeSpan timeout)
    at System.ServiceModel.ClientBase`1.System.ServiceModel.ICommunicationObject.Close(TimeSpan timeout)
    at System.ServiceModel.ClientBase`1.Close()
    at System.ServiceModel.ClientBase`1.System.IDisposable.Dispose()

There are various causes for which the fundamental connection can be at disconnected before the using block is finished and the .Dispose() is raised. Common problems like network connection disconnection. Do NOT use using on WCF Con/Client/ConFactory. Instead you need to use an alternative. First create an extension method.
public static class WcfMyExtensions
    public static void Using<T>(this T myclient, Action<T> work)
        where T : ICommunicationObject
        catch (CommunicationException e)
        catch (TimeoutException e)
        catch (Exception e)

Then use this instead of the “using” keyword:
new ConClient().Using(con => {
    con.Login(username, password);

Or if you are using ConFactory then:

new ConFactory<IConService>().Using(con => {   
    con.Login(username, password);

How to change Theme dynamically in SilverLight 4

This article will show how you can change Themes in Silverlight  dynamically at runtime.
Available themes in SilverLight are-

1)Bubble Creme
2)Bureau Black
3)Bureau Blue
4)Expression Dark
5)Expression Light
6)Rainier Orange
7)Rainier Purple
8)Shiny Blue
9)Shiny Red
10)Twilight Blue
11)Whistler Blue

To implement the Themes for the MainPage.xaml .Follow the following Steps:

1)Make sure you have added all the Theming dlls which are available in April2010 silverlight Toolkit. You can download this toolkit from

2)Copy and paste following code in Views/Home.xaml
In the below code add the following two xml namespaces
xmlns:local="clr-namespace:newApp" (‘newApp’ is the assembly name of Silverlight project)

<navigation:Page x:Class="newApp.Home"
    xmlns:d="" xmlns:mc=""
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480"
    Style="{StaticResource PageStyle}" xmlns:sdk="">

    <Grid x:Name="LayoutRoot">
            <local:ThemeChangeCommand x:Key="themeCommand" />
        <Button Content="New Theme" Height="23" HorizontalAlignment="Left" Margin="60,111,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
        <ScrollViewer x:Name="PageScrollViewer" Style="{StaticResource PageScrollViewerStyle}">

            <StackPanel x:Name="ContentStackPanel">

                <TextBlock x:Name="HeaderText" Style="{StaticResource HeaderTextStyle}"
                <TextBlock x:Name="ContentText" Style="{StaticResource ContentTextStyle}"
                                   Text="Home page content"/>
                <ListBox Height="100" Name="listBox1" Width="120" />
                <CheckBox Content="CheckBox" Height="16" Name="checkBox1" />
                <RadioButton Content="RadioButton" Height="16" Name="radioButton1" />
                <TextBlock Height="23" Name="textBlock1" Text="TextBlock" Width="119" />
                <ComboBox Height="23" Name="comboBox1" Width="120" />



3)Add one Class called   ThemeChangeCommand.cs  for handling the requests.
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Controls.Theming;

namespace newApp
        public class ThemeChangeCommand : ICommand
            #region ICommand Members

            public bool CanExecute(object parameter)
                return true;

            public event EventHandler CanExecuteChanged;

            public void Execute(object parameter)
                Theme themeContainer = (Theme)((FrameworkElement)Application.Current.RootVisual).FindName("ThemeContainer");

                string themeName = parameter as string;

                if (themeName == null)
                    themeContainer.ThemeUri = null;
                    themeContainer.ThemeUri = new Uri("/System.Windows.Controls.Theming." + themeName + ";component/Theme.xaml", UriKind.RelativeOrAbsolute);

                if (CanExecuteChanged != null)
                    CanExecuteChanged(this, new EventArgs());


4)The job is done. Press F5 and once the page is loaded Right-Click on the MainPage to get the Context Menu having the list of available themes .Click on the Theme of your choice and then you can see all the controls according to the new Theme. See the below screen shot for more details

Populating Silverlight Chart on clicking on Legend Items

To get single graph on clicking on to legend Items

In the following article we will add three areaseries to a chart. On clicking to each LegendItem we can get that particular legend series.

Please add the refrence of following assembly

Create a class YearlyCarSold.cs and copy and paste following code

public class YearlyCarSold
        private string _Year;
        private int _NoOfCars;

        public YearlyCarSold(string year, int cars)
            _Year = year;
            _NoOfCars = cars;

        public string Year
            get { return _Year; }
            set { _Year = value; }

        public int NoOfCars
            get { return _NoOfCars; }
            set { _NoOfCars = value; }


Create another class SeriesData.cs  and copy and paste following code

public class SeriesData
         public List<YearlyCarSold> GetSeriesData(string val,int k)
            List<YearlyCarSold> list = new List<YearlyCarSold>();
            list.Add(new YearlyCarSold("2002" + val, 8000 + k));
            list.Add(new YearlyCarSold("2003" + val, 9000 + k));
            list.Add(new YearlyCarSold("2004" + val, 10000 + k));
            list.Add(new YearlyCarSold("2005" + val, 11000 + k));
            list.Add(new YearlyCarSold("2006" + val, 12000 + k));
            list.Add(new YearlyCarSold("2007" + val, 9000 + k));
            list.Add(new YearlyCarSold("2008" + val, 500 + k));
            list.Add(new YearlyCarSold("2009" + val, 1000 + k));
            return list;

Now Create a MainPage.xaml
<UserControl x:Class="bargraph.MainPage"
    d:DesignHeight="300" d:DesignWidth="400">
        <Style x:Key="LegendItemStyle" TargetType="toolkit:LegendItem">
            <Setter Property="IsTabStop" Value="False" />
            <Setter Property="Template">
                    <ControlTemplate TargetType="toolkit:LegendItem">
                        <CheckBox Click="CheckBox_Click" Cursor="Hand" IsChecked="true" Content="{TemplateBinding Content}" Tag="{TemplateBinding Content}">
                                <ControlTemplate TargetType="CheckBox">
                                    <StackPanel Orientation="Horizontal">
                                        <Rectangle Width="8" Height="8" Fill="{Binding Background}" Stroke="{Binding BorderBrush}"
                                                   StrokeThickness="1" Margin="0,0,3,0" />
                                        <datavis:Title Content="{TemplateBinding Content}" />
                                <ToolTip Content="Click to hide/show."></ToolTip>
    <Grid x:Name="LayoutRoot">
        <toolkit:Chart x:Name="chartSample" Background="Silver"  BorderBrush="Black" BorderThickness="3" UseLayoutRounding="False" >

And  Copy and paste following code in MainPage.xaml.cs
   public partial class MainPage : UserControl
        public MainPage()
            Loaded += new RoutedEventHandler(MainPage_Loaded);

        void MainPage_Loaded(object sender, RoutedEventArgs e)
            System.Windows.Controls.DataVisualization.Charting.Compatible.ColumnSeries perf1 = GetMethod("1", 1);
            System.Windows.Controls.DataVisualization.Charting.Compatible.ColumnSeries perf2 = GetMethod("2", 2);
            System.Windows.Controls.DataVisualization.Charting.Compatible.ColumnSeries perf3 = GetMethod("3", 3);
                chartSample.Title = "Last 24 Hours Disk Utilization (% Total Available Free Space)";//% Used Space)";

                // this.chartSample.Legend = legend1;

            catch (Exception ex)
                throw ex;

        System.Windows.Controls.DataVisualization.Charting.Compatible.ColumnSeries GetMethod(string k, int l)
            SeriesData seriesData = new SeriesData();
            // COLUMNSERIES
            System.Windows.Controls.DataVisualization.Charting.Compatible.ColumnSeries perf = new System.Windows.Controls.DataVisualization.Charting.Compatible.ColumnSeries();

            // System.Windows.Controls.DataVisualization.Charting.Compatible.BarSeries perf = new System.Windows.Controls.DataVisualization.Charting.Compatible.BarSeries();            //System.Windows.Controls.DataVisualization.Charting.Compatible.ColumnSeries perf = new System.Windows.Controls.DataVisualization.Charting.Compatible.ColumnSeries();

            //UNCOMMENT FOR LineSeries//
            //System.Windows.Controls.DataVisualization.Charting.Compatible.LineSeries perf = new System.Windows.Controls.DataVisualization.Charting.Compatible.LineSeries();

            //UNCOMMENT FOR PieSeries//
            //PieSeries perf = new PieSeries();

            //UNCOMMENT FOR PieSeries//
            // System.Windows.Controls.DataVisualization.Charting.Compatible.ScatterSeries perf = new System.Windows.Controls.DataVisualization.Charting.Compatible.ScatterSeries();
            perf.Name = k;
            perf.IsSelectionEnabled = true;

            perf.ItemsSource = seriesData.GetSeriesData(k, l);
            perf.IndependentValueBinding = new System.Windows.Data.Binding("NoOfCars");
            perf.DependentValueBinding = new System.Windows.Data.Binding("Year");
            //perf.TransitionDuration = new TimeSpan(0, 0, 5);
            perf.Title = k;
            Style style = this.Resources["LegendItemStyle"] as Style;
            perf.LegendItemStyle = style;

            return perf;

           private void CheckBox_Click(object sender, RoutedEventArgs e)
            CheckBox chk = (sender as CheckBox);

            System.Windows.Controls.DataVisualization.Charting.Compatible.ColumnSeries ls = this.chartSample.Series.Cast<System.Windows.Controls.DataVisualization.Charting.Compatible.ColumnSeries>().Where(s => s.Title.ToString() == chk.Tag.ToString()).ElementAtOrDefault(0);

            chartSample.Series.Clear(); // Clears the chart
            chartSample.Series.Add(ls); // Add Single series

            // Uncomment to check for all three graph
            //if (chk.IsChecked.Value)
            //    chk.Opacity = ls.Opacity = 1;
            //    chk.Opacity = 0.5;
            //    ls.Opacity = 0;

And that’s it….enjoy playing with graph…