Quantcast
Channel: Telerik Blogs
Viewing all 4135 articles
Browse latest View live

Wishing our Indian customers a Very Happy Diwali

$
0
0

The Indian subcontinent and the Indian community worldwide is celebrating the festival of lights - Diwali on Nov 13th 2012. On this auspicious and joyous occasion, Telerik would like to wish all of its customers a Very Happy and Prosperous Diwali!

Happy Diwali

If you are using the Telerik productivity tools already, we hope that they have helped you create better applications in lesser time. Hence, our humble contributions to your moments of happiness. We pledge to continue to create wonderful tools for your benefit in the coming year.

We leave you with a Diwali resource to check out: http://www.telerikhelper.net


RadSlideView for Windows Phone: One Step Closer to the Native Photo Browsing Experience

$
0
0

With our Q3 2012 release last month, we introduced a new functionality in RadSlideView: Filmstrip mode. This feature brings this control even closer to the native photo browsing experience of Windows Phone. As you might have noticed, with RadSlideView you can zoom-in an image and see more details, but when you zoom-out, you can't zoom any further than fitting the image to the available screen-size. Not anymore. The new mode allows you to see the adjacent images if you zoom out enough and quickly browse all images by pan and flick gestures. To leave this mode, simply zoom-in or tap some of the images.

Filmstrip Mode First Look

To use the filmstrip mode, you have to set the IsFilmstripModeEnabled property of RadSlideView to True and also define a FilmstripModeItemTemplate. This template may be the same as the ItemTemplate, but it may also be completely different. The most typical scenario is that you would want both zooming in and out of the images. The zooming in is done by PanAndZoomImage that needs to be included in the ItemTemplate:

<telerikPrimitives:RadSlideView.ItemTemplate>
    <DataTemplate>
        <telerikSlideView:PanAndZoomImageSource="{Binding}"/>
    </DataTemplate>
</telerikPrimitives:RadSlideView.ItemTemplate>

The zooming out is handled by the filmstrip mode itself, so you should not include another PanAndZoomImage but rather have a native Image element in the template of the filmstrip. The other specific thing is that the images in RadSlideView stretch by default to fill the space they have, but in filmstrip mode they don’t. So if you want to cover the whole screen you will need to explicitly set the width of the Image element, for example:

<telerikPrimitives:RadSlideView.FilmstripModeItemTemplate>
    <DataTemplate>
        <ImageSource="{Binding}"Width="480"/>
    </DataTemplate>
</telerikPrimitives:RadSlideView.FilmstripModeItemTemplate>

You can take advantage of the two item templates by providing different information in them and show/hide some details like title, author, etc. for only one of the modes. 

Pretty much that’s all you need to know before bringing the native picture experience to your application. The filmstrip mode is available in RadSlideView as part of both RadControls for Windows Phone 7 and 8

Now you can get license for our controls not only from Telerik’s website but also from Nokia as part of their Premium Developer Program

Have fun and don’t forget to share your comments and feedback in our forums.


AcceleratorHK Week 1

$
0
0

Last week was the first week of the AcceleratorHK program. We have six teams that make up this cohort coming from: Hong Kong, Silicon Valley, Mexico, and Malaysia. The teams are just starting out but are in the following domains: social, location based, and community.

We started out with an introduction to Customer Development by program director Paul Orlando and then broke up the teams and gave them a Startup Weekend style assignment : go out and work on project for 48 hours with new teammates with a focus on Customer Development. The results were…interesting.

We had two mentors come in and work with the teams. John Bristowe came in from Australia and spoke about HTML5 and Phonegap (since we are a mobile accelerator) and then provided technical training on KendoUI and Icenium.

2012-11-08 10.18.00

Shanghai based, Spanish investor Oscar Ramos also came in and did a great mentoring talk on Visual Thinking and how to use it as a tool in your customer development process.

2012-11-08 17.16.26

We even had time to hit the racetrack at Happy Valley on Wednesday night for Oktoberfest night for a cohort social.

1352294791184

On Friday we had our first check-in to see how the teams were doing and each team did their elevator pitch. (One team included their winnings at Happy Valley as their first revenue. Smile)

A great start to the Accelerator. Stay tuned for more updates.

XAMLflix presents RadPivotGrid for WPF and Silverlight

$
0
0

Introduction

Hello everyone!

As you may have read in the latest issue of the Telerik Newsletter, we are proud to announce a brand new XAMLFlix episode on RadPivotGrid. In case you haven’t heard, XAMLFlix is a video series devoted to getting you up to speed quickly with our Telerik controls for WPF and Silverlight. In this episode, we will take a look at what RadPivotGrid Beta for WPF has to offer, with three short videos. So grab some coffee and let’s get started!

What Is RadPivotGrid?

RadPivotGrid is a control used to aggregate millions of records in a concise tabular format. The data can be easily grouped, filtered, sorted and manipulated to create different types of reports. The three videos available for viewing right now show you just how to accomplish that.

  • Getting Started with RadPivotGrid – In this video, we will see how easy it is to setup a LocalDataProvider and bind RadPivotGrid to data inside of a predefined class. We will also discuss how easy it is to setup Row/Column/AggregiateGroupDescriptions which will allow us to customize the data displayed inside the RadPivotGrid. Download Project
  • Using RadPivotFieldList with RadPivotGrid– In this video, you will quickly learn how RadPivotFieldList is an integral part of RadPivotGrid. It allows the end-user to modify RadPivotGrid and generate many different reports with the current data. Download Project
  • Customizing RadPivotGrid with Group Filtering – So far, we have seen how easy it is to use RadPivotGrid and RadPivotFieldList. In this video we will show you how easy it is to let your user customize their RadPivotGrid output with group filtering. Group filtering allows you to find items matching a criteria and adjust the data automatically. You can apply filters based upon Grand Total or the Names of the group. This gives your users the ultimate in flexibility with very little effort on your part. Download Project

Wrap-Up & Share Your Thoughts

Telerik XAMLflix for WPF controlsIn these three videos, we learned a lot about what RadPivotGrid is capable of, but that is not all of the features we are planning to add. We are currently in BETA, with an official version coming Q1 2013. We are working hard to add new features such as XMLA and ADOMD for taking advantage of OLAP data operations and much more!

As always, we are always open for feedback on how we can improve this control or any control currently available, so feel free to leave a comment below or send me a tweet on Twitter at @mbcrump.

I’d also encourage you to go ahead and download your own copy of the Telerik WPF or Silverlight control suite right now where you can explore this control and others.

Thanks for reading and happy coding!

About the author

Michael Crump - XAML RockStar!

Michael Crump

Michael Crump is a Microsoft MVP, INETA Community Champion, and an author of several .NET Framework eBooks. He speaks at a variety of conferences and has written dozens of articles on .NET development. He works at Telerik with a focus on our XAML control suite. You can follow him on Twitter at @mbcrump or keep up with his various blogs by visiting his Telerik Blog or his Personal Blog.

Startup Weekend in Hong Kong

$
0
0

This past weekend was the 3rd Startup Weekend in Hong Kong and I was lucky enough to return again as a judge. This year it was huge with 14 teams competing!

 2012-11-10 16.49.13

As usual, I was very impressed by the ideas, hard work, and execution. They stared on Friday night with lots of pitches and team formation. The group worked all day Saturday and Sunday at the CoCoon co-working space in Hong Kong (the same co-work space AcceleratorHK is using). A few AcceleratorHK cohort members as well as program director Paul Orlando were helping out as mentors.

2012-11-10 18.35.38

On Sunday night we all gathered to a different venue where we heard all of the 14 pitches. Myself and four other esteemed judges listened to the 5 minute presentations and lead the 3 minute Q&A session.

 2012-11-11 17.23.48

The teams came from all walks of life as well as had ideas and teams that were in a variety of domains including: social, conference networking, kitchen rental, shopping, car sharing, film location scouting, and creative ways to use your free time. After the deliberation, which was close, we choose “FilmScout” as the winner. FilmScout was a team that built a solution for filmmakers and film students to find film locations to shoot in. While a niche market, they were a 100% solution to a market segment and demonstrated that they followed the Customer Development process over the course of the competition (which accounts for 1/3 of the judging criteria).

After the event there was some networking and I was interviewed on local Hong Kong TV about the startup scene in Hong Kong, AcceleratorHK, and of course my role as a judge in Startup Weekend.

2012-11-11 20.47.49

Creating a Windows 8 Application From Scratch

$
0
0

Phil Japikse, Michael Crump and I set out to create three related applications from scratch.  That is, a Windows 8 version written in XAML with C# (me), a Windows 8 version written in JavaScript (Phil) and a Windows 8 Phone version (Michael).  Mockup1

The idea behind the application was summed up in an email by Phil, paraphrased here:

  • The main goal of the application is to show off our controls
  • The business purpose of the application is to allow Telerik Evangelists to gather information from conference attendees

The design will allow us to:

  • Enter demographic information for raffle registration
  • Enter demographic information for follow ups
  • Tag one or more products for follow up
  • Enter information on problem reports
  • Enter information for product suggestions

 

We knew we wanted expert design help for the UI/UX aspect, but to get us started we met briefly to mock-up what we had in mind.  The goal was not to show how the UI would look (that would be up to the designers) but rather to show the kind of information we wanted to gather.  We used MockUpScreens, working with a shared screen over Skype.

In the upper right corner you see an example of one of the screens (click on the image to see full size).  Of course, with Windows 8, rather than having multiple screens and navigation controls to move between them, we may create one very wide screen that the user can swipe across (much like the weather app that comes with Windows 8).

From here we will give these mock-ups to the designers who will return wire-frames of the look and feel of the application.

The next step is to create the model: the persistence layer of classes or tables that will hold the data we collect.  This should be almost totally automatic once we have the wireframes.

It is my intention to document every step of the creation of the XAML/C# version of this application, including design decisions (and mistakes!) and the process of taking an application from conception through making it ready for the Windows Store.  That is my intention; we’ll see how it goes!

JustCode Code Style Settings for C#, Part 1

$
0
0

In our previous blog posts on the JustCode Formatter, we’ve showed you what it is and how it works. If you haven’t read those yet, please see our post on "Introducing the Formatter" and "Comparing the JustCode Formatter to the Visual Studio Formatter".

