RadGrid

RadGrid and SqlDataSource control – Be Careful with your DataSource choice

Overview:

This blog post is in response to one of the customer queries we received a couple of days back. One of our India customer called us up and said that they are seeing slowness in couple of pages where they are using RadGrid. Problem statement was – when they click on “Add New Row” button it takes nearly 1.5 minutes for the row to appear on the grid. This made it even scary for them as they had moved the code to production. Through this blog post I will try to outline what I found out and what could have been done better to resolve the problem.

Analysis:

I went in to a call with the customer and took a look at their code. There were couple of things they were doing. Let me list them down:

  • DataSource for the RadGrid was a SqlDataSource control defined in the .ASPX page
  • They were handling OnItemCommand and OnItemDataBound. They had some logic in this method which would execute on every data bound and every item command
  • The new item template had lot of drop down lists and each of them were bound to SqlDataSource control as their data source.

Now, next thing I did was to take look at the timing. We used IE Developer Tools and captured the network traffic when Add New button was clicked. What I found out was, server was taking close to 10 seconds to finish its server side processing. That’s a lot of time if you ask me. What was surprising for them was, they had paging enabled on the grid. So they were thinking that paging is happening correctly but still why is the add new row scenario slow.

So this made me to delve little bit deeper into what exactly is happening in this scenario. So rest of this blog post is all about my observation. Read on if you have faced a similar problem.

Observations:

Did two experiments to figure out what was happening. First I use a RadGrid and bind it to SqlDataSource control and look at the query executed at the DB side. Second was to use entity data source instead of SQL data source and look at the query executed at the DB.

For my experiments I am using Northwind Database and in particular Order Details table. Order Details table contains nearly 2155 records. So this makes a good candidate to mimic a scenario where you are paging the RadGrid lets say 10 records per page.

I assume that you have RadControls for ASP.NET AJAX suite installed on your system. If not, you can always download from our products page – www.telerik.com/products/aspnet-ajax.aspx. You will need that if you want to follow along with this post. Also in order to trace the SQL Queries executed, I am making use of a open source tool called “Express Profiler” which is available at CodePlex here: http://expressprofiler.codeplex.com/. I had to use this as I have a SQL Server 2012 express edition and express edition does not come with Profiler option. You need a full blown SQL server to get the profiler.

I have created a RadControls Web Application for my experiments. When you install the RadControls for ASP.NET AJAX suite, you will get project templates in Visual Studio, using which you can create a web application.

SNAGHTML47a123f

Fig 1: RadControls Web Application Project Template

DataBinding with SqlDataSource control:

First experiment was placing a RadGrid and bind it to SqlDataSource control. I placed a RadGrid and set its basic properties.  Then added a SqlDataSource control to the page and set its connection string and provided a select command. Here is the code snippet for grid and SQL data source control:

 
    <telerik:RadGrid ID="RadGrid1" runat="server" 
                     DataSourceID="SqlDataSource1" 
                     AllowPaging="true" AllowSorting="true" 
                     AllowFilteringByColumn="true" AllowAutomaticInserts="True"
                     MasterTableView-EditMode="InPlace"  
                     MasterTableView-CommandItemDisplay="TopAndBottom" />
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                       ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
                       ProviderName="System.Data.SqlClient" 
                       SelectCommand="SELECT * FROM [Order Details]" />

Analyzing the queries:

Now, before you run the application, lets get ready to trace the SQL queries that get executed. You should have downloaded the Express Profiler. Start the express profiler – Set the server details, select the authentication mechanism and finally select the events you want to trace. Here is the screen shot:

SNAGHTML4aaebbd

Fig 2: Express Profiler Settings

Run the web application. Notice that if we just set AllowPaging=true on RadGrid and do not provide a page size, by default RadGrid puts 10 as the PageSize. So in my case I should see only 10 rows on my first page of the RadGrid. Here is the Grid output:

image

Fig 3: RadGrid output

When I ran the app and looked at the trace, here is what I get:

SNAGHTML4af9b0f

Fig 4: SQL Query Trace for SQL Data Source Control bound to RadGrid

What you see here is a call to retrieve all the records from the table. You may be asking but the page size is set to 10. That is correct but what really happens is this: RadGrid will go ahead and ask SQL Data Source to get the data. SQL Data Source will blindly execute the query that has been set for the select command. RadGrid will not be able to do any tinkering with query because the SQL Data Source does not provide us a chance to put paging related statements.

Now lets do a page change on the grid. I will go ahead and click on Page 2.  RadGrid will now navigate to Page 2. Here is the trace that is generated for this:

SNAGHTML4c8b053

Fig 5: SQL Trace for Page Change Event

What you notice is, the SQL Data Source goes ahead and brings all the records from the table. RadGrid will then pick up only the second page rows and displays it.

Now lets go ahead and click on the Add New Row button and trace the query executed:

SNAGHTML4cdbf80

Fig 6: SQL Trace for Add New Record Event

As you can see it again retrieves all the records from the table.

What this tells us is the time taken is due to the fact that its going and getting all the table records no matter whatever is the situation we have. Now hitting DB and getting everything does call for some time although small but it till takes up time on the server.

Now lets do the same experiment but with Entity Data Source.

DataBinding with Entity Data Source:

I will use the same data grid but instead of SQL Data Source I will use a Entity Data Source. In order to work with Entity Data Source, you need a Entity Data Model. I will not get into how to create a Entity Data Model but assume that you know how to do it. Just create a ADO.NET Entity Data Model and generate the models from the database and use the same Northwind database. Once you have the ADO.NET Entity Data Model created, create a Entity Data Source on the page. Here is the Entity Data Source code snippet that I have:

 
<asp:EntityDataSource ID="EntityDataSource1" runat="server" 
                          OnContextCreating="EDS_ContextCreating" 
                          EntitySetName="Order_Details" />

I am making use of the OnContextCreating event to set the DbContext of ADO.NET Data Model to Entity Data Source ObjectContext. Here is the code for the event handler of OnContextCreating:

 
protected void EDS_ContextCreating(object sender, EntityDataSourceContextCreatingEventArgs e)
{
    var db = new NORTHWINDEntities();
    e.Context = (db as IObjectContextAdapter).ObjectContext;
}

Here NORTHWINDEntities is my Entity Data Model context. I am just casting it to ObjectContext since Entity Data Source works with ObjectContext. I set this entity data source as the data source of the RadGrid.

Analyzing the Queries:

Now lets run the app and trace SQL queries for the same set of actions we did with SQL Data Source control.

First, on page load:

SNAGHTML509e74c

Fig 7: Entity Data Source – Page Load – Query Trace

As you can see we have put in a “SELECT TOP 10” statement in the query. So its not bringing all 2155 records rather only 10 records. So time spent to do this will be very negligible. We also execute one additional query to get the total record count.

Now lets see what happens when we do a paging:

SNAGHTML50e4016

Fig 8: Entity Data Source – Paging – Query Trace

Now, lets trace the query when we do ‘’Add new record” scenario:

SNAGHTML50fd88d

Fig 9: Entity Data Source – Add New Record – Query Trace

Notice that, in this scenario, we automatically page to the last row and add a blank record.

As you can see from the above experiments, RadGrid is intelligent enough to optimize the queries based on the scenario you are dealing with.

Conclusion:

It was very evident from the experiments that if you are using SQL Data Source as your data source choice, there is not much RadGrid can do to optimize the query before it gets executed. Where as with Entity Data Source, RadGrid is smart enough to optimize the query and always have a optimized data fetch. I personally recommend using an ORM in the project for the data access scenarios and use the Entity Data Source as your data source choice. We i.e at Telerik have a free ORM called OpenAccess. Its free for life so you can pretty much use this in your production without any hassle at all. Do give it a try and let us know how you feel about it.

I hope this blog post does give you information on things you need to take care while doing data binding to Grids. This is just not in particular to RadGrid, this is mostly about any data binding scenario. Trace your queries and be sure that write and optimized queries are getting executed in your apps.

Till next time, Happy Coding.

RadHtmlChart

How to bind RadHtmlChart for ASP.NET AJAX to EntityDataSource control

Introduction:

This is the 3rd blog post in the series on RadHtmlChart, our HTML5 based charting control for ASP.NET AJAX and its data binding options. So far we have seen data binding the RadHtmlChart control with SQLDataSource and LinqDataSource. In this blog post we will look at one more data binding option namely binding to EntityDataSource.

In this blog post we will focus on how to create a EDM or entity Data Model using Entity Framework, then adding the EntityDataSource control to the web page and finally binding it to the RadHtmlChart. For the rest of this post it is assumed that you have already installed our RadControls for ASP.NET AJAX suite and also our free ORM called OpenAccess.

About EntityDataSource:

EntityDataSource is a control that was made available during the days of Visual Studio 2008 SP1 i.e. .NET 3.5. According to MSDN EntityDataSource control is defines as:

A control which can be used together with a data-bound control to retrieve data from an EDM and to display, edit, and sort data on a Web page by using little or no code.

I wont be spending too much time on discussing EntityDataSource control in this blog post. I suggest you to go through the overview article from MSDN available here: http://msdn.microsoft.com/en-us/library/cc488502.aspx. The article will get you up to speed with the EntityDataSource control.

Getting Started:

To start with, lets create a “C# RadControls Web Application”. Open a Visual Studio and navigate to File > New Project > Telerik > Web and select “C# RadControls Web Application”. Give it a name & click finish so that VS can go ahead and create the project for us.

SNAGHTML13df131b

Figure 1: New Project Dialog

Adding ADO.NET Entity Data Model:

Entity Data Source control requires a ADO.NET Entity Data Model to work with. Entity Data Source can be configured to work with a Entity Data Context for reading, creating, updating and deleting data with little or no code from the web page. In order to create a EDM, we need to first add Entity Framework bits to our project. Use the Nuget Package Manager to add a package named EntityFramework.

SNAGHTML1424992c

Figure 2: Nuget Package Manager

One of the best practice is to create a Models folder at the root of the web application. So lets create a folder called Models. Right click on the Models folder and select Add > New Item. In the new item dialog, under Data category select “ADO.NET Entity Data Model”, give it a name and click Add.

SNAGHTML142c24a9

Figure 3: Add New Item Dialog

Next we will be presented with a EDM Wizard. In the interest of the time, I will post my settings in the wizard as a serious of images below:

SNAGHTML142e40e0

Figure 4: Entity Data Model Contents

SNAGHTML142f47a3

Figure 5: Data Connection

SNAGHTML1430a6f2

Figure 6: Database objects

Once we finish with the wizard, NorthwindEntityDataModel.edmx is created in the Models folder. Double clicking that we will be presented with a visual designer with one object called Product placed. Remember we had selected only one Table for this demo called Product. Here is the screen shot of the EDMX designer:

image

Figure 7: EDMX Designer

Now that we have the EDM created, next is to add the Entity Data Source control to the page.

Adding Entity Data Source Control:

Open Default.aspx page and add EntityDataSource control to the page. You can either drag and drop the entity data source control from toolbar and you can write the declarative code by hand. I will drag and drop it from the toolbox onto the page. Use the Entity Data Source control smart tag (either from the ASPX page or from the designer) to configure data source settings. Here is my settings for the data source:

SNAGHTML144def19

Figure 8: Object Context Configuration

SNAGHTML144ee98e

Fig 9: Data Selection Configuration

When we finish the configuration wizard, following code will be generated by the Visual Studio

 
<asp:entitydatasource id="NorthwindEntityDataSource" runat="server" 
defaultcontainername="NORTHWINDEntities" connectionstring="name=NORTHWINDEntities" 
enableflattening="False" entitysetname="Products" 
entitytypefilter="Product" 
select="it.[ProductName], it.[UnitPrice]">
</asp:entitydatasource>

Note that we couldn’t add the top 10 keywords when configuring using the wizard and also there was no way to provide the orderby clause. In order to specify the top keyword just prepend “top(10)”  to the Select text. EntityDataSource supports OrderBy property. So add the property and provide the value “it.UnitPrice DESC”. Here is the final code:

 
<asp:EntityDataSource ID="NorthwindEntityDataSource" runat="server"
                DefaultContainerName="NORTHWINDEntities"
                ConnectionString="name=NORTHWINDEntities"
                EnableFlattening="False"
                EntitySetName="Products"
                EntityTypeFilter="Product"
                Select="top(10) it.[ProductName], it.[UnitPrice]"
                OrderBy="it.UnitPrice DESC" >
            </asp:EntityDataSource>

Add RadHtmlChart:

You can add a RadHtmlChart either by dragging and dropping from the toolbox onto the page or by writing the declarative code on the page. I will be dragging and dropping the control on to the page. Following 3 things need to be taken care while data binding to a EntityDataSource. They are:

  • DataSourceID: Set the DataSourceID property of the RadHtmlChart to the name of the Entity Data Source you want to bind to.
  • DataFieldY: Set the DataFieldY property of the data series to the column name from which the data points have to plotted on the Y axis. I am plotting the UnitPrice on the Y axis so I will set the DataFieldY property to “UnitPrice
  • DataLabelsfield: Set the DataFieldsLabel property of the XAxis to the column name from which we need the X axis data points to be plotted. I am having the products name on the XAxis so I will set the DataLabelsField property to “ProductName”.

Here is the complete code for the RadHtmlChart:

 
<telerik:RadHtmlChart ID="RadHtmlChart1" runat="server" 
                DataSourceID="NorthwindEntityDataSource" 
                Height="600px" Width="1000px">
                <ChartTitle Text="Top 10 Products By Price">
                    <Appearance>
                        <TextStyle FontSize="16px"></TextStyle>
                    </Appearance>
                </ChartTitle>
                <Legend>
                    <Appearance Position="Top">
                    </Appearance>
                </Legend>
                <PlotArea>
                    <Series>
                        <telerik:ColumnSeries Name="UnitPrice" DataFieldY="UnitPrice">
                        </telerik:ColumnSeries>
                    </Series>
                    <XAxis DataLabelsField="ProductName">
                        <LabelsAppearance RotationAngle="90" />
                        <MinorGridLines Visible="false" />
                        <MajorGridLines Visible="false" />
                    </XAxis>
                    <YAxis>
                        <TitleAppearance Text="Price" />
                        <MinorGridLines Visible="false" />
                    </YAxis>
                </PlotArea>
            </telerik:RadHtmlChart>

Here is the output of the chart:

image

Figure 10: RadHtmlChart Output

Summary:

In this post we looked at one more data binding technique with RadHtmlChart. We looked at EntityDataSource, how to configure entity data source and finally how to bind it with RadHtmlChart. With just 3 things to take care its very easy to bind the chart with entity data source. Hope this makes you excited to start working with RadHtmlChart. Do let us know your experience with the RadHtmlChart.

Till next time – Happy Coding !

RadHtmlChart LinqDataSource

How to bind LinqDataSource to RadHtmlChart for ASP.NET AJAX

Introduction:

RadHtmlChart which is a charting component in RadControls for ASP.NET AJAX suite supports binding to variety of data sources. In this post we will look at a scenario where we will see how to bind the RadHtmlChart to LinqDataSource. So the rest of this post is about how to achieve databinding linq data source to RadHtmlChatrt. So lets get started. First we will look at creating a new project in Visual Studio, then we will add a Data Context to the project, then add a LinqDataSource & use the data context to return top 10 products from Northwind database and finally add RadHtmlChart and see how to use LinqDataSource as the source of the chart.

Creating New Project:

To get started, let’s first create a new “C# RadControls Web Application”. Note you need to have our RadControls for ASP.NET suite installed before you can do this. Open a Visual Studio, select File > New Project > Telerik > Web and C# RadControls Web Application.

imageFigure 1: New Project Dialog

Visual Studio will go ahead and create a Web Application. It will have a single page named Default.aspx. For the rest of the demo, we will work with this page.

Add Northwind Data Context:

In order to work with Linq Data Source, I will create a Entity Data Context using our OpenAccess ORM. OpenAccess is a free tool to download and you can use this in your production too without any licensing involved. First Add New Item to your project of type “Telerik OpenAccess Domain Model”. Give it a name and click Ok.

SNAGHTML20d3224b

Figure 2: Add New Item dialog

You will next be presented with a wizard. Here is the wizard dialog screen shots and the settings I have done:

SNAGHTML20d8441d

Figure 3: OpenAccess Model Type

SNAGHTML20d8e599

Figure 4: Database Connection

SNAGHTML20da3474

Figure 5: Database Items – Products Table Selected

SNAGHTML20dafe38Figure 6: Naming Rules

SNAGHTML20dd52ec

Figure 7: Code Generation Settings

Once you click finish, the wizard will create a .rlinq file in your project. If you double click the rlinq file, you will get a visual designer. For this post I have selected only Products table. So you will see the products table visually laid out:

image

Figure 8: OpenAccess Data Model

Next we will see how to add a LinqDataSource and hook that with our data model to return the products data.

Add LinqDataSource:

In order to add LinqDataSource to your page, you can either drag and drop from the tool box or directly code the tag in the source file. What we will do for this demo is, we will handle a specific event called OnSelecting. In the event handler we will instantiate our OpenAccess data model and return the top 10 products ordered by UnitPrice in descending order. Here is the code which defines LinqDataSource control on the page:

<asp:LinqDataSource ID="LinqDataSource1"
        runat="server"
        OnSelecting="LinqDataSource1_Selecting">
    </asp:LinqDataSource>