One of our design goals was to make sure the Formatter is much more customizable than Visual Studio’s, and in this post, we will show you how easy it is to customize it.

What are the Code Style settings?

When you utilize JustCode’s refactorings, expand code templates, format and/or clean your code, or make other changes to your code, JustCode needs to know how to structure the affected code. JustCode has a set of rules that are taken into account when modifying code. These rules are called the “Code Style” settings. You can find them in the JustCode -> Options -> Code Style pages.

You can easily customize rules using these settings pages, such as where the block braces will be positioned, whether to put spaces or not between given code constructs, or whether to wrap code and even how to wrap it if the line length is larger than a customizable value.

Code Style settings can also be customized per solution. That way all the people working on that solution will use the same coding rules and the code they produce will be styled in the same manner.

Code Style settings for C#

For a more clear and concise user experience, JustCode separates Code Style settings by language and functionality.

C# Code Style Settings are separated into ten categories:

  • General
  • Indentation
  • Spacing
  • New Lines
  • Blank Lines
  • Ordering
  • Brace Positioning
  • Wrapping
  • Using Directives
  • Naming Conventions

In this post, we will look at the first five categories – General, Indentation, Spacing, New Lines, and Blank Lines.

General

JustCode style settings image
Image 1. General page.

The General Settings page (shown in Image 1) contains settings that are unrelated to any of the other functional groups. The main settings on this page define whether code blocks should be introduced or not by the specified JustCode code generation features.

Indentation

JustCode style settings image
 Image 2. Indentation page.

The Indentation Settings page (shown in Image 2) contains settings that allow for customizing how certain code constructs will be indented related to their parent constructs.

Each setting has a code preview window at the bottom of the page for immediate feedback of how changing the setting will affect your code. To show the preview, select the setting that you want to view. The images below (Image 3) show the code preview changing when the setting is changed.

JustCode style settings image 
Image 3. Changing the preview in result of setting change.

Spacing

JustCode style settings image
Image 4. Spacing page.

Customizing the spacing settings will help make your code more readable by automatically adding spaces based on your selected settings.

As you can see in Image 4, JustCode has a significant number of spacing settings that you can customize. We have set the default values based on user feedback so most developers won’t have to spend much time customizing them, but the defaults are easy to change if they don’t match your preferred code spacing style.

As with all of the settings pages, the Spacing settings page also provides previews so you can see how your code will be affected by a settings change before applying them.

New Lines

JustCode style settings image
Image 5. New Lines page.

The New Lines settings (Image 5) customize whether braces, bracket, parentheses, certain keywords, and other constructs are placed on their own line or not.

This settings page also provides a preview so you can see how your code will be affected before applying a change.

Blank Lines

JustCode style settings image
Image 6. Blank Lines page.

Putting empty lines between code constructs can greatly improve readability and the structure of your code. As shown in Image6, there are several options for each setting. Take for example “Blank lines after Events” (highlighted in group 1). There are sets of options (see groups 2 and 3) allowing for additional customization based on the following code construct. If in your code there are less than “Min” value blank lines, additional blank lines will be added. Likewise, if in your code there are more than the “Max” blank lines, the extra lines will be removed.

If you just want to put a set number of blank lines after a given code element, regardless the following element, you can use the edit-box after the setting name (see group 4). Modifying this edit-box’s value will automatically modify all values in the underlying group.

Summary

We have only scratched the surface covering just half of the settings for C# - General, Indentation, Spacing, New Lines, and Blank Lines. There are a host of additional settings that we will cover in the next blog post, and that’s just for C#!

We welcome you to experiment with the Code Style settings. We are confident you’ll be able to make your code look exactly like you want it. Your previous settings are safe with JustCode’s Visual Studio Cloud Backup - just be sure to create a backup before you begin.

If you have a suggestion for more customization, please leave us feedback on the JustCode Feedback Portal. You can also write to us in the forum as well as contact support directly.

Happy Coding!

The JustCode team

JC

Notifications and Settings in Telerik Control Panel

$
0
0

The Telerik Control Panel introduced a new and efficient way to install and update Telerik products. The Q3 2012 release makes it easier than ever to keep your Telerik products up-to-date with notifications and more customization.

If you are unfamiliar with the Telerik Control Panel, you can learn more about its standard features and how it enhances the Telerik Experience in Introducing the Telerik Control Panel.

When you open the Control Panel to update your products for the Q3 release, this screen appear.

clip_image002

The updater updates itself, and it brings features to make your Telerik experience that much better.

Options Abound

After installing the update, you can access the new customization features by opening the Options dialog. Access this by clicking the gear button in the upper-right corner.

clip_image003

The Options page appears, and there are several items to customize.

Notifications

The primary feedback we received on how to improve the Telerik Control Panel was to add notifications. This feature is now available, and by default, enabled on a weekly schedule.

clip_image005

You can disable notifications if you do not wish to keep your products up to date. However, it is easy to maintain the latest and greatest. Simply change the schedule to Daily. If you instead prefer fewer notifications, the Monthly option is also available.

You will receive notifications on your taskbar according to the schedule when newer versions of installed products are available or when one of your products is within 60 days of expiration.

clip_image006

You can easily check which products are about to expire and either renew the license, choose Remind Me Later, or simply close the window. If you choose Remind Me Later, you will receive another notification in one hour. If you close the window, you will receive a reminder during the next scheduled notification.

clip_image008

If updates are available, you receive the option to launch the Control Panel to update your software.

clip_image010

Download Settings

The Control Panel retrieves packages from a Telerik service and caches them before installation, and it retains these packages so you can make future changes. This panel allows you to change the folder in which the packages are stored. It also allows you to delete cached packages.

clip_image012

Proxy Settings

This one is straightforward. Check the box to use Internet Explorer’s proxy settings.

clip_image014

Installation Settings

When installing from an MSI, you receive the choice to install to your preferred folder. Of course, the vast majority of people click through this screen, but an installer must offer this decision to allow customization. The Telerik Control Panel enhances this experience by making it a setting and applying it to every product.

The Control Panel provides an additional option to keep parallel versions. This is a valuable feature when working with many projects.

clip_image016

Conclusion

This release of the Telerik Control Panel makes it even easier to keep your Telerik products up-to-date. If you are not using it yet, what are you waiting for? Download it now from the Your Account page on Telerik.com!


The Agile Tour is coming to Hong Kong!

$
0
0

I am happy to be part of the organizing committee for the Agile Tour in Hong Kong on December 1st. I also convinced Telerik to send me 30kg of Tee-shirts for attendees of the event. Smile Details are below, register today, space is limited (only about 30 seats left)!

EventBrite Link to register: http://agiletour2012hongkong.eventbrite.com

AGILE TOUR 2012 COMING TO HONG KONG DECEMBER 1, 2012

Welcome all,

Agile Tour is finally coming to Hong Kong! We organize a full day with international and local expert speakers on a variety of Agile topics:

Title : How to suck less with distributed teams
Speaker : Emerson Mills
Abstract:

We all know that distributed teams suck. ( Don't we? ) They perform much worse than co-located teams. Unfortunately for places just starting to move to Agile methodologies, it's often a impediment that has to be worked around or removed. In this session we'll discuss some of the illusions about distributed team productivity and how to get around some of the problems before you can move to co-located teams.

  1. Why did we even use them?!
  2. Distribute teams not people
  3. Giving teams ownership of features and not tasks
  4. Sharing a product development culture

Title: Inject start up spirit
Speaker: Wang XiaoMing
Abstract:

During the past a couple of years I heard many complains from CEOs and senior management that there was unavoidable bureaucracy and large company problems which were their big pain. Many teams suffered unclear project goals, small team but many management layers, ineffective meeting, tons of reports and unstable products. Those problems caused project failure or delay. In this presentation I will lead you to experience a real project in a large company who saved themselves from failure and transferred to a team with start up spirit and doubled their velocity in 4 months.

  1. A real project, double velocity
  2. The pain of founders
  3. Inject start up spirit
  4. Lightweight Agile.

Title: Test Driven Development
Speaker: Ian Lucas
Abstract:

In this session we will explore Test Driven Development (TDD) utilizing XQuery, the XML Query Language. TDD helps facilitate higher quality software solutions, and the modular nature of XQuery lends itself well to the practice.

  1. TDD in context
  2. Defining Success criteria upfront (i.e. Test Cases as requirements specifications)
  3. Practical examples of TDD with XQuery and XQunit

Title: Agile ate my Project Plan!
Speaker: Michael Mallete
Abstract:

Among the biggest reasons for the reluctance of organizations in adopting Agile is their belief in the effectiveness of traditional models in estimation and planning. The fear of losing their perceived predictability through their conventional techniques. Agile erases these all and leaves you with a chaotic view of what is to come. But is that truly the case?

We will first explore the assumptions behind traditional estimation and planning techniques
We will then counter that with the assumptions behind Agile estimation and planning
We will show the different features of traditional estimation and planning
We will then show the different features of Agile estimation and planning
We then compare what we actually lose and what we gain when we move toward Agile estimation and planning

Title: Introduction to DevOps (topic to be confirmed)
Speaker: TBD
Abstract:

DevOps is a response to the growing awareness that there is a disconnect between what is traditionally considered development activity and what is traditionally considered operations activity. This disconnect often manifests itself as conflict and inefficiency.

You will have a chance to meet and talk to international and local Agile experts!

Intended Audience

  • IT professionals already experienced in Agile or thinking about moving to Agile (Developers, Testers, Business Analysts, Project managers, Scrum Masters, Product Managers / Owners etc.)

  • Managers responsible for Agile Development or in future likely involved in Agile

  • Anyone interested in Agile

How to register

Through EvenBrite. Register Early to avoid disappointment.

Regular: 75 HK$

Price on day self – provided there are still seats: 100 HK$

EventBrite Link: http://agiletour2012hongkong.eventbrite.com

Date
Saturday, December 1, 2012, 9am – 5pm, with lunch break from 12-1:30.
There will be time to meet speakers after 5pm.

Location

Cocoon, Causeway Bay, close to MTR and various lunch locations with local or international food.

http://www.hkcocoon.org/en/index.aspx

Transportation

  • Tin Hau MTR Exit A2 (10 mins walk)
  • Fortress Hill MTR Exit A (7 mins walk)
  • From Hong Kong Island, take Route 5X or 5 Bus straight to the final station
  • From Kowloon, take Route 118 Bus, get off the bus at Gordon Road station (3 mins walk)
  • From Airport, take Route A11 Bus, get off the bus at Gordon Road station (3 mins walk)

Supporting Organizations

Interacting with the RadDatePicker and RadTimePicker for Windows 8

$
0
0

Introduction

My good friend Michael Crump showed how to create an Appointment Tracking app with the RadDatePicker and RadTimePicker in this excellent post. I’m going to start where Michael left off, adding additional business rules and logic by interacting with controls.

If you haven’t read his post, you can download the project from here. I will start from this project to add in the additional functionality.

Design Goals

Imagine that the business has approached the development team and is complaining that users are selecting departure dates that are prior to the arrival date, and there is a desire to make the scheduler more “user friendly”.  The additional requirements are as follows:

  • Provide better visual cues to guide the user
  • Format the dates Day MMM DD, YYYY
  • Prevent selecting Arrival Time prior to selecting Arrival Date
  • Prevent selecting Departure Time prior to selecting Departure Date
  • Provide for resetting all form fields
  • Prevent selecting Departure Date that is prior to Arrival Date
  • Prevent selecting Departure Date/Time that is prior to Arrival Date/Time

The new screen design is shown in Figure 1.

image
Figure 1 – Updated Screen Mockup

We also want to add a message box so that if the user enters bad data, they are warned prior to clearing the bad data, similar to Figure 2.

image
Figure 2 – Error message

Setting the Initial State

We can set the initial state for the controls through the data-win-options attributes (and this can be conveniently done through Blend) or through JavaScript.  In this case, since there is a requirement to reset all of the form fields, I’m going to create a method in JavaScript, but before we do that, we need to have references to the controls.

Start by opening up default.js.  First, add variables to hold refererences to all of the controls we need.  Next, add an app.onready function, and assign the winControls to the variables.  I also add a call t othe setup() function, which I will write shortly.  This is shown in Listing 1.

var appointmentName;
var arrivalDate;
var arrivalTime;
var departureDate;
var departureTime;
app.onready = function () {
    appointmentName = document.getElementById("appointmentInput");
    arrivalDate = document.getElementById('arrivalDateInput').winControl;
    arrivalTime = document.getElementById('arrivalTimeInput').winControl;
    departureDate = document.getElementById('departureDateInput').winControl;
    departureTime = document.getElementById('departureTimeInput').winControl;
    setup();
};
Listing 1

Configuring the Controls

To set the initial state of our controls, I am going to take advantage of the richness of the RadDatePicker and the RadTimePicker controls.

Setting the Watermark

Both the RadDatePicker and the RadTimePicker allow for customizing the watermark text by setting the “emptyContent” property. I create the setup() function and set the initial values for the watermarks in Listing 2.

function setup() {
    arrivalDate.emptyContent = 'Select arrival date';
    arrivalTime.emptyContent = 'Select arrival date first';
    departureDate.emptyContent = 'Select departure date';
    departureTime.emptyContent = 'Select departure date first';
};
Listing 2

NOTE: If not set, it will default to “Select Date” for the RadDatePicker and “Select Time” for the RadTimePicker.

Setting the Display Format

There are a lot of configuration options for setting the display format for dates and times. The RadControls take full advantage of the WinJS libraries and date and time formatting. 

Date Formatting

Some of the date formatting options are listed in the table below:

Date FormatExample
{dayofweek.full}Friday
{dayofweek.abbreviated(3)}Fri
{month.full}January
{month.abbreviated(3)}Jan
{month.integer}1
{month.integer(2)}01
{date.integer}8
{date.integer(2)}08
{year.full}2012
{year.abbreviated(2)}12

I want to set the format so that 11/6/2012 would display as “Sat, Nov 06, 2012” (as shown in Figure 3. 

image
Figure 3

To set the proper date format we use the “displayValueFormat” property for both controls in our application, adding the lines shown in Listing 3 to the setup() method.

arrivalDate.displayValueFormat = '{dayofweek.abbreviated(3)} {month.abbreviated(3)} '
    + '‎{day.integer(2)}, ‎{year.full}';
departureDate.displayValueFormat = '{dayofweek.abbreviated(3)} {month.abbreviated(3)} '
    + '‎{day.integer(2)}, ‎{year.full}';
Listing 3
Time Formatting

There aren’t as many options for formatting how time displays, as can be expected.  If your machine is formatted to display time in 24 hour format, you can not display AM/PM at all.  Some of the available formats are display in the following table.

Time FormatExample
{hour.integer}9
{hour.integer(2)}09
{minute.integer}5
{minute.integer(2)}05
{period.abbreviated}AM
{period.abbreviated(2)}A

The requirements don’t call for a specific formatting, and I prefer two digit times, so I set the displayValueFormat property in the setup() method for the time pickers as shown in Listing 4.

arrivalTime.displayValueFormat = '{hour.integer(2)}‎:‎{minute.integer(2)}';
departureTime.displayValueFormat = '{hour.integer(2)}‎:‎{minute.integer(2)}';
Listing 4

Preventing selecting times before selecting dates

Our next two requirements are to prevent selecting the Arrival Time or Departure Time prior to selecting the appropriate dates.  The  controls have two properties, “isreadOnly” and “enabled”.  Technically, setting “isReadOnly = true” and “enabled = false” would both work.  However, “enabled = false” also hides the control, giving a less than positive experience (as shown in Figure 4).

image
Figure 4

A better experience is to use “isReadOnly = true” so the controls don’t pop in and out.  As the watermarks explain “Select arrival date first” and “Select departure date first”, the users are informed of why they can’t select a time if a date hasn’t been selected, giving a much more pleasant experience.  Setting the controls to read only are the last two lines for the setup() method, and are shown in Listing 5.

arrivalTime.isReadOnly = true;
departureTime.isReadOnly = true;
Listing 5

Clearing the Controls

It is a common requirement to enable users to start over with data entry forms by providing a “Clear” button. It is also a good idea to have the users confirm that they really want to clear the form to prevent data loss due to accidental clicks.  WinJS provides the Flyout control for just this reason.  The user can click (or tap) on a button in the Flyout to execute the command, or click/tap anywhere else in the application to make the Flyout simply disappear.

Creating the Flyout Control in HTML

Flyout controls show standard HTML in essentially a message box.  This HTML will only be visible when the Flyout control is shown though JavaScript, so it doesn’t affect our page layout.  The div for the control and the HTML it contains is shown in Listing 6.

<divid="clearFlyout"
data-win-control="WinJS.UI.Flyout"
aria-label="Clear confirmation">
    Are you sure you want <br/>
    to clear all controls? 
<br/><br/>
<palign="center">
<buttonid="confirmClearButton">Clear</button>
</p>
</div>
Listing 6

Showing the Flyout Control

To show the Flyout control we create another variable to hold the reference to the control (we’ll need this later to hide it again), and call show() from the click event of the “Clear” button.  The “show” command takes the DOM element that will anchor the location of the Flyout, as well as additional parameters to refine the positioning – placement and alignment respectively. 

var clearFlyout;
app.onready = function () {
//content already covered not shown for brevity
    clearFlyout = document.getElementById('clearFlyout').winControl;
var clearCmd = document.getElementById('clearButton');
    clearCmd.addEventListener('click', function () {
//Show the flyout based on the location of the clearCmd
        clearFlyout.show(clearCmd,'top','center');
    });
};
Listing 7

Wiring up the Confirm Clear Button

Our final task for this requirement is to wire up the confirmation button contained in the Flyout to call a method that will clear the form values and call the setup() method when clicked.  Wiring up the confirmClearButton is added to the app.onready method and is shown in Listing 8.

//added to app.onready
var confirmClearCommand = 
document.getElementById('confirmClearButton');
confirmClearCommand.addEventListener('click', clearAllItems);
Listing 8

The final task that we need to do in the clearAllItems() method is to hide the Flyout.  The code is shown in Listing 9.

function clearAllItems(e) {
    appointmentName.value = null;
    arrivalDate.value = null;
    arrivalTime.value = null;
    departureDate.value = null;
    departureDate.minValue = null;
    departureTime.value = null;
document.getElementById("appointmentOutput").innerText = "";
    clearFlyout.hide();
    setup();
};
Listing 9

Preventing Bad Data

The final two requirements are designed to prevent users from adding incorrect data.  When the Arrival Date changes, the code needs to:

  • Change the ArrivalTime to not be readonly and change the watermark,
  • Set the minValue for the Departure date to the Arrival Date,
  • Clear out the DepartureDate if it’s less than the Arrival Date,
  • Clear out the DepartureTime if the dates are the same and DepartureTime < ArrivalTime

When the Departure Date changes, the code needs to:

  • Change the DepartureTime to not be readonly and change the watermark

We can do this very simply because of the richness of the controls and their interactions through JavaScript.

Adding Change Event Listeners

Adding the event listeners is straight forward JavaScript added to the app.onready function.

arrivalDate.addEventListener('change', dateChange);
departureDate.addEventListener('change', dateChange);
Listing 10

The event handler simply checks the controls to make sure the rules have been properly followed.  The full code is shown in Listing 11. 

function dateChange(e) {
if (e.target.element.id === arrivalDate.element.id) {
if (arrivalDate.value !== null) {
            arrivalTime.isReadOnly = false;
            arrivalTime.emptyContent = 'Select arrival time';
            departureDate.minValue = arrivalDate.value;
if (departureDate.value !== null&& departureDate.value < arrivalDate.value) {
var message = "Departure date must be greater than or equal arrival date. \r\n"
                                + "Departure date will be cleared.";
                showErrorMessage(message);
                clearDepartureDate();
            } elseif (departureDate.value === arrivalDate.value &&
                arrivalTime.value !== null&& departureTime.value !== null&& 
                arrivalTime.value > departureTime.value) {
var message = "Departure time must be equal to or later than arrival time. \r\n"
                                + "Departure time will be cleared.";
                showErrorMessage(message);
                departureTime.value = null;
            }
        }
    }
else {
if (e.target.value !== null) {
            departureTime.emptyContent = 'Select departure time';
            departureTime.isReadOnly = false;
        }
    }
};
function clearDepartureDate() {
    departureDate.value = null;
    departureTime.value = null;
    departureTime.isReadOnly = true;
    departureTime.emptyContent = 'Select departure date first';
}
function showErrorMessage(message) {
var msg = new Windows.UI.Popups.MessageDialog(message);
    msg.showAsync();
};
Listing 11

The logic certainly isn’t production worthy, but the main item I want to show is how easily a control’s behavior can be changed based on the state of other controls on the page. In particular, as shown in Listing 12, when there is a valid date selected in the ArrivalDate RadDatePicker, I update the watermark as well as allow input into the ArrivalTime RadTimePicker, and set the minValue of the DepartureDate to the ArrivalDate.

if (arrivalDate.value !== null) {
    arrivalTime.isReadOnly = false;
    arrivalTime.emptyContent = 'Select arrival time';
    departureDate.minValue = arrivalDate.value;
};
Listing 12

Summary

In this post I showed you how easy it is to incorporate the RadDatePicker as the RadTimePicker into your application with business logic and validation.  With very few lines of code, your application can help guide your users down the path of success. 

Download the source code here.

About the author

Philip Japikse

2012STLDODN.93x112Philip Japikse an international speaker, a Microsoft MVP, INETA Community Champion, MCSD, CSM/ CSP, and a passionate member of the developer community, Phil Japikse has been working with .Net since the first betas, developing software for over 20 years, and heavily involved in the agile community since 2005. Phil works as a Developer Evangelist for Telerik's RadControls for Windows 8 as well as the Just family of products (JustCode, JustMock, JustTrace, and JustDecompile) and hosts the Zero To Agile podcast (www.telerik.com/zerotoagile). Phil is also the Lead Director for the Cincinnati .Net User’s Group (http://www.cinnug.org). You can follow Phil on twitter via www.twitter.com/skimedic and read his personal blog at www.skimedic.com/blog.

Speech Recognition Made Easy with Telerik RadControls for WP8

$
0
0

Introduction

Hello everyone! I’m sure by now you’ve heard the news from //Build/ that Telerik has released its Windows Phone 8 controls and this release includes several new components:

  • Speech Recognition – Allows your end-users to navigate and interact with your app using their voice.
  • MultiResolutionImage – Windows Phone 8 supports new display resolutions up to 1280x768 and Telerik RadControls make it easy for developers to display the appropriate images in their apps, according to the device resolution through this control.
  • DataForms – This new component allows you to automatically generate the UI for your input forms, with support for validation and custom layouts.
  • Along with many others detailed here.

In this post, we are going to explore the Speech Recognition API provided by Telerik that is currently in CTP (Community Tech Preview) that you can grab now from your account. But before we begin, let’s take a look at the completed application, then build it step-by-step together

Note: You may also download the completed source code now if you wish.




Support in the Official Windows Phone 8 SDK

Before we get started, let’s take a look at what is included in the official Windows Phone 8 SDK. There are three speech components that you can integrate with your app:

  • Voice Commands – After your user installs your application, they have the ability to say “open” or “start”, followed by your app name. They can also use the voice commands to deep link into a page inside your application.
  • Speech Recognition (and the focus of this post) – After your app launches, you are required to use a GUI (Graphical User Interface) for speech recognition that provides visual feedback to users. While a GUI is required, you can use your own or use the one built-in. It also requires that you setup voice commands from C#/VB, which adds another layer of testing to be performed. Below is a sample of what the built-in GUI provides.

WP8-2WP8-3WP8-4

While this is great for some applications, others may like a less intrusive way of obtaining speech data from the user. This is where Telerik RadControls for Windows Phone 8 comes in. No GUI is required and you can declare voice commands declaratively through XAML instead of code-behind.

  • Text-to-Speech (TTS) – is the last on the list and simply allows your app to translate text to speech and output it through the phones speaker. This is also known as “Speech Synthesis”.

Taking a look at the Telerik Speech Recognition API (CTP) in RadControls for Windows Phone 8.

Now that we have seen what Microsoft provides out of the box, let’s examine how to implement using our API.

First, you will need to obtain RadControls for Windows Phone 8 and then download the SpeechRecognition DLL found in your account.

Begin by creating a new VS2012 Windows Phone 8 project and adding references to:

  1. Telerik.Windows.Controls.Primitives – Only required to use our RadSlideView control which is shown in the demo.
  2. Telerik.Windows.Controls.Speech – Required to use our Speech Recognition API.


You will also need to add the ID_CAP_SPEECH_RECOGNITION and ID_CAP_MICROPHONE capabilities in the app manifest. If you need help in learning how to do this, then consult this document.

We are going to use the RadSlideView in this demo, so let’s begin by adding some images to our application. If you don’t have any images readily available, then download the completed project and use mine. We are going to create a folder called, “Images” in the current solution and add several images to this folder.

Let’s jump into the MainPage.xaml and declare our UI (User Interface)

Our UI is simply going to be the RadSlideView control taking up the entire screen with the Speech Recognition API added in. Let’s go ahead and add the proper XML namespaces as shown below:

   1: xmlns:telerikSpeech="clr-  namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.Speech"
   2: xmlns:telerikPrimitives="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.Primitives"
   3: xmlns:speech="clr-namespace:TelerikSpeechRecognitionSampleApp.SpeechHandlers"

This is going to allow us to reference our controls in XAML, and we are also going to add a new SpeechHandlers class to separate the voice actions from our UI.

Let’s go ahead now and replace the existing Grid with the following code snippet.

   1:<Gridx:Name="ContentPanel"Grid.Row="1"Margin="12,0,12,0">
   2:<telerikPrimitives:RadSlideViewx:Name="xSlideView"ItemsSource="{Binding}"TransitionMode="Flip"IsLoopingEnabled="True">
   3:<telerikPrimitives:RadSlideView.ItemTemplate>
   4:<DataTemplate>
   5:<ImageSource="{Binding}"Stretch="Fill"Margin="6,0,6,0"/>
   6:</DataTemplate>
   7:</telerikPrimitives:RadSlideView.ItemTemplate>
   8:<telerikSpeech:SpeechManager.SpeechMetadata>
   9:<telerikSpeech:SpeechRecognitionMetadata
  10:InputIdentificationHint="Available commands: 'next' or 'previous'"
  11:InputIdentificationToken="MainContent">
  12:<telerikSpeech:SpeechRecognitionMetadata.InputHandler>
  13:<speech:PreviousNextSpeechHandler/>
  14:</telerikSpeech:SpeechRecognitionMetadata.InputHandler>
  15:<telerikSpeech:SpeechRecognitionMetadata.RecognizableStrings>
  16:<telerikSpeech:RecognizableStringValue="next"/>
  17:<telerikSpeech:RecognizableStringValue="previous"/>
  18:</telerikSpeech:SpeechRecognitionMetadata.RecognizableStrings>
  19:</telerikSpeech:SpeechRecognitionMetadata>
  20:</telerikSpeech:SpeechManager.SpeechMetadata>
  21:</telerikPrimitives:RadSlideView>
  22:</Grid>

In this sample, we are adding a RadSlideView and setting its DataTemplate to a simple Image control. We are going to add the images to the ItemSource shortly.

Next, we declare the SpeechManager.SpeechMetadata and provide the text the application will say to the user upon execution. In this instance it will say, “Available commands: ‘next’ or ‘previous’” as shown in the video earlier in this blog post. We need to create some sort of InputHandler to perform actions on those commands and that is accomplished with the PreviousNextSpeechHandler. The two recognizable voice commands are next and previous. At this point, we can simply close our XAML tags and write some C#.

Let’s begin with MainPage.xaml.cs

This page is going to simply add the Images to RadSlideView and handle the OnNavigatedTo and OnNavigatedFrom event handlers. This will ensure that when the page is “Navigated To” the SpeechManager will start listening for events and when the page is “Navigated Away” then it will reset the SpeechManager and clean up outstanding resources.

The entire code for this page is located below.

   1:public MainPage()
   2: {
   3:     InitializeComponent();
   4:this.Loaded += new RoutedEventHandler(SlideView_Loaded);  
   5: }
   6:  
   7:void SlideView_Loaded(object sender, RoutedEventArgs e)
   8: {
   9:string[] uris = newstring[8];
  10:for (int i = 0; i < 8; i++)
  11:     {
  12:         uris[i] = "Images/transitionsNew-" + (i + 1) + ".png";
  13:     }
  14:  
  15:     xSlideView.DataContext = uris;
  16: }
  17:  
  18:protectedoverridevoid OnNavigatedTo(NavigationEventArgs e)
  19: {
  20:base.OnNavigatedTo(e);
  21:     Telerik.Windows.Controls.SpeechManager.StartListening();
  22: }
  23:  
  24:protectedoverridevoid OnNavigatedFrom(NavigationEventArgs e)
  25: {
  26:     Telerik.Windows.Controls.SpeechManager.Reset();
  27:base.OnNavigatedFrom(e);
  28: }

Finishing up by adding the SpeechHandlers

Since you would typically want all the SpeechHandler code in a separate file for separation from the view and easier readability (when multiple Handlers are used), we will create a folder in our main project called, “SpeechHandlers” and add a class called that implements the ISpeechInputHandler interface. After doing that our solution explorer should look like the following with the other steps added:

Solution_Explorer

Double click on the PreviousNextSpeechHanlder.cs and replace the existing class with the following one:

   1:publicclass PreviousNextSpeechHandler : ISpeechInputHandler
   2: {
   3:  
   4:privateconststring NEXT_PHOTOS = "next";
   5:privateconststring PREVIOUS_PHOTOS = "previous";
   6:  
   7:publicbool CanHandleInput(string input)
   8:     {
   9:returntrue;
  10:     }
  11:  
  12:publicvoid HandleInput(FrameworkElement target, string input)
  13:     {
  14:if (string.Compare(NEXT_PHOTOS, input, StringComparison.InvariantCultureIgnoreCase) == 0)
  15:         {
  16:  
  17:             RadSlideView sv = target as RadSlideView;
  18:             sv.MoveToNextItem();
  19:             Telerik.Windows.Controls.SpeechManager.StartListening();
  20:  
  21:         }
  22:  
  23:if (string.Compare(PREVIOUS_PHOTOS, input, StringComparison.InvariantCultureIgnoreCase) == 0)
  24:         {
  25:             RadSlideView sv = target as RadSlideView;
  26:             sv.MoveToPreviousItem();
  27:             Telerik.Windows.Controls.SpeechManager.StartListening();
  28:         }
  29:     }
  30:  
  31:publicvoid NotifyInputError(FrameworkElement target)
  32:     {
  33:         MessageBox.Show("Error");
  34:  
  35:     }
  36: }

As we can see from the code snippet, whenever you implement the ISpeechInputHanlder interface then the CanHandleInput, HandleInput and NotifyInputError methods are added automatically for you. The CanHandleInput can return true or false depending on whether you want to enable or disable the API. The HandleInput is going to listen for certain keywords like ‘next’ or ‘previous’ in our example and perform actions based upon the voice commands. In this instance, it is going to move our RadSlideView to the Next or Previous Image. Of course, you could do anything you want for example, zooming in or out of an image, panning, etc. The NotifyInputError is going to trigger upon any type of input error, in this case I’m just showing a simple MessageBox, but you would probably want to log the error to a web service or such.

Conclusion

I hope this blog post helps clear up any confusion regarding Speech Recognition in Windows Phone 8. We are very excited about our Speech Recognition API and would encourage you to leave feedback. We have also extended the Telerik Picture Gallery sample app (with source code available) to support this new API. As stated earlier, this control is in CTP and we are working hard to make sure it is easy to use. Don’t forget that the source code for this project is available for download as well.

I would also like to take this opportunity and invite you to join the Nokia premium developer program to get RadControls for Windows Phone for free. They also have a vast variety of resources available to help you get your next app into the marketplace.

Thanks for reading!

-Michael Crump (@mbcrump)

image

About the author

Michael Crump - XAML RockStar!

Michael Crump

Michael Crump is a Microsoft MVP, INETA Community Champion, and an author of several .NET Framework eBooks. He speaks at a variety of conferences and has written dozens of articles on .NET development. He works at Telerik with a focus on our XAML control suite. You can follow him on Twitter at @mbcrump or keep up with his various blogs by visiting his Telerik Blog or his Personal Blog.

Fixing Visual Studio 2012 Intellisense for WinJS Files

$
0
0

I have been frustrated by Intellisense acting up when working on WinJS Windows Store applications.  Figure 1 is just an example of the quirky behavior that I’ve been experiencing:

image
Image 1

Fortunately, the fix is extremely easy, and I picked it up from Adam Freeman’s book on Apress “Metro Revealed: Building Windows 8 apps with HTML5 and Javascript

Add references in your JavaScript files to ui.js and base.js.  You can do this by dragging the files from your solution explorer.  They are located by expanding Windows Library for JavaScript 1.0, and then the “js”  folder.  Make sure you include the triple swack at the beginning of the line so VS know that they are a reference.  A double swack won’t work.

Once you do, you’ll find that Intellisense works wonderfully!

image

About the author

Philip Japikse

2012STLDODN.93x112Philip Japikse an international speaker, a Microsoft MVP, INETA Community Champion, MCSD, CSM/ CSP, and a passionate member of the developer community, Phil Japikse has been working with .Net since the first betas, developing software for over 20 years, and heavily involved in the agile community since 2005. Phil works as a Developer Evangelist for Telerik's RadControls for Windows 8 as well as the Just family of products (JustCode, JustMock, JustTrace, and JustDecompile) and hosts the Zero To Agile podcast (www.telerik.com/zerotoagile). Phil is also the Lead Director for the Cincinnati .Net User’s Group (http://www.cinnug.org). You can follow Phil on twitter via www.twitter.com/skimedic and read his personal blog at www.skimedic.com/blog.

Week 2 at AcceleratorHK

$
0
0

Last week was our second week at AcceleratorHK and things are starting to fall into a good cadence. On Monday, we had our first of the weekly 1:1 meetings and Paul and I worked directly with the teams on the issues that they face. We also had two amazing mentors come in:

First was Salim Virani, the creator of Leancamp. He talked to us about Customer Development and took a lot of time out of his vacation time in HK to spend with the teams on how to ask the right Customer Discovery and Customer Validation questions.

 IMG_20121113_160618

Later in the week we had Mikaal Abdulla, co-founder of 8 Securities, a Hong Kong startup success story, come in and tell us the story of leaving a well paying secure job and going out and starting a new business in Hong Kong, along with the war stories of raising money and some secrets to their brilliant marketing campaigns.

 IMG_20121115_150506

On Friday we did our first Friday all-hands meeting and was able to have an update by each team on their progress, practice their elevator pitch (next week I am going to put some of them in an actual elevator to practice), and ask the cohort for any help. We also gave out some Telerik tee-shirts. Smile We have a strict attendance policy, so one member had to phone in via Skype who was home sick. (Notice we gave him his tee-shirt anyway.)

IMG_20121116_140435

On Friday night we went out for some beers after a long week at the Accelerator doing Customer Development. The teams are still focusing on Customer Discovery and Customer Validation and will be in Week 3 as well. Stay tuned…

Future Mocking

$
0
0

Mocking legacy code is hard. Especially, if it’s a third-party library and you have little control over how it’s written. It is even more difficult to unit test a type that is instantiated internally. One can argue that it should be refactored to accept dependencies via constructor injection.  However, constraints such as time, budget, experience with the offending code, or even access to the source often prevent paying down the technical debt accumulated in these legacy systems.  

This post will show you how to mock an external library (concept) where it calls a login service class that cannot be sent via dependency injection

LoginService class validates user based on username and password:

Future mocking blog post image

This is instantiated and called by a class internally whenever user is validated:

Future mocking blog post image

This example is intentionally simplistic. The goal here is to show the way to mock such scenarios where it is out of the developer’s hands to refactor the code in such a way as to allow for wrapping the class with a proxy or even replacing it with an interface.

In JustMock it is possible to mock a member regardless of its instance. This is of course limited to the particular context defined by the developer of the test so as to not lead to side effects, and everything behaves as expected. 

The mechanism for forward mock a dependency is by using the IgnoreInstance() method when arranging the behavior of the mock.  This instructs the profiler to replace calls to that method on instances in the call chain with the mocked call. 

In order to assert that ValidateUser method is called, I wrote the following specification:

Future mocking blog post image

This works great under most cases. However, if LoginService throws an exception inside its constructor (as in our example service implementation) or the constructor is executing code that is interfering with the test (such as open a database connection) then the above specification will fail. 

The good news is that JustMock has you covered.  Instead of creating a new instance of your service,  you create a Mock of your concrete type and mark the constructor as mocked. This will then bypass and code in the constructor of the mocked type, and your test will work as expected.

My updated specification is shown in the next code listing:

Future mocking blog post image

This will make the test green as I have wanted. 

Although sending instance via Dependency Injection is considered a much better way of handling dependencies (see this post by my coworker Phil Japikse on Why SOLID Matters), it is a simple fact that you will have to work with code that is not perfect and clean.  In that regard JustMock can save your day and help you  deliver more than expected. 


Happy Coding!


JustMock blog banner

About the author

mehfuz

Mehfuz Hossain

Mehfuz works as the Team Lead at Telerik focusing on JustMock. He is passionate playing around with the latest bits. He has been a Microsoft MVP, author of OS projects like LinqExtender and LINQ to flickr. Prior to working at Telerik , Mehfuz worked as a core member in many high volume web applications including Pageflakes that is acquired by Live Universe in 2008. He is a frequent blogger and was also a contributor and site developer at dotnetslackers.com. He is a firm believer of openness and currently enjoys his free time with objective-c and nodejs bits and never minds writing in textmate.

@mehfuzh

What to Expect from Telerik's ASP.NET AJAX Control Suite in February 2013

$
0
0

We spent the past few weeks reviewing the feedback we’ve received from you through support tickets, our public issue tracking system, emails to our sales team, talks with our evangelists at conferences, etc. We are now officially ready to announce the plans we’ve come up with based on your input.

Basically, we will develop our ASP.NET AJAX control suite in several directions:

1. Enhancing User Experience

  • Persistence Framework– with Q1 2013 your users will be able to persist app settings between sessions.
  • Improved performance thanks to modern (light) rendering leveraging HTML5 and CSS3 in modern browsers for our Window, Dock, Rating, Tooltip, Button and FormDecorator controls.
  • Mobile support– improving the behavior of all controls under iOS6 and Windows 8 touch.
  • Accessibility - We will aim at making all RadControls Section 508 compliant and at least level AA compliant with the W3C Web Content Accessibility Guidelines 1.0/2.0.

2. Skinning
With Q1’13 we are making your skinning tasks a lot easier. Enjoy at least one new skin and SASS support allowing you to build custom skins more quickly.

Other major things we’ve planned include:

  • A new control incorporating TreeView functionality in a ComboBox
  • Two new controls extracting RadComboBox functionality in order to make it lighter – DropDownList and an advanced input with the look and feel of website search boxes.

We have a lot of enhancements to the existing controls planned as well and you can take a look at them at our Roadmap.

Don’t forget to let us know what you think about our plans! It’s important for us. By the way, we still don’t have any clue what name to choose for the “TreeViewComboBox” control, so feel free to jump in with suggestions. Thanks in advance!

About the author

Iana Tsolova

Iana Tsolova

Iana Tsolova is Unit Manager of Telerik’s ASP.NET AJAX division. She joined the company back in 2008 as a Support Officer and has since occupied various positions at Telerik, including Senior Support Officer, Team Lead at one of the ASP.NET AJAX teams and Technical Support Director. Iana’s main interests are web development, reading articles related to geography, wild nature and latest renewable energy technologies.


JustCode JavaScript Templates for WinJS

$
0
0

I’ve been doing a lot of WinJS work recently, and I am an avid user of the JustCode Template functionality.  So, I thought I’d share my templates as I have them now, and will update this post as I update them or create more.  For more information on creating JustCode templates, please see this help content.

For each template, I show my acronym in parenthesis.  For example, the first template’s acronym is “winjsfile”.  I also don’t show the results for every template, since some of them are obvious.

Templates for New JavaScript File

This template and the related templates following are used when I have created a new, blank JavaScript file.

Template (winjsfullfile):

/// <reference path="//Microsoft.WinJS.1.0/js/ui.js" /> 
/// <reference path="//Microsoft.WinJS.1.0/js/base.js" /> 
(function () { 
    "use strict"; 
    WinJS.Namespace.define("$1$", { 
         | 
    }); 
})();

Related templates

Microsoft WinJS References and Self Executing Function

Template (winjsfile):

/// <reference path="//Microsoft.WinJS.1.0/js/ui.js" /> 
/// <reference path="//Microsoft.WinJS.1.0/js/base.js" /> 
(function () { 
    "use strict"; 
  | 
})();
Microsoft WinJS References

Template (references):

/// <reference path="//Microsoft.WinJS.1.0/js/ui.js" />
/// <reference path="//Microsoft.WinJS.1.0/js/base.js" />
|
Self Executing Function

Template (sefunc):

(function () {
    "use strict";
	|    
})();
WinJS Namespace

Template (namespace):

WinJS.Namespace.define("$1$", { 
   | 
});

Namespace Templates

I’ve created several templates for common items in namespaces, such as property functions, observable properties, and class definitions.

Property Function

Template (propfunc):

$1$: function ($2$)  { 
    | 
},

Observable Property

Template (bindingprop):

$1$: WinJS.Binding.as({ 
   | 
}), 

WinJS Class (within a namespace)

Template (winjsclass):

$1$:WinJS.Class.define(function($2$) {
this._initObservable();
this.$2$ = $2$;
          |
}),
WinJS Class Binding Mixin
WinJS.Class.mix($1$,
             WinJS.Binding.mixin,
             WinJS.Binding.expandProperties({ $2$: "", $3$: ""})
);

Miscellaneous Templates

Binding List

Template (bindinglist):

var $1$ = new WinJS.Binding.List();

Event Listener

Template (listener):

$1=SELECT_VARIABLE()$.addEventListener('$2=SELECT(click,change,focus,load,select,submit)$', function (e) { 
    | 
}); 

Pages

Template (pages):

WinJS.UI.Pages.define("/$1$.html", { 
  ready: function(element) { 
         | 
  }, 
});

 

I hope these help.  If you have some great templates, share them with me!

Happy Coding!

About the author

Philip Japikse

2012STLDODN.93x112Philip Japikse an international speaker, a Microsoft MVP, INETA Community Champion, MCSD, CSM/ CSP, and a passionate member of the developer community, Phil Japikse has been working with .Net since the first betas, developing software for over 20 years, and heavily involved in the agile community since 2005. Phil works as a Developer Evangelist for Telerik's RadControls for Windows 8 as well as the Just family of products (JustCode, JustMock, JustTrace, and JustDecompile) and hosts the Zero To Agile podcast (www.telerik.com/zerotoagile). Phil is also the Lead Director for the Cincinnati .Net User’s Group (http://www.cinnug.org). You can follow Phil on twitter via www.twitter.com/skimedic and read his personal blog at www.skimedic.com/blog.

Coded UI Test Support for WPF

$
0
0

Introduction

Hello again!

We recently released a brand new XAMLFlix episode on RadPivotGrid Beta and RadAutoCompleteBox. Both of these video series are dedicated to getting you up to speed quickly with our Telerik controls for WPF and Silverlight. So while you are playing with the new controls, we thought you might like a crash course on how you can use Coded UI Testing with RadControls for WPF. We will specifically be taking a look at RadGridView, as it is one of our most popular and requested controls to show this integration with.

The video is hosted on Telerik TV and you can watch it now or download the source code for further exploration. It is also important to note that this video is the foundation of something larger to come (which is our upcoming support for Level 2, 3 and 4).

What is Coded UI Testing and why is it important to me?

Coded UI tests are automated UI tests which can be created with various versions of Visual Studio 2010 or Visual Studio 2012 Premium and up to test different kinds of user interfaces. These UI includes: Web, WPF, Silverlight and Windows Forms.

Automated UI Testing is not just limited to what Microsoft provides, Telerik provides our own with Test Studio and several others exist. Telerik wants to support whatever UI testing framework your company has chosen and with our Q3 2012 release, we have added support for Coded UI Testing for RadControls for WPF. We begin with Level 1 support and are planning to add additional levels with Q1 2013. I’ll summarize what all 4 levels provide.

Coded UI Levels 1 – 4:

  1. Level 1: Basic Record and Playback – This allows the recorder to record click events, identify elements, navigation and validation. This is all possible via the recorder dialog that pops up after you create a new Coded UI Test.
  2. Level 2: Rich Property Validation – This allows assertions on custom properties and the playback engine can validate properties during test run.
  3. Level 3: Code Generation – Special classes can be written for a control and the test code is more readable.
  4. Level 4: Intent Aware Actions – Recorder aggregates actions based on filter rules in Action filter, can record only intended steps based on control behavior and you can set information in table cells.

 

What is a Coded UI Test Made-up of?

Now that you have a solid understanding of what Coded UI is and what it is made up of, let’s begin by taking a look at our solution explorer of a Coded UI Test Project. This is the exact same one as shown in the video.

image

  • Properties->AssemblyInfo.cs– This contains general information about an assembly with information such as Title, Description and Version information.
  • References– Contains the standard Microsoft.VisualStudio.QualityTools* and TestTools*, but also includes Telerik.WinControls.CodedUI.2012.
  • CodedUITest1.cs contains the actual CodedUI test class, method invocation, and assertion invocation.
  • UIMap.uitest contains an XML representation of the UIMap class which includes windows, controls, properties, methods, assertions and actions.
    • UIMap.cs–any customization done to the UIMap are stored in this file.
    • UIMap.designer.cs– contains the generated code once a tester begins recording UI interactions.

Where to go from here?

So far we have discussed the different levels of Coded UI, taken a look at what the project consist of and the support that Telerik brings for it in Q3 2012. I’d recommend your next step is watching the video and downloading the sample source code.

If you have any questions regarding Coded UI, then feel free to leave me a comment on this blog post or send me a tweet on Twitter at @mbcrump. You can also download the Telerik WPF control suite right now to give it a shot!  

Thanks again and I’ll see you in the next blog post.

-Michael Crump
@mbcrump

About the author

Michael Crump - XAML RockStar!

Michael Crump

Michael Crump is a Microsoft MVP, INETA Community Champion, and an author of several .NET Framework eBooks. He speaks at a variety of conferences and has written dozens of articles on .NET development. He works at Telerik with a focus on our XAML control suite. You can follow him on Twitter at @mbcrump or keep up with his various blogs by visiting his Telerik Blog or his Personal Blog.

API Testing with Telerik Fiddler

$
0
0

Fiddler has long been the tool of choice for developers and testers who are building and verifying APIs exposed over HTTP(S). In this post, we’ll explore the existing features Fiddler offers for API Testing and announce new capabilities we’ve released in Fiddler 2.6/4.6.

Composing API Calls

The Composer tab enables the authoring of arbitrary HTTP(S) requests using any HTTP method, url, headers and body, and the many Inspectors permit examination of responses of any type, including XML, JSON, BSON and myriad other formats. Over the last few years, the power of the Composer has grown, and it now offers many conveniences, including a Request History pane:

image

… to allow simple reuse of existing requests. The powerful Scratchpad tab allows you to easily display a list of requests and execute those requests as needed—a great feature for live demonstrations of your API for tech talks and the like:

image

As you can see in the screenshot above, the Scratchpad even supports executing requests expressed curl syntax, so you can easily exercise APIs that are documented in terms of the parameters passed to that popular tool.

 

Capturing API Calls

Of course, Fiddler is best known as a proxy debugger, and its ability to capture traffic from nearly any source means the fastest way to generate API tests is to simply capture the API traffic from an existing client and modify and augment those tests as desired. You can start with a baseline of the calls your clients presently send, and add new tests to probe for performance, security, error handling and other problems.

One of the most powerful capabilities Fiddler offers is capture of traffic from almost any device (iOS, Android, Windows, Mac and so on); you can easily exercise your mobile clients’ API endpoints without adding any new software to the device itself!

 

Resending Requests from the Web Sessions List

After you’ve collected a set of requests in Fiddler, you can easily save them to a Session Archive Zip (.saz) file for convenient reuse at any time. To resend the traffic, just load the SAZ file, select the desired requests and use the Replay submenu on the Web Sessions list’s context menu to resend the requests. Common choices include:

  • Reissue Requests: Resend the selected requests as quickly as possible
  • Reissue Sequentially: Resend the selected requests, waiting for a response to each before sending the next
  • Reissue and Verify: Resend the selected requests, verifying each response’s status code and body match the original response

Of these options, the last is perhaps the most interesting—you can very easily regression test an API set by simply collecting “good” traffic in a SAZ file and then using that traffic as a baseline against which later verifications will be conducted. The verification performed is rather crude, which is why we’re excited to announce…

Automated API Testing

The new APITest extension to Fiddler greatly enhances its power to validate the behavior of web APIs. Click View> Tabs> APITest to show the APITest tab. The bulk of the tab displays a Test List, a list of API requests and Validators.

image

Tests can be added to the list by simply dragging and dropping Sessions from Fiddler’s Web Sessions list. You can then use the context menu to specify a Validator and optionally mark it with a Note (comment) and optionally assign it to a group.

Validators

Validators offer a lightweight way to judge the success or failure of a test, and support many of the same operators used by Fiddler’s AutoResponder feature. As seen in the screenshot above:

  • EXACT:This is a Test: Ensure the status code matches and response body contains (case-sensitively) the text This is a Test 
  • Updated via API: Ensure the status code matches and response body contains (case-insensitively) the text Updated via API
  • {CODE}: Only ensure the response status code matches the original status, for example, 201 for the first test
  • {BODY}:(Not pictured above) Ensure the response status code matches and the response body is identical 

In addition to the EXACT: operator prefix, the REGEX: and NOT: prefixes are also supported for text searches:

image

The HEADER: prefix allows you to ensure that the response bears a specified header containing a given value (for example, HEADER:Content-Encoding=gzip ensures that the response has a Content-Encoding header showing that the response used GZIP compression).

The SCRIPT: prefix allows you to specify a FiddlerScript function in your CustomRules.js file to use to evaluate the response; the named function is passed both the test Session and the baseline (original) Session and can evaluate any criteria you like to return whether or not the test has passed. Beyond examining the headers and body of the response, you could, for instance, evaluate the values in the Session’s Timers object and fail the test if the response took more than 100 milliseconds.

  // This method is called by "SCRIPT:CheckTest" validators; it
  // returns TRUE if the Test passes, and false otherwise.
  static function CheckTest(oRun: Session, oBase: Session): boolean
  {
    // Simplest possible validator
    if (oBase.responseCode != oRun.responseCode)
    {
        oBase["api-lastfailreason"] = "Mismatched status code...";
        return false;
    }

   
var timeTotal = 0;
    timeTotal = (oRun.Timers.ServerDoneResponse - oRun.Timers.ClientDoneRequest).TotalMilliseconds;
    if (timeTotal > 100)
    {
        oBase["api-lastfailreason"] = "Performance Too slow...";
        return false;
    }


    return true;   
  }

Script Events

Before your Test List is run, the BeforeTestList method (if present in your FiddlerScript) is run, permitting you to adjust the requests as needed:

  static function BeforeTestList(arrSess: Session[]): boolean
  {
    // In this method, you can do any setup you need for the test,
    // e.g. adding an Authorization: token OAUTH value that you
    // obtained programmatically...
    var sOAUTHToken = obtainToken();
    if (String.IsNullOrEmpty(sOAUTHToken)) return false;

    for (var i: int=0; i<arrSess.Length; i++)
    {
      arrSess[i].oRequest["Authorization"] =  sOAUTHToken;
    }
   
    MessageBox.Show("Token Set. Running " + arrSess.Length.ToString() +
                    " tests.", "BeforeTestList");

    return true; // Test should proceed; return false to cancel
  }

After all of the individual test cases are executed, the AfterTestList method allows you to validate any post-conditions, log the results of the Test list or perform other operations. The method is passed a TestListResults object which contains an enumerable list of TestResult objects. Each result contains the baseline (original) Session, the test Session and an IsPassing boolean indicating whether the test passed. The WriteFailuresToSAZ convenience method will write all failing TestResults to a SAZ file for later analysis.

  static function AfterTestList(listResults: TestListResults)
  {
    for (var oResult in listResults)
    {
      FiddlerApplication.Log.LogString(oResult);
    }

    listResults.WriteFailuresToSAZ("C:\\temp\\lastfailure.saz");
  }

 

Working with Test Lists

A Test List is simply a set of Sessions each of which contains several custom Session Flags (api-testitem, api-Validator, api-LastResult, and api-LastFailReason). As a consequence, these lists can be saved and loaded as regular SAZ files; their “Test List” functionality only lights up when loaded into the APITest tab using its context menu. The menu commands are largely self-explanatory:

image

  • Run Selected Tests runs only those tests that are currently selected in the UI
  • Rerun Failed Tests runs all tests that are marked as failing
  • Set Comment… sets the Notes column for the selected tests
  • Set Validator… assigns the validation criteria for the selected tests
  • Set Group… assigns the tests to a UI group, useful for organizing your test list
  • Inspect baseline… opens the original Session in Inspectors for viewing or editing
  • Promote moves the selected test earlier in the run order
  • Demote moves the selected test later in the run order
  • Clone creates a copy of the current test, useful when you need to use multiple validators
  • Save Test List saves the test list to a SAZ file
  • Load Test List adds the tests from a SAZ file to the current test list

You can temporarily disable one or more tests from running by pressing the spacebar with the desired tests selected.

FiddlerCore

While the new APITest extension offers powerful functionality, many larger enterprises instead choose to use the FiddlerCore .NET Class Library to build their API Testing infrastructure. FiddlerCore allows you to fully customize the behavior of your testing logic, driving the test using the .NET Language of your choice (typically C#). Because FiddlerCore does not utilize any of Fiddler’s UI, it can easily be integrated into existing test automation suites and can be used in console and service applications.

Load Testing APIs

The Fiddler-native Session Archive Zip file format is supported by Telerik Test Studio’s Load Testing product, allowing you to simply import a SAZ file that exercises your API set, configure the number of virtual users and run time, and generate load instantly or on the schedule you set. If you’d like to apply validation logic while your server is under load, run the Load Test in Test Studio solution and in parallel execute your Test List in Fiddler.

 

We hope you find Fiddler’s API Testing support useful, and we look forward to your feedback as we continue to enhance the tool.

 

What's New in Telerik Fiddler 4.6

$
0
0
Telerik Fiddler version 4.6 (and v2.6 targeting .NET2) is now available for download. The new version includes several new features and dozens of tweaks and bug fixes, described in this article.

View > Tabs Menu

The new View > Tabs menu offers a list of tabs that are hidden by default. image
The Preferences command displays a tab that ​enables you to edit Fiddler’s Name/Value preferences.

The new APITest command displays the new Fiddler APITest tab that enables easy testing of web APIs.

The AutoSave command (formerly located in the Tools menu) permits you to automatically save Session Archive Zip files on a regular schedule.

Note: In the future, this submenu will become an extension point to allow developers to easily expose optional UI tabs.

Lint Filters

Fiddler’s Lint feature enables you to control how Fiddler reports violations of the HTTP protocol and other errors. Controlled on the Tools > Fiddler Options > General tab, you can leave the If protocol violations are observed setting at the basic “Warn on Critical errors” section or adjust it to “Warn on all errors”; the latter setting performs more tests on traffic to find mistakes that could cause clients or servers to misbehave. However, this setting can get pretty noisy. To suppress specific warnings, you can now use the Filter link on the Protocol Violation Report dialog. image
Each Lint warning now has a unique code consisting of a letter and three digits. The letter prefix indicates the severity:

  • L: Common "problem", low impact, unlikely to break anything
  • M: Significant problem, likely to break functionality in one client
  • H: Important problem likely to significantly break functionality in multiple clients
You can exclude an entire class of warnings by simply including the prefix in the list of exclusions.

Single Session Timeline

The Timeline tab in Fiddler ​enables you to visualize the download of multiple Sessions at once so you can view parallelism and connection reuse. In Fiddler 4.6, the view of a single Session has been enhanced so you can visualize how the content of the Session was downloaded. You can determine, for instance, whether the headers were flushed immediately or the client was forced to wait for headers until the body was ready, and you can determine whether download speed improved or regressed as the download proceeded. For instance, in this chart, the server took 2.5 seconds to return the headers and began to slowly stream the body in small chunks. As the download progressed, the speed improved until completion at just over 9.2 seconds: image 

Interface Tweaks

A new Copy as Image command on each Inspector’s tab context menu allows you to copy an image of the tab’s contents to your clipboard for easy pasting in an email or blog post. The Headers, XML and JSON Inspectors allow you to easily highlight nodes of interest—simply press the spacebar on a node to temporarily render it with a yellow highlight: image
The new Math context menu appears when you right-click on a numeric column in the Web Sessions list; the menu currently offers a single command, Sum and Average, which shows these attributes of the selected Sessions: image
The Composer tab now offers a splitter between the headers and body boxes, so you can adjust their height as desired:

image
Pressing the / key while in the Web Sessions list now enters QuickSearch mode in the QuickExec box, selecting any Sessions whose URL contains the text you type.

Hash Support

Fiddler now offers enhanced support for computing hashes of blocks of bytes or strings. The Tools > TextWizard feature now offers a quick way to get a hash (MD5 to SHA512) of a block text, in either base64 or dashed hexadecimal format: image
New methods are also available for FiddlerScript to compute hashes. For instance, you can copy the following block to just inside your Rules > Customize Rules > Handlers class: [See Code]
 
When you save the script, Fiddler adds a new tab to display theSubresource Integrityattributes for the selected response bodies: image 

FiddlerScript Improvements

BindUITab Enhancements

As seen in the Resource Integrity Hashes example above, the BindUITab attribute ​enables you to create new tabs inside Fiddler that are populated based on the selected Sessions. BindUITab now offers a second parameter that enables you to specify one or more of the following options:
  • <nowrap>: The RichEdit control should not wordwrap lines
  • <nolink>: The RichEdit control should not detect or underline urls
  • <html>: Instead of using a RichEdit control, the function’s response will be rendered as HTML inside a Web Browser Control

BeforeFiddlerShutdown event

Fiddler now exposes a BeforeFiddlerShutdown event that enables extensions or FiddlerScript to block shutdown of Fiddler; this may be useful if you wish to prompt the user for permission to lose unsaved work, etc. A Fiddler extension should attach an event handler:
   
FiddlerApplication.BeforeFiddlerShutdown += (o, c) => { c.Cancel = (DialogResult.Cancel == MessageBox.Show("Allow Fiddler to close????", "Go Bye-bye?", MessageBoxButtons.OKCancel)); };


Within FiddlerScript, you can add a method to the existing Handlers class:
   
static function OnBeforeShutdown(): Boolean {
  return ((0 == FiddlerApplication.UI.lvSessions.TotalItemCount()) ||
    (DialogResult.Yes == MessageBox.Show("Allow Fiddler to exit?", "Go Bye-bye?",
    MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)));
}

AutoResponder Improvements

The AutoResponder now supports the NOT: operator inside the METHOD:, HEADER:, and FLAG:, operators. For instance, if you’d like the AutoResponder only to impact requests from Google Chrome, add this rule to the top of your list:

image

Microsoft Edge Support

Fiddler has been updated to recognize Microsoft’s new Edge browser as a Web Browser, so features ​such as the Process Filter in the Status Bar: image
 …and in the Browse command in the Fiddler toolbar: image
... work as expected. Note: You should use the WinConfig button at the left of Fiddler’s toolbar to enable Windows 10 “Store” applications to run Fiddler. By default, you shouldn’t need to use the WinConfig button for Edge, because Edge’s about:flags enables access to loopback by default.

ImageView Enhancements

FavIcon Preview

When a site uses an .ICO file as its favicon, the icon may contain multiple different images that are used, depending on the user’s device and the context in which the icon is rendered. Fiddler’s ImageView Inspector now renders all of the images contained within the .ICO file like so: ImageView showing icon 

JPEG Thumbnails

Websites should generally strip embedded thumbnails from JPEG files. Embedded thumbnails are a common source of bloat, wasteful bytes that aren’t used by the client. However, some sites fail to optimize their images by removing thumbnails. In some cases, an image thumbnail may even contain data which was never meant to be made public, if, for instance, the larger image was cropped without regeneration of the thumbnail. The ImageView now ​enables you to extract the thumbnail image as a new Session added to the Web Sessions list: Extract Thumbnail 

AutoSave Enhancements

Fiddler's AutoSave feature (now found under View > Tabs > AutoSave) now supports several preferences to control its behavior:

Set fiddler.extensions.AutoSave.AlwaysOn to true to have Fiddler automatically activate AutoSave mode when it starts.

Set fiddler.extensions.AutoSave.Minutes to the number of minutes to collect traffic between each save operation; the default is 5.

Set fiddler.extensions.AutoSave.HeadersOnly to true if you'd like the SAZ file to contain only the request and response headers, omitting the bodies.

Set fiddler.extensions.AutoSave.Path to the folder path under which auto-saved SAZ files should be stored.

Additional Upgrade Notifications

By default, Fiddler’s automatic update notifications will only show if a significant change in version number occurs. For instance, say you’re running version 4.6.0.2 and version 4.6.0.3 becomes available. By default, Fiddler will only tell you about this minor update if you manually check for new versions by clicking Help > Check for Updates. When Fiddler 4.6.1.0 becomes available, the updater detects this larger change in version number and prompts you to upgrade.

If you would prefer Fiddler to notify you of every update automatically, use the black QuickExec box below Fiddler’s Web Sessions list to enter the following command:

    prefs set fiddler.updater.BleedingEdge true

With this preference set, you’ll see more frequent notice of upgrades. On one hand, that’s great—you’ll get the latest Fiddler improvements ahead of most other people. On the other hand, as a bleeding-edge user, you’re also more likely to uncover any bugs we inadvertently introduce in new versions.

Fiddler Improvement Program

You may now opt-in to sending telemetry information about your PC environment and Fiddler usage. Within your first few boots of Fiddler, you’ll see the following dialog:

image
Telemetry data is reported over HTTPS and its usage is governed by the Telerik Privacy Policy. If you later change your mind, you can control your participation using the checkbox Participate in the Fiddler Improvement Program on the Tools > Fiddler Options > General tab. Note: If an administrator has set the BlockUpdateCheck registry key in the HKLM registry hive, users cannot opt-in to the Fiddler Improvement Program.

The Telerik Analytics integration into Fiddler has already yielded several bug fixes and has helped us prioritize our investments in performance and feature improvements. We’ll write more about what we’ve learned from Fiddler Telemetry in a future blog post.

Performance Improvements

One early finding from our Fiddler Telemetry is a surprising number of users are running on 32-bit Windows, where the address space limitations mean they often run into “out of memory” errors. To help mitigate this, we’ve made some under-the-hood changes to how Fiddler allocates memory, and this is only the beginning of a larger project to improve Fiddler’s overall performance for everyone.

As a part of our performance investigations, two new commands were added to the QuickExec box, !memory and !threads. Invoke these commands to add information to the Log tab for troubleshooting purposes. If you find Fiddler is running more slowly than expected, sending the output of these commands to us will help narrow down the problem.

We hope you enjoy the new version of Fiddler!

Use Candlestick Chart and DataSource for iOS to Display JSON

$
0
0

Candlestick chart is a financial chart type, which is widely used to present price movements. It visualizes large amounts of data in a simple, readable way, enabling users to follow the price movements for the whole period or the current moment.

Each candlestick is described with four values–open, close, high and low and consists of body and an upper and a lower shadow.

If you want to dive into the art of the financial science and find out more about the candlestick charts, here is the magic explained.

From Theory to Practice–a Long Way to Go...or Not So Long

So far, we know the candlestick chart is convenient and useful, and we love it, but how do we implement it quickly, easily and without being a math star.

Don’t worry, the Telerik UI for iOS comes to the rescue! With the TKChart component, all we have to do is pass the data, and our chart will be ready--no math, not even a single calculation. I promise!

Simple Data Consumption

Let’s try it and generate some data for the chart.

let openPrices = [100, 125, 69, 99, 140, 125]
let closePrices = [85, 65, 135, 120, 80, 136]
let lowPrices = [50, 60, 65, 55, 75, 90]
let highPrices = [129, 142, 141, 123, 150, 161]
var dateNow = NSDate()
var financialDataPoints = [TKChartFinancialDataPoint]()
         
for var i = 0; i < openPrices.count; ++i {
     var date = dateNow.dateByAddingTimeInterval(CDouble(60 * 60 * 24 * i))
     financialDataPoints.append(TKChartFinancialDataPoint(x: date, open: openPrices[i], high: highPrices[i], low: lowPrices[i], close: closePrices[i]))
}

Now we have to create a TKChart, and add TKChartCandleStickSeries populated with our data.

let chart = TKChart(frame: CGRectInset(self.view.bounds, 15, 15))
chart.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
self.view.addSubview(chart)
         
let candlestickSeries = TKChartCandlestickSeries(items: financialDataPoints)
chart.addSeries(candlestickSeries)
         
let xAxis = chart.xAxis as! TKChartDateTimeAxis
xAxis.minorTickIntervalUnit = TKChartDateTimeAxisIntervalUnit.Days
xAxis.setPlotMode(TKChartAxisPlotMode.BetweenTicks)
xAxis.majorTickInterval = 1

Piece of cake!

Couple of lines of code, and we have a shiny candlestick chart.

Telerik Candlestick Chart for iOS

Now, what if our data comes from a web service?

Consuming JSON Data from a WebService with TKDataSource

The result from the request usually comes in JSON format, so we have to get only the JSON objects we need, deserialize them and convert them to TKChartDataPoint objects. After that we can pass them to the chart. Managing all these operations is not a show stopper, but it would be much better if we could use one component to manage them all.

Fortunately, the TKDataSource component is here to make data management more convenient than ever. It is a non-visual component that consumes data from various sources, including web services. It also supports shaping operations ​such as sorting, filtering and grouping. Finally, it works perfectly with data-enabled visual controls.

We can use the TKDataSource combined with TKChart to get data from a web service, reshape it and visualize it.

First of all, we create a TKChart the same way we did it above.

let chart = TKChart(frame: CGRectInset(self.view.bounds, 20, 20))
chart.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
self.view.addSubview(chart)

Then we create the TKDataSource and set it up to get the data from the web service.

For this demo, I am going to use Yahoo! Finance APIs and get the stats of Progress Software Corporation between 10/03/2015 and 20/03/2015.

let dataSource = TKDataSource()
let url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20%20%20yahoo.finance.historicaldata%20%20%20%20%20%20%20%20%20where%20%20symbol%20%20%20%20=%20%22PRGS%22%20%20%20%20%20%20%20%20%20and%20%20%20%20startDate%20=%20%222015-03-10%22%20%20%20%20%20%20%20%20%20and%20%20%20%20endDate%20%20%20=%20%222015-03-20%22&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback="
 
dataSource.loadDataFromURL(url, dataFormat: TKDataSourceDataFormat.JSON, rootItemKeyPath: "query.results.quote") { (error:NSError!) -> Void in
     if(error != nil) {
          NSLog("Can't connect with the server")
     }
}

We got the JSON data, but the web service returns a bit more information than we need to populate our chart, so we specify that we want to deserialize only the objects in the query.results.quote path.

The dataSource object now contains a collection of the stats for each day the service has returned. As you can see they are deserialized and ready to use.

DataSource for iOS by Telerik

For your convenience, we are iterating over the items of the dataSource and are converting the Date property from NSString to NSDate. This is necessary to have our data visualized properly.

dataSource.map { (item:AnyObject!) -> AnyObject! in
     let dateFormatter = NSDateFormatter()
     dateFormatter.dateFormat = "yyyy-MM-dd"
     let date: NSDate = dateFormatter.dateFromString(item.valueForKey("Date") as! String)!
     item.setValue(date, forKey: "Date")
     return item
}

Now we have to tell the dataSource how to visualize the data.

In the createSeries method, we define the type of series the chart will be working with, in this case TKChartCandleStickSeries.

dataSource.map { (item:AnyObject!) -> AnyObject! in
     let dateFormatter = NSDateFormatter()
     dateFormatter.dateFormat = "yyyy-MM-dd"
     let date: NSDate = dateFormatter.dateFromString(item.valueForKey("Date") as! String)!
     item.setValue(date, forKey: "Date")
     return item
}

With the createPoint method, we get the data from each serialized item and convert it to a TKChartFinancialDataPoint object, which can be visualized by the Candlestick chart.

dataSource.settings.chart.createSeries { (group: AnyObject!) -> TKChartSeries! in
    let series = TKChartCandlestickSeries()
    return series
}
         
let formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
         
dataSource.settings.chart.createPoint { ( seriesIndex:Int,  dataIndex:Int,  item:AnyObject!) -> TKChartData! in
     var point = TKChartFinancialDataPoint(x: item.valueForKey("Date"), open:     formatter.numberFromString(item.valueForKey("Open")as! String), high: formatter.numberFromString(item.valueForKey("High")as! String), low: formatter.numberFromString(item.valueForKey("Low")as! String), close: formatter.numberFromString(item.valueForKey("Close")as! String), volume: formatter.numberFromString(item.valueForKey("Volume") as! String))
     return point
}

Finally, we should set the dataSource property of the chart to our dataSource object and set up the xAxis to display date objects.

chart.dataSource = dataSource
let xAxis = chart.xAxis as! TKChartDateTimeAxis
xAxis.minorTickIntervalUnit = TKChartDateTimeAxisIntervalUnit.Days
xAxis.setPlotMode(TKChartAxisPlotMode.BetweenTicks)
xAxis.majorTickInterval = 2
         
let yAxis = chart.yAxis as! TKChartNumericAxis
yAxis.range.minimum = 25
yAxis.majorTickInterval = 1

This is the final result:

Candlestick Chart w/ JSON Data

You can set your imagination free and explore the other great options the TKChart and TKDataSource offer.

In case you want to continue where we left off, here is the full code of the example in Objective-C and Swift. To run the projects, download and install a free trial ​Telerik UI for iOS.

Enjoy!

Download UI for iOS by Telerik
Viewing all 4135 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>