Here is the event handler definition:

protected void LinqDataSource1_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
        NorthwindDataModel context = new NorthwindDataModel();
        e.Result = context.Products
                          .OrderByDescending(p => p.UnitPrice)
                          .Take(10);
    }

Now that we have the data model and the linq data source only thing left out is to add the RadHtmlChart and bind it to linq data source.

Add RadHtmlChart:

So now we are ready to add the chart. You can either drag & drop the chart from the toolbox on to the page or code the chart definition directly on the page. In this post I will just add the RadHtmlChart code and highlight the main points you need to take care while wiring it with LinqDataSource.

So here is my chart definition:

<telerik:RadHtmlChart runat="server" ID="RadHtmlChart1"
                DataSourceID="LinqDataSource1" Width="1000" Height="700">
                <PlotArea>
                    <Series>
                        <telerik:ColumnSeries DataFieldY="UnitPrice" Name="Price">
                            <LabelsAppearance>
                                <TextStyle Bold="true" FontSize="15" Color="Orange" />
                            </LabelsAppearance>
                            <TooltipsAppearance Visible="false" />
                        </telerik:ColumnSeries>
                    </Series>
                    <XAxis DataLabelsField="ProductName">
                        <LabelsAppearance RotationAngle="90" />
                        <MajorGridLines Visible="false" />
                        <MinorGridLines Visible="false" />
                    </XAxis>
                    <YAxis>
                        <LabelsAppearance><TextStyle Bold="true" /></LabelsAppearance>
                        <TitleAppearance Text="Units" />
                        <MinorGridLines Visible="false" />
                    </YAxis>
                </PlotArea>
                <Legend>
                    <Appearance Visible="false" />
                </Legend>
                <ChartTitle Text="Top 10 Products by Price">
                </ChartTitle>
            </telerik:RadHtmlChart>

Here are the things you need to do for wiring up the chart with LinqDataSource:

  • On the chart set the DataSourceID property to the ID of the LinqDataSource
  • When you define a series, set the DataFieldY property to a value “UnitPrice”. Here UnitPrice is the column in my data source which I want to bind and plot the points on Y axis
  • On the XAxis definition, set the DataLabelsField property to a value “ProductName”. Here ProductName is the column to which I want to bind and plot the XAxis points.

And that’s all its there to wiring up the RadHtmlChart to LinqDataSource. Now build the project and run to see the output. Here is a screenshot of the chart we just created:

image

Figure 9: RadHtmlChart output

Summary:

In this blog post I wanted to show one of the data binding option that RadHtmlChart supports – namely LinqDataSource. As we have seen it is very easy to create a LinqDataSource and bind it to RadHtmlChart. We just need to take care of 3 things to make the chart work with the LinqDataSource. I hope this blog post gives you a head start if you are working with LinqDataSource and the RadHtmlChart. Do let us know your feedback/comment you may have on this post.

Till next time – Happy Coding.

RadHtmlChart

How to Bind RadHtmlChart for ASP.NET AJAX to SQL Data Source Control

Introduction:

RadControls for ASP.NET AJAX contains a HTML5 powered charting control known as RadHtmlChart. This charting component outputs SVG and is completely client side rendering of the chart. The charting component will output SVG on modern browsers and falls back to VML when running in older browsers. When it comes to data binding the chart, it supports a wide range of data binding mechanism starting from simple array to your custom object collection. In this blog post we will take a look at one of the data binding mechanism namely binding to SqlDataSource.

Pre-Requisites:

In order to follow this post, you will need our RadControls for ASP.NET AJAX suite. You can download a 30 day free trial from http://www.telerik.com/products/aspnet-ajax.aspx. So download the trial and install it on your system. If you already have a licensed version installed that’s even better. Following sections assume that you have done this.

Getting Started:

First lets create a “C# RadControls Web Application”. Fire up a Visual Studio and do the customary File > New Project action. In the new project dialog, you will see Telerik as one of the installed template. Expand Telerik and you will see Web as one of the nodes. Select Web and you will presented with different project templates. Select “C# RadControls Web Application”. Give your project a name and click Ok.

SNAGHTML1665f329Fig 1: New Project Dialog

You will be presented with 2 more dialogs to select theme and web settings. Select appropriately and finish the wizard. Visual Studio will go ahead and create the project.

Adding SQL Data Source to the page:

The project template will add all references required for Telerik ASP.NET Ajax controls, necessary updates to Web.config and create a Default.aspx page. We will be working with Default.aspx for this blog post. Since we need to bind the chart to a SqlDataSource control, lets go ahead and add one to the page. You can configure the data source using the smart tag option in the ASPX page or just go to design and select the smart tag on the control.

image

Fig 2: Configuring SqlDataSource

Clicking on Configure Data Source, will open “Choose Your Data Connection” dialog. So go ahead and set up your connection for the data source. For this example I will be using Northwind as the database and Products table. Once you pass the connection settings dialog, you will be required to configure the select statement. For this demo I will just do a select of top 10 products by their price in descending order. Here is how my test query looks like:

SNAGHTML1678372cFig 3: Test Query Dialog

Click Finish to finish configuring the SqlDataSource. Next we will see how to work with RadHtmlChart.

Adding RadHtmlChart to the page:

From the Toolbox, drag and drop a RadHtmlChart on the page. In the ASPX page, select the smart tag on the RadHtmlChart. It will open a configuration window. We will configure the RadHtmlChart now to work with SqlDataSource control.

image

Fig 4: RadHtmlChart Smart Tasks

Select the DataSource from the Choose Data Source drop down.Then click on the Open Configuration Wizard. You will see the following Configuration Wizard pop up:

SNAGHTML167ef05cFig 5: RadHtmlChart Configuration Wizard

We will go through the configuration one by one.

Chart Type:

For this blog post I will be going with Column chart. So in the Type tab, select Column Chart.

SNAGHTML1680fd76Fig 6: Chart Type selection

Data:

Now to let the chart know where to read the data from, select the Data tab. The data source would have been defaulted to the sql data source we had added in previous section. Now we need to add a series to the chart. Click on the “+” button next to the Series section. Provide Name, AxisName, Type of the series and what field in the data source should the Y axis data point be read from. For this example UnitPrice will be my Y axis data point. I will be plotting the price on the Y axis. Here is how my settings look like:

SNAGHTML1684d53e

Fig 7: Series configuration

X Axis:

Now we need to configure how our X axis will look like. If you want to customize the Min Value, Max Value, Step and Axis Crossing Value or you want to hard code the X axis items, you can do so in the XAxis tab.

SNAGHTML168eec95

Fig 8: XAxis Configuration

Once done with the settings click Apply. Now we need to show the product name as the X axis data point. For that we will need to get back to the code, add a property called “DataLabelsField” and value of this property will be the column name from the data source which will contain the data points. In our case this will be ProductName column. Here is the code:

<XAxis DataLabelsField="ProductName"></XAxis>

Y Axis:

Similar to XAxis you can customize how you want the YAxis to look. The YAxis tab provides you options to customize the axis and also allows you to add additional Y Axis to the chart.

SNAGHTML1694c8e0

Fig 9: YAxis Configuration

In our current example, we don’t have to do anything here. The Min and Max value and Step will be calculated automatically based on the data source.

Legend, Title:

Last but not the least, we can customize how the Legend and the Title of chart should look like. Click on the Legend/Title tab and provide the appropriate data. Here is my settings:

SNAGHTML169795df

Fig 10: Legend, Title Configuration

Click Ok when done. This will generate the following code in the ASPX:

<telerik:RadHtmlChart ID="RadHtmlChart1"
runat="server" DataSourceID="SqlDataSource1">
 <ChartTitle Text="Top 10 Products By Price">
 <Appearance>
 <TextStyle FontSize="16px"></TextStyle>
 </Appearance>
 </ChartTitle>
 <Legend>
 <Appearance Position="Top"></Appearance>
 </Legend>
 <PlotArea>
 <XAxis DataLabelsField="ProductName">
 </XAxis>
 <YAxis Name="Price">
 </YAxis>
 <Series>
 <telerik:ColumnSeries Name="Price"
 DataFieldY="UnitPrice" />
 </Series>
 </PlotArea>
 </telerik:RadHtmlChart>

So we are now done with the RadHtmlChart configuration. We have configured it to work with the Sql Data Source we added in the previous section. We have set what chart we want and configured the series, XAxis, YAxis and Legend/Title. Its time now to look at the output.

Output:

Build and run the project. It should open up a browser and show you the following chart output:

image

Fig 11: RadHtmlChart output

Conclusion:

In this post we saw how easy it is to configure RadHtmlChart to work with Sql Data Source. Also we looked at the RadHtmlChart configuration wizard which makes it super easy to configure the chart with various settings and best of all you don’t have to write any code. The configuration wizard gives you a GUI and when you are done with the settings, it will generate the code for you. I say this is a productivity gainer. Let us know how you are using RadHtmlChart in your projects. We will love to hear your feedback or suggestions. So do drop in a line in the comments.

Till next time, Happy Coding.

RadControls for Silverlight

Silverlight RadCartesianChart: Reading data from WCF Service

Overview:

As part of evangelism job I speak to a lot of customer and try to tell them how they can use our controls. Couple of days back I was speaking one customer who was evaluating our RadControls for Silverlight suite and in particular was working with RadCartesianChart control. He saw all our demos of RadCartesianChart we ship and said that they all provide data from the code behind and are static in nature. They were looking for examples which tell them how to consume data from a WCF service and provide it to RadCartesianChart. So this blog post is all about how do we provide data to ChartView from a WCF Service. So lets get started.

Create RadControls Silverlight Application:

First thing to do, is to create a new project of type RadControls Silverlight Application. I am using Visual Studio 2012 for the rest of this blog post. You can do this in VS2010 too. Open Visual Studio IDE and select File > New Project. In the New Project dialog select Telerik > Silverlight > C# RadControls Silverlight Application. Give a name for the project and click ok.

SNAGHTMLf99013 Fig 1. New Project Dialog

Next, Visual Studio will ask you whether to host the SL app in a new web site and what should be the SL version. I am opting SL Version 5 for the sake of the demo. Here is the screenshot of the dialog:

SNAGHTMLfc02a3

Fig 2. Silverlight Application Settings Dialog

Since we have selected RadControls Silverlight Application, next you will get a “Project Configuration Wizard” where you will select the Components you require in your project. Since I am only interested in Charting, I will select only Telerik.Windows.Controls.Charting and the wizard automatically selects the dependent components for me. Here is the screenshot of the dialog:

SNAGHTML100ba2f

Fig 3: Telerik Project Configuration Wizard – Silverlight Settings Dialog

Clicking next will take you to theme settings. I am selecting Windows8 theme that comes out of the box. Click finish to let Visual Studio create the project.

SNAGHTML1023d24

Fig 4: Telerik Project Configuration Wizard – Theme Settings Dialog

Once Visual Studio finishes creating the project, here is how the solution will look like:

image

Fig 5: Solution Explorer

You can see that we have 2 projects in the solution. One is the actual Silverlight app and another is the Web app which will host the Silverlight XAP. Next we look at how to create a WCF service.

Create WCF Service:

For the sake of the demo, I will be creating a WCF service which does the following things:

  • Create a ProductModel which will act as a DataContract. It will have ProductID, Name and Price as properties
  • Create a WCF Service which will connect to Northwind Database.
  • Have one Operation called GetTop10ProductsByPrice.  This will execute a simple query to fetch top 10 products price wise and convert that into list of ProductModel and return it to client

Product Model Class:

We will create the WCF service in Web App project. We App will host our service too. Create a new folder called “Model” and create the ProductModel class. Here is the code for the ProductModel class:

[DataContract]
public class ProductModel
{
private int productID;
[DataMember]
public int ProductID
{
get { return productID; }
set { productID = value; }
}

private string productName;
[DataMember]
public string ProductName
{
get { return productName; }
set { productName = value; }
}

private decimal price;
[DataMember]
public decimal Price
{
get { return price; }
set { price = value; }
}
}

Chart Data WCF Service:

First create a folder and name it as Services. Right click on Services folder and select Add > New Item. In Add New Item dialog, select Silverlight from installed templates and then Silverlight-enabled WCF Service. Lets name the service as ChartDataService.svc. Click Add to create the service.

SNAGHTML185ec2a
Fig 6: Add New Item dialog

Next, since we need to connect to Northwind database, add a connection string to Web.config in the Web project. I have named my connection string as “NorthwindConnection”.

Next, in the ChartDataService, remove the generated operation contact with name “DoWork”. Instead add a new Operation and lets call it “GetTop10ProductsByPrice”. In this function we will connect to Northwind Database using SQL Connection and execute a simple query. We will loop through the data reader and generate a list of ProductModel and return the list. Here is the code for GetTop10ProductsByPrice operation:

[OperationContract]
        public IList GetTop10Products()
        {
            string nwConn = ConfigurationManager.ConnectionStrings["NorthwindConnection"].ConnectionString;
            var prodList = new List();
            using (SqlConnection conn = new SqlConnection(nwConn))
            {
                const string sql = @"SELECT TOP 10 ProductID, ProductName, UnitPrice
                                     FROM Products
                                     ORDER BY UnitPrice DESC";
                conn.Open();
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    if (dr != null)
                        while (dr.Read())
                        {
                            var cust = new ProductModel
                            {
                                ProductID = dr.GetInt32(0),
                                ProductName = dr.GetString(1),
                                Price = dr.GetDecimal(2)
                            };
                            prodList.Add(cust);
                        }
                    return prodList;
                }
            }
        }

Consuming WCF Service from Silverlight App:

Now that we have a service, next thing to do is to reference that service in our Silverlight application. Right click on Silverlight application and select “Add Service Reference”. In the Add Service Reference window, click on Discover button. The WCF Service we created in the previous section will be automatically discovered and will list down the operation it supports.

SNAGHTML125209f

Fig 7: Add Service Reference Dialog

Now click on the Advanced button located in the bottom left side of the dialog to open the service reference settings dialog. In the Service Reference Settings dialog, under Reuse types in referenced assemblies, select the System related assemblies and not the Telerik ones. Here is a screenshot of the dialog:

SNAGHTML1290d1f
Fig 8: Service Reference Settings Dialog

Clicking Ok will add a service reference in Silverlight app which can be invoked at runtime to fetch the data required for the chart.

Add RadCartesianChart Control:

Next we need to add the ChartView control on the screen. In order to do this, Open MainPage.xaml, identify the ChartView control from the toolbox, drag and drop it on to the MainPage.XAML. Give the chart a name. Here is the code to CartesianChart markup:

<telerik:RadCartesianChart Grid.Row="1" 
                            x:Name="chartView" 
                            Palette="Metro">
    <telerik:RadCartesianChart.VerticalAxis>
        <telerik:LinearAxis Title="Price (USD)"/>
    </telerik:RadCartesianChart.VerticalAxis>
    <telerik:RadCartesianChart.HorizontalAxis>
        <telerik:CategoricalAxis Title="Products"/>
    </telerik:RadCartesianChart.HorizontalAxis>
    <telerik:RadCartesianChart.Series>
        <telerik:BarSeries x:Name="barSeries1" 
                            ItemsSource="{Binding}" 
                            ValueBinding="Price" 
                            CategoryBinding="ProductName" 
                            ShowLabels="True" />
    </telerik:RadCartesianChart.Series>
</telerik:RadCartesianChart>

Lets take a closer look at the code. I first define the vertical axis and tell the chart that it’s a linear axis. I also set title to the vertical axis and call it “Price (USD)” because my vertical axis will hold the price of products. Next, I define horizontal axis and and tell the chart that it’s a Categorical axis. My horizontal axis will be used to represent the product itself, so setting the title of horizontal axis as “Products”. Now that we have finished setting the axis only thing left now is to create a series. So I define Series and create a BarSeries. I have given a name for the bar series and will use this name in code behind to perform data binding. We need to provide the data to the series – so lets set the ItemsSource to the Binding it will get at runtime. Now we need to tell what fields corresponds to the value of the series and what corresponds to the category axis of the series. Set ValueBinding to “Price” field and CategoryBining to “ProductName”.

Data Binding:

We defined the UI part of the chart. Now to provide data to the chart. We had add a service reference to our WCF service earlier. So we will have a client class created in the Silverlight project and will be known as ChartServiceClient. So we will use this client class to invoke the “GetTop10Products” operation. Here is the code to invoke the service and bind the data received to the chart view:

void MainPage_Loaded(object sender, RoutedEventArgs e)
{
            ChartServiceClient client = new ChartServiceClient();
            client.GetTop10ProductsCompleted += client_GetTop10ProductsCompleted;
            client.GetTop10ProductsAsync();
}

void client_GetTop10ProductsCompleted(object sender, GetTop10ProductsCompletedEventArgs e)
{
            var data = e.Result;
            this.chartView.DataContext = data;
}

As you can see we invoke the operation asynchronously. When the operation completes we get the data and set it as the DataContext of the Chart. Run the application and when the page loads we should get the Chart as below:

image

As you can see we get our bar series graph which will show the price (in USD) on the vertical axis and products in the horizontal axis. We see the top 10 products by price.

Conclusion:

In this blog post, what I attempted was a very specific scenario which is most common on real world. As I said in the beginning, the customer I was talking to wanted to see an example of how to connect to a WCF Service, get data from the service and bind that data to Chart. So this blog posts outlines the steps required to make the chart work with WCF Service, Hope this is useful to many of you who may be having the same scenario. Do let me know your feedback if any.

Till next time – Happy Coding!

Windows Azure Mobile Services Data and Telerik RadDataGrid: Two good things together

Learn more about Rad Controls for Windows 8 here

Recently I was in a Windows Azure event for local user group. Attendees were very excited about Windows Azure Mobile Services. When I discussed with them how more immersive and user friendly it could be working with data from Windows Azure Mobile Service Table in Telerik RadDataGrid, they got more excited. In this post we will go very basic and learn basic required steps to fetch data from Mobile Service Data Table in RadDataGrid.

image

If you are new to Mobile Services and Windows Store App development then before you proceed in this post, I recommend you to read these two posts

Step by Step working with Windows Azure Mobile Service Data in XAML based Windows Store Apps

Three Steps to work with RadDataGrid in XAML based Windows Store Application

Video: Getting started with RadDataGrid in XAML based Windows Store Application

Mobile Service Data Table

You can view all Windows Azure Mobile Services and tables by login to Windows Azure Management Portal.

We are going to display data from techbloggers table. I have created this table in Windows Azure Mobile Service as shown below. There are three columns in table. We will display content from techbloggers Mobile Service table in RadDataGrid.

image

We need App URL and key. You need key and application URL to work with Mobile Services from Windows Store application. You will find key and application URL at the portal.

image

Creating Windows Store App

Very first you need to install Windows Azure SDK for Windows 8. You can download that from here . After installing make sure that you have installed RadControls for Windows 8. You can download trial from here

Now go ahead and create a Windows Store App by choosing Blank App project template from Windows Store project tab. After project being created add Rad Controls for Windows 8 reference and Windows Azure Mobile Services Managed Client reference in the project. To add reference right click on Reference in project and select Add Reference.

image

After adding reference on XAML add namespace on MainPage.xaml to work with RadDataGrid


xmlns:telerik="using:Telerik.UI.Xaml.Controls.Grid"

Next add following namespaces on MainPage.xaml.cs to work with Mobile Services client.


using Microsoft.WindowsAzure.MobileServices;
using System.Runtime.Serialization;

Next you need to create entity class representing table from the Windows Azure Mobile Service. Let us create entity class as following. We are creating entity class TechBloggers.


public class TechBloggers
 {
 public int id { get; set; }
 [DataMember(Name = "name")]
 public string Name { get; set; }
 [DataMember(Name = "technology")]
 public string Technology { get; set; }

}

After creating entity class go ahead and add following global variables.


MobileServiceClient client;
IMobileServiceTable<TechBloggers> bloggerstable;

Once global variable is defined in the constructor of page you need to create instance of MobileServiceClient and MobileServiceTable. Let us go ahead and create that in constructor of the page.


public MainPage()
 {

 this.InitializeComponent();
 MobileServiceClient client = new MobileServiceClient("https://youappurl", "appkey");
 bloggerstable = client.GetTable<TechBloggers>();
 }

Next you need to put RadDataGrid on XAML and bind it to data source. RadDataGrid can be created as following


<telerik:RadDataGrid x:Name="BloggerGrid" />

Next you need to bind RadDataGrid to List of Bloggers. List of Bloggers will be fetched from Mobile Service data table. You can do this as following.


protected async override void OnNavigatedTo(NavigationEventArgs e)
 {
 var items = await bloggerstable.ToListAsync();
 this.BloggerGrid.ItemsSource = items;
 }

Next go ahead and run application. You will get records from Mobile Service table bind to RadDataGrid.

image

These are basic steps to fetch data from Windows Azure Mobile Services Table Data and display in RadDataGrid. In further posts we will get into further details of working with these two together. I hope you find this post useful. Thanks for reading.

Learn more about Rad Controls for Windows 8 here

How to work with Images in RadDataGrid in XAML based Windows Store Application

Learn more about Rad Controls for Windows 8 here

Before you start with this post I recommend you to read following blog posts to get it started with RadDataGrid.

Video: Getting started with RadDataGrid in XAML based Windows Store Application

Three Steps to work with RadDataGrid in XAML based Windows Store Application

In this post we will take a look on working with Images as column value in RadDataGrid. As we discussed in this post that there are two types of columns in RadDataGrid.

image

To work with images we need to work with TemplateColumns. TemplateColumn uses DataTemplate to define content of column. To start with let us create business class Product. We will display collection of Products in RadDataGrid. Product class is defined as following. Along with other properties there is a property of Product Image. ProductImage property will hold URL of Image to be displayed for each Products.


public class Product
 {
 public string ProductName { get; set; }
 public double ProductPrice { get; set; }
 public string ProductType { get; set; }
 public BitmapImage ProuctImage { get; set; }
 }

Next let us create collection of Products locally. GetProducts function will return list of Products. We will bind this function as ItemSource of RadDataGrid.


private List<Product> GetProducts()
 {
 List<Product> lstProduct = new List<Product>()
 {
 new Product
 {
 ProductName = "Pen",
 ProductPrice = 100,
 ProductType = "Education",
 ProuctImage = new BitmapImage(new Uri("/ProductImages/Pen.jpg",UriKind.Relative))
 },
 new Product
 {
 ProductName ="Pencil",
 ProductPrice = 50,
 ProductType = "Education",
 ProuctImage = new BitmapImage(new Uri("/ProductImages/Pencil.jpg",UriKind.Relative))

 },
 new Product
 {
 ProductName ="Math Book",
 ProductPrice = 345,
 ProductType = "Education",
 ProuctImage = new BitmapImage(new Uri("/ProductImages/Mathbook.jpg",UriKind.Relative))

 },
 new Product
 {
 ProductName ="Ball",
 ProductPrice = 23,
 ProductType = "Sports",
 ProuctImage = new BitmapImage(new Uri("/ProductImages/Ball.jpg",UriKind.Relative))

 },
 new Product
 {
 ProductName ="Cricket Bat",
 ProductPrice = 560,
 ProductType = "Sports",
 ProuctImage = new BitmapImage(new Uri("/ProductImages/Cricketbat.jpg",UriKind.Relative))

 },
 new Product
 {
 ProductName ="Baseball Bat",
 ProductPrice = 550,
 ProductType = "Sports",
 ProuctImage = new BitmapImage(new Uri("/ProductImages/Baseballbat.jpg",UriKind.Relative))

 },
 };
 return lstProduct;
 }

As of now we have data source in place. Next we need to create RadDataGrid. After creating RadDataGrid we will create DataGridTemplateColumn with DataTemplate. To create RadDataGrid with image as one of the column value we need to follow following steps inside RadDataGrid.

Step 1: Create DataGridTemplateColumn

Step 2: Create DataGridTemplateColumn.CellContentTemplate

Step 3: Create DataTemplate and put Image inside this

We can create RadDataGrid Column with Image in column value as following,

image

We can create columns for each properties in the same way we created for ProductImage property. Final RadDataGrid with columns can be created as following,


<Page
 x:Class="RadDataGridProductDemo.MainPage"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:local="using:RadDataGridProductDemo"
 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 xmlns:telerik="using:Telerik.UI.Xaml.Controls.Grid"
 mc:Ignorable="d">

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
 <telerik:RadDataGrid x:Name="ProductGrid" AutoGenerateColumns="False">
 <telerik:RadDataGrid.Columns>
 <telerik:DataGridTemplateColumn Header="Name" >
 <telerik:DataGridTemplateColumn.CellContentTemplate>
 <DataTemplate>
 <TextBlock Text="{Binding ProductName}"
 VerticalAlignment="Center"
 HorizontalAlignment="Center"/>
 </DataTemplate>
 </telerik:DataGridTemplateColumn.CellContentTemplate>
 </telerik:DataGridTemplateColumn>
 <telerik:DataGridTemplateColumn Header="Photo" >
 <telerik:DataGridTemplateColumn.CellContentTemplate>
 <DataTemplate>
 <StackPanel>
 <Image Source="{Binding ProductImage}"
 Height="100"
 Width="100" />
 </StackPanel>
 </DataTemplate>
 </telerik:DataGridTemplateColumn.CellContentTemplate>
 </telerik:DataGridTemplateColumn>
 <telerik:DataGridTemplateColumn Header="Price" >
 <telerik:DataGridTemplateColumn.CellContentTemplate>
 <DataTemplate>
 <TextBlock Text="{Binding ProductPrice}"
 VerticalAlignment="Center"
 HorizontalAlignment="Center"/>
 </DataTemplate>
 </telerik:DataGridTemplateColumn.CellContentTemplate>
 </telerik:DataGridTemplateColumn>
 <telerik:DataGridTemplateColumn Header="Type" >
 <telerik:DataGridTemplateColumn.CellContentTemplate>
 <DataTemplate>
 <TextBlock Text="{Binding ProductType}"
 VerticalAlignment="Center"
 HorizontalAlignment="Center"/>
 </DataTemplate>
 </telerik:DataGridTemplateColumn.CellContentTemplate>
 </telerik:DataGridTemplateColumn>

 </telerik:RadDataGrid.Columns>
 </telerik:RadDataGrid>
 </Grid>
</Page>

Now go ahead and run application. You will find Product Images as one of the column value.

image

In this way you can work with Images as column value in RadDataGrid. I hope you find this post useful. Thanks for reading.

Learn more about Rad Controls for Windows 8 here

Video: Getting started with RadDataGrid in XAML based Windows Store Application

Learn more about Rad Controls for Windows 8 here

Read content of this video in following blog

Three Steps to work with RadDataGrid in XAML based Windows Store Application

 

 

Learn more about Rad Controls for Windows 8 here

How to set Column Header Style of RadDataGrid in XAML based Windows Store Application

Learn more about Rad Controls for Windows 8 here

RadDataGrid is most important RadControl to create enterprise based Windows Store Application. Currently I have been writing on RadDataGrid and you can read previous two posts at below link,

Part 1: Three Steps to work with RadDataGrid in XAML based Windows Store Application

Part 2: Working with Columns width in RadDataGrid in XAML based Windows Store Application

In this post we will take a look on setting Column Header Style. You can set column header style by configuring value of

image

To start with first you need to add following references on XAML.


xmlns:telerik="using:Telerik.UI.Xaml.Controls.Grid"
xmlns:telerikgridrimitives="using:Telerik.UI.Xaml.Controls.Grid.Primitives"

After adding reference Create RadDataGrid as following. Make sure AutoGenerateColumns property is set to false


<telerik:RadDataGrid
 x:Name="ProductGrid"
 AutoGenerateColumns="False"
 Width="500">
</telerik:RadDataGrid>

After this you need to manually create columns. Create RadDataGrid.Columns inside RadDataGrid.

image

After creating RadaDataGrid.Columns you need to create RadDataGrid.Columns. In columns you can set

  1. Header : Set value of header text
  2. Width : Fixed width of the column
  3. PropertyName : Set this as property name of business object you want to display in this column.

image

In DataGridTextColumn you need to set HeaderStyle. That can be done as following. In below code we are setting

  1. Header Background
  2. Header Fontstyle
  3. Header Fontsize

image

So putting all together you can create RadDataGrid with customized column header as following


<telerik:RadDataGrid
 x:Name="ProductGrid"
 AutoGenerateColumns="False"
 Width="500">
 <telerik:RadDataGrid.Columns>

<telerik:DataGridTextColumn
 PropertyName="ProductName"
 Header="Name"
 Width="200">
 <telerik:DataGridTextColumn.HeaderStyle>
 <Style
 TargetType="telerikgridrimitives:DataGridColumnHeader">
 <Setter Property="Background" Value="SaddleBrown"/>
 <Setter Property="FontStyle" Value="Italic"/>
 <Setter Property="FontSize" Value="20"/>
 </Style>
 </telerik:DataGridTextColumn.HeaderStyle>
 </telerik:DataGridTextColumn>

 <telerik:DataGridTextColumn

 PropertyName="ProductPrice"
 Header="Price"
 Width="50"/>
 <telerik:DataGridTextColumn
 PropertyName="ProductType"
 Header="Type"
 Width="150"/>
 <telerik:DataGridTextColumn
 PropertyName="InStock"
 Header="In Stock"
 Width="100">
 <telerik:DataGridTextColumn.HeaderStyle>
 <Style
 TargetType="telerikgridrimitives:DataGridColumnHeader">
 <Setter Property="Background" Value="Blue"/>
 <Setter Property="FontStyle" Value="Oblique"/>
 <Setter Property="FontSize" Value="20"/>
 </Style>
 </telerik:DataGridTextColumn.HeaderStyle>
 </telerik:DataGridTextColumn>

</telerik:RadDataGrid.Columns>
 </telerik:RadDataGrid>

On running application you will get RadDataGrid with styled column header as following

image

In this post we used some of the discussion from last post so did not discuss about binding and Product class in earlier part of this post. However For your reference find definition of business class Product below


public class Product
 {

 public string ProductName { get; set; }
 public double ProductPrice { get; set; }
 public string ProductType { get; set; }
 public bool InStock { get; set; }
 }

ItemSource of RadDataGrid is set as below,


protected override void OnNavigatedTo(NavigationEventArgs e)
 {

this.ProductGrid.ItemsSource = GetProducts();
 }

GetProducts() class is defined as below,


private List<Product> GetProducts()
 {
 List<Product> lstProduct = new List<Product>
 {
 new Product
 {
 ProductName ="Pen",
 ProductPrice = 100,
 ProductType = "Education",
 InStock = true
 },
 new Product
 {
 ProductName ="Pencil",
 ProductPrice = 50,
 ProductType = "Education",
 InStock = false
 },
 new Product
 {
 ProductName ="Math Book",
 ProductPrice = 345,
 ProductType = "Education",
 InStock = true
 },
 new Product
 {
 ProductName ="Ball",
 ProductPrice = 23,
 ProductType = "Sports",
 InStock = true
 },
 new Product
 {
 ProductName ="Cricket Bat",
 ProductPrice = 560,
 ProductType = "Sports",
 InStock = true
 },
 new Product
 {
 ProductName ="Baseball Bat",
 ProductPrice = 550,
 ProductType = "Sports",
 InStock = false
 },
 };

return lstProduct;
 }

In this way you can work with column header style. I hope you find this post useful. Thanks for reading.

Learn more about Rad Controls for Windows 8 here

Working with Columns width in RadDataGrid in XAML based Windows Store Application

Learn more about Rad Controls for Windows 8 here

In last blog post we learnt to work with RadDataGrid in three simple steps. In this post let us have a look on how we could work with Columns in RadDataGrid. Before we move ahead and understand how to work with columns width and columns header, let us have some understanding on columns in RadDataGrid. There are two kinds of columns in RadDataGrid.

image

TextColumn renders each cell value as System.String object whereas TemplateColumn renders as DataTemplate. In this post we will focus our discussion on TextColumn. It inherits DataGridColumn.

It got following important properties

  1. Header
  2. HeaderStyle
  3. SizeMode
  4. Width
  5. SortDirection

image

We will use Product business object from LAST POST . You will notice in output of last post that RadDataGrid columns were taking default width. Width of column was stretched to maximum. We got output as following

image

Now if you want to set width of each columns you need to follow following steps

Make sure AutoGenerateColumns property is set to false

image

After this you need to manually create columns. In column creation you need to set width of the column. Create RadDataGrid.Columns inside RadDataGrid.

image

After creating RadaDataGrid.Columns you need to create RadDataGrid.Columns. In columns you can set

  1. Header : Set value of header text
  2. Width : Fixed width of the column
  3. PropertyName : Set this as property name of business object you want to display in this column.

image

So putting all together you can create fixed width text column in RadDataGrid as following. We have XAML from previous post. Modified XAML with fixed column width is as following


<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
 <telerik:RadDataGrid
 x:Name="ProductGrid"
 AutoGenerateColumns="False"
 Width="500">
 <telerik:RadDataGrid.Columns>

<telerik:DataGridTextColumn
 PropertyName="ProductName"
 Header="Name"
 Width="200"/>
 <telerik:DataGridTextColumn
 PropertyName="ProductPrice"
 Header="Price"
 Width="50"/>
 <telerik:DataGridTextColumn
 PropertyName="ProductType"
 Header="Type"
 Width="150"/>
 <telerik:DataGridTextColumn
 PropertyName="InStock"
 Header="In Stock"
 Width="100"/>
 </telerik:RadDataGrid.Columns>
 </telerik:RadDataGrid>
 </Grid>

On running application you will get RadDataGrid with fixed column width as following

image

Other important property of column is SizeMode. This property can be set with following three values

image

  1. Width property takes effect only when SizeMode is set to Fixed.
  2. If SizeMode is set to Auto then column takes only width which is required. It overrides value of width.
  3. If SizeMode is set to Strech then column will override width value and stretch to all available space.

image

If you modify above RadDataGrid with setting SizeMode property of fourth column as Auto then RadDataGrid will render as following

image

In this post we used some of the discussion from last post so did not discuss about binding and Product class in earlier part of this post. However For your reference find definition of business class Product below


public class Product
 {

 public string ProductName { get; set; }
 public double ProductPrice { get; set; }
 public string ProductType { get; set; }
 public bool InStock { get; set; }
 }

ItemSource of RadDataGrid is set as below,


protected override void OnNavigatedTo(NavigationEventArgs e)
 {

this.ProductGrid.ItemsSource = GetProducts();
 }

GetProducts() class is defined as below,

private List<Product> GetProducts()
 {
 List<Product> lstProduct = new List<Product>
 {
 new Product
 {
 ProductName ="Pen",
 ProductPrice = 100,
 ProductType = "Education",
 InStock = true
 },
 new Product
 {
 ProductName ="Pencil",
 ProductPrice = 50,
 ProductType = "Education",
 InStock = false
 },
 new Product
 {
 ProductName ="Math Book",
 ProductPrice = 345,
 ProductType = "Education",
 InStock = true
 },
 new Product
 {
 ProductName ="Ball",
 ProductPrice = 23,
 ProductType = "Sports",
 InStock = true
 },
 new Product
 {
 ProductName ="Cricket Bat",
 ProductPrice = 560,
 ProductType = "Sports",
 InStock = true
 },
 new Product
 {
 ProductName ="Baseball Bat",
 ProductPrice = 550,
 ProductType = "Sports",
 InStock = false
 },
 };

return lstProduct;
 }

In this way you can work with column width. I hope you find this post useful. Thanks for reading.

Learn more about Rad Controls for Windows 8 here

Three Steps to work with RadDataGrid in XAML based Windows Store Application

Recently I was talking to Windows Store App Developers. When I show them demo of RadDataGrid , all they got very excited. One of the manager asked me to show working with RadDataGrid in simplest steps. In this post we will take a look on working with RadDataGrid in three simple steps.

Learn more about Rad Controls for Windows 8 here

Step 1: Add Rad Controls for Windows 8 reference

Go ahead launch Visual Studio and create a new Windows Store Application. Select Blank App project template to create application. After project being created add Rad Controls for Windows 8 reference in the project. To add reference right click on Reference in project and select Add Reference.

image

After adding reference on XAML add namespace to work with RadDataGrid


xmlns:telerik="using:Telerik.UI.Xaml.Controls.Grid"

Step 2: Create Business object

Next step you need to create business object. Let us create business objects for Product


public class Product
 {

 public string ProductName { get; set; }
 public double ProductPrice { get; set; }
 public string ProductType { get; set; }
 public bool InStock { get; set; }
 }

We will display Products in RadDataGrid. In real time scenario List of Products will be fetched from Services. For purpose of this post let us create List of Products as collection locally.


private List<Product> GetProducts()
 {
 List<Product> lstProduct = new List<Product>
 {
 new Product
 {
 ProductName ="Pen",
 ProductPrice = 100,
 ProductType = "Education",
 InStock = true
 },
 new Product
 {
 ProductName ="Pencil",
 ProductPrice = 50,
 ProductType = "Education",
 InStock = false
 },
 new Product
 {
 ProductName ="Math Book",
 ProductPrice = 345,
 ProductType = "Education",
 InStock = true
 },
 new Product
 {
 ProductName ="Ball",
 ProductPrice = 23,
 ProductType = "Sports",
 InStock = true
 },
 new Product
 {
 ProductName ="Cricket Bat",
 ProductPrice = 560,
 ProductType = "Sports",
 InStock = true
 },
 new Product
 {
 ProductName ="Baseball Bat",
 ProductPrice = 550,
 ProductType = "Sports",
 InStock = false
 },
 };

return lstProduct;
 }

Step 3: Create RadDataGrid and bind with the datasource

In last step you need to put RadDataGrid on XAML and bind it to data source. RadDataGrid can be created as following


<telerik:RadDataGrid x:Name="ProductGrid" />

Next you need to bind RadDataGrid to List of Products. You can do that as following


this.ProductGrid.ItemsSource = GetProducts();

Run Application

On running application you will find RadDataGrid. You will notice that by default RadDataGrid supports sorting on columns

image

In these 3 simple steps you can start working with RadDataGrid in XAML based Windows Store Application. In further posts we will get into deeper concepts of RadDataGrid. I hope you find this post useful. Thanks for reading.

Learn more about Rad Controls for Windows 8 here

Complex Object and RadAutoCompleteBox in XAML based Windows Store Application

Learn more about Rad Controls for Windows 8 here

In this post we will take a look on working with Complex Business object and RadAutoCompleteBox in XAML based Windows Store Application. To start with make sure that you have added RadControls for Windows 8 reference in project. To add reference right click on project and from Extensions tab select RadControls for Windows8.

image

After adding reference of RadControls for Windows 8 you need to create business object. Let us assume, we are going to work with Employee object. You need to create Employee class is as follows,

public class Employee
 {
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public string Department { get; set; }

}
}

As of now you have created Employee class. Next you need to create or rather populate Employee data. There are many ways Employee data can be populated in application. Some of them are as follows,

  • From WCF SOAP Service
  • From WCF REST based Service returning either JSON or XML.
  • From OData Service etc

For purpose of this post we are going to populate data locally. Let us create a function returns collection of Employee

private List<Employee> GetEmployees()
 {
 List<Employee> lstEmployee = new List<Employee>
 {
 new Employee
 {
 FirstName = "Dhananjay",
 LastName = "Kumar",
 Department = "Team1"
 },
 new Employee
 {
 FirstName = "Dhananjay",
 LastName = "Kumar",
 Department = "Team1"
 },
 new Employee
 {
 FirstName = "Deepak",
 LastName = "Chwala",
 Department = "Team2"
 },
 new Employee
 {
 FirstName = "Amit",
 LastName = "Chawla",
 Department = "Team1"
 },
 new Employee
 {
 FirstName = "Arun",
 LastName = "Narayn",
 Department = "Team2"
 },
 new Employee
 {
 FirstName = "Bunty",
 LastName = "Goyel",
 Department = "Team1"
 },
 new Employee
 {
 FirstName = "Boman",
 LastName = "Irani",
 Department = "Team2"
 },
 new Employee
 {
 FirstName = "Charu",
 LastName = "Sharma",
 Department = "Team2"
 },
 new Employee
 {
 FirstName = "Depanker",
 LastName = "Banerjee",
 Department = "Team1"
 },
 new Employee
 {
 FirstName = "Ashok",
 LastName = "Singhal",
 Department = "Team2"
 },
 new Employee
 {
 FirstName = "Chabhi",
 LastName = "Rastogi",
 Department = "Team1"
 },

};

return lstEmployee;
 }

As of now you have collection of business object with you. Now you need to create RadAutoCompleteBox. Very first on XAML add following namespace


xmlns:tinput="using:Telerik.UI.Xaml.Controls.Input"

After adding namespace you need to add RadAutoCompleteBox on XAML a follows,


<tinput:RadAutoCompleteBox
 Height="70"
 Width="200"
 x:Name="autocompleteEmployee"
 DisplayMemberPath="FirstName">

 </tinput:RadAutoCompleteBox>

You can set one of the property of complex object as suggestion term. Above we are setting FirstName property as suggestion term.

In last step you need to set ItemSource of RadAutoCompleteBox. This can be set as following

protected override void OnNavigatedTo(NavigationEventArgs e)
 {
 autocompleteEmployee.ItemsSource = GetEmployees();

 }

Now on running application you will find RadAutoCompleteBox bind with complex object.

image

In this way you can work with complex object as RadAutoCompleteBox in XAML based Windows Store Application. I hope you find this post useful. Thanks for reading.

How to perform localization on RadGrid for ASP.NET AJAX

Overview:

I attended TechEd India 2013 which was held at Bangalore on Mar 18 & 19. I was talking to couple of developers on their experience with our Rad Controls. One of the developer with whom I was talking to wanted to know if localizing string is easy or difficult with our Grid. He was talking about the static texts which we have in our Grids like – message shown on the group bar, message shown in mouse over of columns for sorting, message shown in our filter menu items etc. His project was looking at using a 3rd party control and localizing the controls with minimal effort was one of the main criteria for them. I told him that it was as easy as creating one file and adding it to the project. In this post we will explore our option on localizing Telerik controls in general the RadGrid.

Global Resource Files:

When you download and install the RadControls for ASP.NET AJAX, we also ship resource files for all our controls and is installed in “App_GlobalResources” folder. Below is a screen shot of the resource files installed on your hard disk:

image

Fig1: Global Resources for RadControls

Notice the resource file for Grid high lighted. The file name is RadGrid.Main.resx. This contains all the resource string for neutral culture and will be used by our RadGrid control.

When you create a ASP.NET project, you can add certain specific named folders which the ASP.NET recognizes and specific types of content can be kept in this folder. One such folder is App_GlobalResources and can contain resources namely .resx files and .resources files. These are compiled into assemblies with global scope. These resources are strongly typed and can be accessed programmatically also.

Steps involved in Localizing the RadGrid

Following steps are involved in localizing the RadGrid:

  1. Add RadGrid.Main.resx file to your application’s App_GlobalResources folder
  2. Create a language pack i.e. RadGrid.Main.<locale id>.resx and add it to App_GlobalResources folder
  3. Set the culture to use on the RadGrid

We will go through the above steps one by one in following sections.

1. Adding RadGrid resource files:

Open Visual Studio and create a new project. Select Telerik > Web template and “C# RadControls Web Application”.

SNAGHTML263dbfce

Fig2: New Project Dialog

Once Visual Studio finishes creating the project, solution will look like below:

image

Fig3: Solution Explorer

Open Default.aspx and add a RadGrid from the toolbox. We will bind the grid to Products table from Northwind database. We will make use of OpenAccess to create a Data Model or Domain Model and OpenAccess Data Source for data binding. If you are not familiar with OpenAccess, it is a free ORM tool from Telerik. I encourage you to download and play with it. Add a new item to the project of type “Telerik OpenAccess Domain Model”.

image

Fig4: Add New Item Context Menu

For this demo, I have selected only Products table and created my OpenAccess Domain Model. Here is how the domain model should look like now:

image

Fig5: OpenAccess Domain Model Diagram

After adding the domain model, do a build to make sure everything is ok. Next, open the Default.aspx in designer mode, click on the smart tag of RadGrid, the smart tag property window will be shown. From the choose data source dropdown select <New data source> option. You will be presented with “Choose a Data Source Type” window. Select OpenAccessLinqDataSource. Specify  name for the data source and proceed. Next in “Select OpenAccess Context Type” window, it will automatically select the domain model we have added and select the products table as the entity and click Next. In “Configure Data Selection” window select the columns that needs to be shown on the grid and click Finish. Now we have  a data source and our RadGrid is bound to that data source. Enable Paging, Sorting, Grouping and Filtering on the grid by using the smart tag.

image

Fig6: RadGrid Smart Tag

Add a new folder called “App_GlobalResources”. Add RadGrid.Main.resx file from App_GlobalResources folder found in your RadControls for ASP.NET AJAX installation folder and paste it in your applications App_GlobalResources folder. At this point run the application and you will see the below output of the grid:

image

Fig7: RadGrid output

Notice the static text on – grouping bar, Sort tool tip (when you mouse over on the columns), filter conditions and the page size. So we will see how to localize these.

2. Add language pack:

For the purpose of this blog post I will try to create a French language pack or resource file and the RadGrid will use the strings from it to display the static text. In order to add a language pack for RadGrid, copy the RadGrid.Main.resx and paste it in App-GlobalResources folder. Rename the pasted file to RadGrid.Main.fr-FR.resx. Here fr-FR is the locale that we would like to localize the grid. This can be any other locale that you need to support in your applications. If you double click RadGrid.Main.fr-FR.resx in Visual Studio, you will see the resource editor open and show the strings as a grid. Here is the screenshot of that:

image

Fig8: RESX Editor

As you can see we see the string name and value for that. Since we copied from language neutral resource file, the values are all in English locale. Now all we are required to do is to change the value of the keys to French locale. I will use Bing translator to translate the values and replace them in the RadGrid.Main.fr-FR.resx. After translating some of the values to French, here is how the RESX file looks like:

image

Fig9: French Resource File

3. Set locale on RadGrid

In order for the RadGrid to pick up the right locale you can either set the Culture property of the RadGrid explicitly or set the Culture property to CurrentUICulture. For the purpose of this demo, I am explicitly setting the culture of RadGrid to fr-FR i.e. French.

image

Fig10: RadGrid Culture property

Here is the RadGrid with culture set to fr-FR:

image

Fig11: RadGrid localized to fr-FR locale

Note: The column headers are not localized because I haven’t provided any strings for them. You can pretty much use the same global resource file and use the resource strings instead of the static text. This blog post was to show how parts of RadGrid can be easily localized.

Summary:

With simple 3 steps we were able to localize different texts of RadGrid without much hassle. All we needed to do was to create a language pack and keep it in App_GlobalResources folder. All Telerik controls respect the ASP.NET folder and know how to use the resources from this folder. Hope this helps you all those folks who are looking at localizing our controls. Do leave any feedback if you may have.

How to ask questions in Telerik Forums?

Recently one of our customer sent me mail that how could I ask questions in Forums. She was a fresher with assigned job to work on Rad Controls for AJAX. I helped her over the call and found a step by step guide could be useful for many Telerik products users. To ask question in forums follow following steps,

Step 1

Navigate to http://www.telerik.com/ and login with your Telerik Credentials. You should able to see your name at the right top.

clip_image001

 

Step 2

Next select the specific product for which you want to ask question. Let us say you want to ask question for any of the DevTools. From top click on Product Families and select DevTools.

clip_image003

Step 3

Now from menu select Community & Support and then choose Forums.

clip_image004clip_image006

Step 4

Next you need to choose specific product. Let us assume you want to ask question for Rad Controls for AJAX. For that choose ASP.NET AJAX

clip_image008

Alternatively you can search in entire forum also. For that put your search term and click green Search button.

Step 5

Now you need to select category of your question. For instance if you want to ask question for Calendar control then choose Calendar from listed option. After choosing category click on green New Thread button to ask question.

clip_image010

While asking question following points are important,

  • · Give descriptive title of the question.
  • · Embed code using code button from menu
  • · Be specific in asking question.

At end make sure to check subscribe me to this thread such that on every reply you get a mail.

clip_image012

In this way you can ask questions in forum. I hope you find this post useful. Thanks for reading.

Create QR Code for Windows Phone 8 Apps using Telerik RadBarcodeQR Control

In this post we will take a look on creating QR Code in Windows Phone 8 Applications. We will use Telerik RadBarcodeQR control to create QR code. We will follow step by step approach to achieve this. At the end of this post we will create application as following,

image

Let us follow following steps to work with QR codes.

Step 1

In Windows Phone Application project we need to add Telerik Rad Controls for Windows Phone dll as reference. After adding that add following namespace on XAML.


xmlns:telerikPrimitives="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.Primitives"
 xmlns:telerikDataViz="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.DataVisualization

Step 2

After we have added reference we can simple create QR code with hard coded information as follows. We can create QR code using RadBarcodeQR control.

<telerikDataViz:RadBarcodeQR x:Name="qrContact"
 Opacity="1" Version="20"
 ErrorCorrectionLevel="H"
 Mode="Byte"
 ECI="ISO8859_1"
 FNC1="FNC1SecondPosition"
 Text="your data"
 ApplicationIndicator="00"/>

At this point on running application we will get QR code generated with hard coded data. We will get application running as following,

clip_image002

As we can see that following properties of QR code is configurable.

image

Step 3

As of now we have created QR code with hardcoded data. Let us go ahead and take user input as data and then create QR code of that data.

In XAML, divide content grid in two rows. In first row we will put QR code and in second row RadTextBox to enter user input. On click event of the button we will create QR code

Let us put following XAML to take user input


<StackPanel Orientation="Vertical" Grid.Row="1">
 <TextBlock Text="Contact details"
 Foreground="{StaticResource PhoneSubtleBrush}"
 Margin="12, 6, 12, -6"/>

<telerikPrimitives:RadTextBox Watermark="First and last name"
 Margin="0, -6, 0, 0"
 x:Name="nameTextBox"/>
 <telerikPrimitives:RadTextBox Watermark="Phone number"
 InputScope="TelephoneNumber"
 Margin="0, -12, 0, 0"
 x:Name="phoneTextBox"/>
 <telerikPrimitives:RadTextBox Watermark="Email"
 InputScope="EmailNameOrAddress"
 Margin="0, -12, 0, -2"
 x:Name="mailTextBox"/>

<Button Content="generate QR code"
 x:Name="btngenerateCode"
 />
 </StackPanel>

&nbsp;

Now on click event of the button we will set text property of QR code. We need to make sure that we have not set text property declaratively in XAML.


<telerikDataViz:RadBarcodeQR x:Name="qrContact"
 Opacity="0" Version="20"
 ErrorCorrectionLevel="H"
 Mode="Byte"
 ECI="ISO8859_1"
 FNC1="FNC1SecondPosition"
 ApplicationIndicator="00"/>

On click event of the button we need to set text property. That can be done as following. In below code we are doing concatenation of name, phone number and email as single string and then setting that as text property of QR code.


void btngenerateCode_Click(object sender, RoutedEventArgs e)
 {

 string qrdata = nameTextBox.Text + " " + mailTextBox.Text + " " + phoneTextBox.Text;
 qrContact.Text = qrdata;
 qrContact.Opacity = 1;
 }

On running application we can create QR code from use provided information.

clip_image002[6]

In this very simple we can create QR code using Telerik RadBarcodeQR control. I hope you find this post useful. Thanks for reading.