August 1, 2014

Xamarin Indie Now $25/Month

By

We are very excited to announce that we are now offering Xamarin Indie edition as a month-to-month subscription for just $25/month. As always, Xamarin Indie edition is available to companies with fewer than five employees.

At just $25 per month for iOS or Android, Xamarin Indie makes it incredibly easy to build and ship native mobile apps written in C#, with an extremely affordable price point accessible to anyone.

This offer is available as an experiment through August 31, 2014. We’ll decide whether to extend this offering to new customers depending on what happens in August, but if you sign up for a subscription in August, you can stay on a month-to-month plan as long as you like.

Go get yours today!

Some quick FAQs:

Who is eligible for a monthly Xamarin Indie subscription?
Developers at companies or organizations with up to 5 employees may purchase Xamarin Indie. Companies with more than 5 employees must purchase a Xamarin Business or Enterprise subscription.

Can I continue to use Xamarin after my monthly Indie subscription expires?
Monthly Xamarin Indie subscriptions renew automatically each month. If you allow your subscription to expire, you will no longer be able to use Xamarin to build mobile apps. Your existing mobile apps will continue to work.

Can I still buy Xamarin Indie edition as an annual subscription?
Yes! Xamarin Indie edition is still available as an annual subscription at the normal price of $299/platform/year.

I already have an annual subscription of Xamarin Business or Xamarin Enterprise. Can I add on a monthly Xamarin Indie subscription?
No. You must purchase the same type of subscription for all platforms. For example, if you already have an annual subscription of Xamarin Indie iOS, you cannot add a month-to-month subscription of Xamarin Indie Android.

Can I purchase a month-to-month subscription of Xamarin Business or Xamarin Enterprise?
No. Xamarin Business and Enterprise editions are only available as an annual subscription, and we do not foresee ever offering those as a monthly subscription.

What happens if I sign up for a monthly Xamarin Indie subscription and you decide to stop offering it?
If you subscribe to a monthly Xamarin Indie subscription prior to August 31, 2014, you’ll continue to pay just $25 per month until you choose to cancel your subscription.

How can I pay for a Xamarin Indie monthly subscription?
Dogecoin! Just kidding. We can only accept credit card payments for monthly subscriptions.

Discuss this post in the Xamarin forums.

TwitterFacebookGoogle+LinkedInEmail
July 30, 2014

Put Some Office 365 in Your Apps

By

Office 365 is Microsoft’s cloud-based solution providing access to services like Mail, Calendar, Contacts (using Exchange Online), Storage (using OneDrive) and Collaboration tools (using SharePoint Online). These services are backed by Azure’s robust infrastructure and use Microsoft Azure Active Directory (AD) to authenticate, authorize and grant access to users. Office 365 LogoHowever, developers like us have always want to extend these services in some way. For this reason, Microsoft has released Client Libraries for Office 365 and, good news, they are Portable Class Libraries! This means these libraries can be used in Xamarin.Android and Xamarin.iOS applications. You can read more in the official post from Microsoft.

In this post, we’ll build a Xamarin.Android app, which will connect to the Office 365 service. We’ll extend this app to show data from our Office 365 subscription. The app will talk to our Office 365 Exchange Inbox and fetch mails from there. The overall app will look similar to the screenshots shown below:

xamarin-o365-img1

Step 1: Get the Tooling

To build apps that can connect with Office 365, we need to install the necessary tooling support. For Visual Studio:

  • On the Visual Studio menu, click Tools->Extensions and Updates->Updates.
  • You should see the update available for Office 365 API Tools.
  • Click Update to update to the latest version.

–OR–

  • Download the extension and install it manually.

Step 2: Create Xamarin.Android Application

For this sample, we’ll choose the default Android app template and extend this app to use Office 365 libraries.

  • In Visual Studio, File > New > Project
  • Select C# > Android and Blank App (Android) project template
  • Give project a name (in my case O365Client) and click ‘OK’

xamarin-o365-img2

This will create a default “Hello World” app, which shows the incremental number of clicks of a button.

Step 3: Add Office 365 Connected Service

To use Office 365 Services from this app, we need to add libraries and reference the services. Simply right click the project in the Solution Explorer and add a connected service.

xamarin-o365-img3

On the next screen, sign in with your Office 365 Account:

xamarin-o365-img4

Now, select the service which you want to access and give it a permission and click “OK”:

xamarin-o365-img5

Step 4: Using the Services

In the Solution Explorer, you’ll find that the tooling has added the required assemblies as well as some C# files with sample code:

xamarin-o365-img6

[Application]
public class MyGlobalDeclaration : Android.App.Application
{
  public MyGlobalDeclaration (IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer)
  {
  }
  public static List Messages { get; set;}
  public override void OnCreate()
  {
    base.OnCreate();
    Messages = new List ();
  }
}

To show data in a specific format (Inbox layout) we need to add a custom adapter, which will populate this view. Add a new class to the project and modify it as displayed below:

public class HomeScreenAdapter : BaseAdapter
{
  List items; Activity context;
  public HomeScreenAdapter(Activity context, IEnumerable items) : base()
  {
     this.context = context;
     this.items = items.ToList();
  }
  public override long GetItemId(int position)
  {
    return position;
  }
  public override IMessage this[int position]
  {
    get { return items[position]; }
  }
  public override int Count
  {
    get { return items.Count; }
  }
  public override View GetView(int position, View convertView, ViewGroup parent)
  {
    View view = convertView; // re-use an existing view, if one is available
    if (view == null) // otherwise create a new one
    view = context.LayoutInflater.Inflate(Android.Resource.Layout.SimpleListItem2, null);
    view.FindViewById(Android.Resource.Id.Text1).Text = items[position].Subject;
    view.FindViewById(Android.Resource.Id.Text2).Text = items[position].From.Address;
    view.Tag = items [position].Id;
    return view;
   }
}

Now, let’s modify ‘MainActivity.CS’ to show our Inbox.First, the activity needs to inherit from ListActivity to display records in a list mode:

public class MainActivity : ListActivity

To authenticate against the Inbox in Office 365 i.e. Exchange, we’ll declare two endpoints:

const string ExchangeResourceId = "https://outlook.office365.com";
const string ExchangeServiceRoot = "https://outlook.office365.com/ews/odata";

This is the perfect time to authenticate, we’ll write the EnsureClientCreated method, which will create an Office365 client that we can use to call the services. To execute this method we’ll pass the current activity as the context.

private async Task EnsureClientCreated(Context context)
{
  Authenticator authenticator = new Authenticator(context);
  var authInfo = await authenticator.AuthenticateAsync(ExchangeResourceId);
  return new ExchangeClient(new Uri(ExchangeServiceRoot), authInfo.GetAccessToken);
}

Once the client is ready we can call GetMessages, which gets messages from our Office 365 Inbox.

public async Task GetMessages(Context context)
{
  var client = await EnsureClientCreated(context);
  var messageResults = await (from i in client.Me.Inbox.Messages
      orderby i.DateTimeSent descending
      select i).ExecuteAsync();
  MyGlobalDeclaration.Messages = messageResults.CurrentPage.ToList ();
  ListAdapter = new HomeScreenAdapter(this, MyGlobalDeclaration.Messages);
  return messageResults.CurrentPage;
}

However, we’re yet to call GetMessages method in our code. Modify the OnCreate method as shown below to call this method and fetch messages.

protected override void OnCreate(Bundle bundle)
{
  base.OnCreate(bundle);
  GetMessages (this);
}

When the user clicks on a particular email message, we want to show that message. First, add an OnListItemClick method, which, when clicked, will pass the Email’s ID to next activity, which we’ll add later.

protected override void OnListItemClick (ListView l, View v, int position, long id)
{
  var bodyActivity = new Intent (this, typeof(MessageBodyActivity));
  bodyActivity.PutExtra ("Id", v.Tag.ToString());
  StartActivity (bodyActivity);
}

Now, we’ll add a new layout and activity for the detailed message. To do this, go to Resources > Layouts and add a new Android Layout. I’ve given it a name “Message.axml”.
Modify this file as shown below to include our view.

<!--?xml version="1.0" encoding="utf-8"?-->

Here, add a new Android Activity to the project and modify it with following code to display the message and sender’s email ID.

[Activity (Label = "Email:")]
public class MessageBodyActivity : Activity
{
  protected override void OnCreate (Bundle bundle)
  {
    base.OnCreate (bundle);
    var id = Intent.GetStringExtra ("Id");
    if(string.IsNullOrWhiteSpace(id))
      return;
    var message = MyGlobalDeclaration.Messages.FirstOrDefault (m => m.Id == id);
    if(message == null)
      return;
    SetContentView (Resource.Layout.Message);
    var fromText = FindViewById (Resource.Id.fromText);
    var bodyText = FindViewById (Resource.Id.bodyText);
    fromText.Text = message.From.Address;
    bodyText.SetText(Html.FromHtml(message.Body.Content), TextView.BufferType.Spannable);
  }
}

This completes our amazing Office 365-enabled mobile app! Debug the application, and login with your Office 365 account. This should show all the mails in your inbox, and, if you click on any mail item, it should take you to its detailed view.

I want to reiterate here that you are not just limited to fetching mails from the inbox like we did in this example, but you can fetch calendar events, get files from OneDrive for Business, or even browse through sites available under SharePoint Online.

I hope that this was a great introduction on how you can use the brand new Office365 API in your Xamarin.iOS and Xamarin.Android applications. You can download the full source code for this sample on my GitHub.

Discuss this blog post in the Xamarin Forums

TwitterFacebookGoogle+LinkedInEmail
July 28, 2014

Image Detection in iOS 8

By

Prior to iOS 8, Core Image included facial recognition, allowing applications to easily detect facial features such as mouth and eye positions. This is covered in the Introduction to Core Image article in our Developer Center. In iOS 8, Apple has added additional image recognizers for detecting rectangles as well as QR codes.

CIDetectors

All of the image detectors from Core Image are available in the CIDetector class. This makes the API for doing image recognition the same regardless of which type of detector you are using. You can create an image detector via factory methods on CIDetector as listed below:

  • CIDetector.CreateRectangleDetector
  • CIDetector.CreateQRDetector
  • CIDetector.CreateFaceDetector

These methods take CIContext and CIDetectorOptions instances respectively. A CIContext orchestrates everything that happens when working with Core Image, such as applying filters and performing image detection.

CIDetectorOptions, as the name implies, allows various options to be set. For example you could set the accuracy the detector should use.

Rectangle Detector

With the CIContext and CIDetectorOptions, you can create a CIDetector, as the following code does to create a rectangle detector:

var detector = CIDetector.CreateRectangleDetector (context, options);

Any image features recognized by the detector are returned in an array of CIFeature objects when calling FeaturesInImage for a given CIImage:

var ciImage = CIImage.FromCGImage (imageIn.CGImage);
var features = detector.FeaturesInImage (ciImage);

Each feature has a Bounds property containing a rectangle that encloses the particular feature. This can be used to perform imaging operations on the detected feature. For example, say you want to highlight a feature on an image when it is recognized. You could use the Bounds to create an overlay over the original image:

var overlay = CIImage.ImageWithColor (CIColor.FromRgba (1.0f, 0.0f, 0.0f, 0.7f));
overlay = overlay.ImageByCroppingToRect (features [0].Bounds);
var ciImageWithOverlay = overlay.CreateByCompositingOverImage (ciImage);

This results in a semi-transparent overlay as shown below:

rectangle image detector

QR Code Detector

Core Image previously included the ability to generate QR codes. Now it allows QR code detection as well.

Using a QR code detector is similar to a rectangle detector. Simply create the detector, this time by calling CreateQRDetector, and proceed in a similar fashion to retrieve a CIFeature array.

var detector = CIDetector.CreateQRDetector (context, options);

The following screenshot shows a QR code being detected:

qr code detector

One thing to be aware of, as of iOS 8 beta 4, the QR code detector only works on a device. Calling CreateQRDetector in the simulator returns null.

The addition of new detectors in Core Image, with its high-performance, easy to use API, allows for new scenarios that previously required third party imaging libraries. Combined with the extensive filtering support of Core Image, it’s very easy to create imaging applications in iOS.

The code from this post is available here.

Discuss this blog post in the Xamarin Forums

TwitterFacebookGoogle+LinkedInEmail
July 25, 2014

Contest: Code Monkeys in the Wild

By

We’ve shipped Xamarin Monkeys to every corner of the world, and it’s time for them to check in.  

For this contest, all you need to do is take a picture of your plush Xamarin monkey doing something awesome! Whether it be your favorite part of your town, on a trip to an exotic paradise, or simply hanging with your dog in your backyard, help show the world how far the Xamarin community reaches.

Looking for some inspiration? Check out our well-traveled friends on @ConceptMonkeys and @MotzMonkeys.

Monkeys in Seattle

How to Enter

  1. Take a picture of your monkey doing something amazing.
  2. Tweet your picture with the hashtag #xamarin #codemonkey

Don’t have a monkey yet? No problem.  Step into our Virtual Monkey Photo Booth by running our excellent “Working with Images” Xamarin.Forms tutorial on your phone for a stand-in monkey.

Local-sml

Prizes

  • Best Monkey: Exclusive Xamarin Swag Bag
  • Best Virtual Monkey: Exclusive Xamarin Swag Bag + plush Xamarin monkey

All submissions must be made by August 4th at 8am EDT. A valid entry consists of a tweet with monkey(s). We will evaluate each photo and choose a winner based on novelty, photo quality, and reliability. Winners will be announced on Twitter. Contestants should follow @XamarinHQ to enable us to DM you for private follow-up. There is no purchase necessary to enter the Code Monkeys in the Wild contest.

TwitterFacebookGoogle+LinkedInEmail

Build Your First F# Mobile App Contest Winners

By

The launch of Xamarin 3 at the end of May brought Xamarin developers access to first-class support for F#, enabling succinct, expressive and functional mobile apps for iOS and Android. We received many great entries, making it difficult to select just two winners.

First place goes to Bernard Hsu for his app Evolution! Evolution is, “a mobile app (iOS written in Xamarin) that demos Evolutionary situations in-silico.” Bernard ported the C# version of Evolution to utilize all of the functional power of F# and will be rewarded with a new Apple Mac Mini for the valiant effort. Congratulations!

Evolution App by Bernard Shoe

Second place goes to Peter Klima’s TripDiary app. TripDiary allows you to track your, “trips to nature, for culture or wherever you want, to go take pictures and make notes during your journey.” TripDiary shows off how to interact with a SQLite database in F#, as well as how to build up a complete user interface with maps, photos, and more. Congratulations, Peter, you’ll soon be sporting a new Samsung Gear Live Watch!

tripdiary

Thank you to everyone who participated in the F# contest! Once again, we are amazed to have such a strong and inspiring community following Xamarin. To show our thanks, everyone who submitted a valid entry to the contest will be receiving a plush Xamarin monkey. If you didn’t manage to get an entry submitted this time, no worries; keep an eye on the Xamarin Blog for future contest announcements!

TwitterFacebookGoogle+LinkedInEmail
July 23, 2014

New Sprite Kit Physics Features in iOS 8

By

Sprite Kit, the 2D game framework from Apple, has some interesting new features in iOS 8 and OS X Yosemite. These include integration with Scene Kit, shader support, lighting, shadows, constraints, normal map generation and physics enhancements. Previously, I went through an introduction to Sprite Kit. This post will take a look at some of the new physics features, particularly improvements to physics bodies and physics fields.

bananas

Creating a Physics Body from a Texture

Sprite Kit now supports deriving the physics body of a sprite from its texture. This makes it easy to implement collisions that look more natural.

For example, notice in the following collision how the banana and monkey collide nearly at the surface of each image:

physics collision

Sprite Kit makes creating such a physics body possible with a single line of code. Simply call SKPhysicsBody.Create with the texture and size:

sprite.PhysicsBody = SKPhysicsBody.Create (sprite.Texture, sprite.Size);

Additionally, you can tune how the physics body is derived by passing in an alpha threshold, which defines the minimum alpha value a pixel must have to be included in the resulting physics body.

sprite.PhysicsBody = SKPhysicsBody.Create (sprite.Texture, 0.7f, sprite.Size);

Tweaking the alpha threshold like this fine-tunes the previous collision, such that the monkey falls over when colliding with the banana:

physic collision alpha threshold

Physics Fields

Another great addition to Sprite Kit is the new physics field support. These allow you to add things such as vortex fields, radial gravity fields and spring fields to name just a few.

Physics fields are created using the SKFieldNode class, which is added to a scene just like any other SKNode. There are a variety of factory methods on SKFieldNode to create different physics fields. You can create a spring field by calling SKFieldNode.CreateSpringField(), a radial gravity field by calling SKFieldNode.CreateRadialGravityField(), etc.

SKFieldNode also has properties to control field attributes such as the field strength, the field region, the noise used to generate forces, and the amount of attenuation of field forces as you move away from the field.

For example, the following code creates a spring field and adds it to the scene:

SKFieldNode fieldNode = SKFieldNode.CreateSpringField ();
fieldNode.Enabled = true;
fieldNode.Position = new PointF (Size.Width / 2, Size.Height / 2);
fieldNode.Strength = 0.5f;
fieldNode.Region = new SKRegion(Frame.Size);
AddChild (fieldNode);

You can then add sprites and set their PhysicsBody properties so that the sprites will be affected by the physics field, as the following code does when the user touches the screen:

public override void TouchesBegan (NSSet touches, UIEvent evt)
{
    var touch = touches.AnyObject as UITouch;
    var pt = touch.LocationInNode (this);
    var node = SKSpriteNode.FromImageNamed ("TinyBanana");
    node.PhysicsBody = SKPhysicsBody.Create (node.Texture, node.Size);
    node.PhysicsBody.AffectedByGravity = false;
    node.PhysicsBody.AllowsRotation = true;
    node.PhysicsBody.Mass = 0.03f;
    node.Position = pt;
    AddChild (node);
}

This causes the bananas to oscillate like a spring around the field node:

spring force field

Adding a different field is similar. For instance, the following code creates a radial gravity field:

SKFieldNode fieldNode = SKFieldNode.CreateRadialGravityField ();
fieldNode.Enabled = true;
fieldNode.Position = new PointF (Size.Width / 2, Size.Height / 2);
fieldNode.Strength = 10.0f;
fieldNode.Falloff = 1.0f;

As you can see, this results in a different force field, where the bananas are pulled radially about the field:

radial gravity field

With the new features added to Sprite Kit in iOS 8, it’s now very easy to create interesting effects in 2D iOS and OS X games. Have fun!

The code from this post is available in my GitHub repo.

Discuss this blog post in the Xamarin Forums

TwitterFacebookGoogle+LinkedInEmail
July 22, 2014

Announcing the Xammy Awards

By

Xammy BadgesWe are excited to announce the Xammy Awards, which will be awarded this year at Xamarin Evolve 2014. Xamarin developers represent the world’s top mobile developers and this is your chance to be recognized on our global stage.

Apps can be submitted in the following 4 categories:

  • Consumer: Tell us how your app changes the way we interact with the world and each other.
  • Gaming: Show us how you’ve created a breakthrough new game concept, or otherwise advanced the craft of game development.
  • Enterprise: Highlight how your app is transforming business processes and making BYOD work for employees and businesses.
  • Emerging Devices: Showcase how you’re taking C# to new form factors, and pioneering the next generation of mobile experiences.

There will be winners in each category, a Grand Prize winner, and a Developers’ Choice winner. Submissions are open from now until August 11th, and winners in the 4 categories will be announced at Xamarin Evolve 2014.

There is only one chance to claim a category for this inaugural year of the Xammy Awards — submit your app today!

TwitterFacebookGoogle+LinkedInEmail

Xamarin Evolve 2014: Announcing Training Classes & 39 Conference Sessions

By

Xamarin Evolve 2014 in Atlanta, GA, October 6-10We are very excited to announce the first major wave of amazing, expert-led sessions for Xamarin Evolve 2014, our annual developer conference, happening from October 6-10 in Atlanta, Georgia.

In-Depth Training Sessions Announced

Attend two days of training from Xamarin University spanning all topics from mobile development fundamentals to advanced areas such as enterprise security and data integration, getting the most from Xamarin.Forms, advanced iOS and Android topics such as graphics and animation, and tackling mobile quality with Xamarin Test Cloud.

Ten Tracks to Meet All of Your Mobile Development Needs

During three conference days, you will have the chance to attend over 50 live sessions, in 10 tracks, led by industry leaders and experts from Microsoft, GitHub, Facebook and more, covering all areas of mobile development:

  • Xamarin Platform: deep dive into C#, F#, Async, and getting the most from Xamarin Studio and Visual Studio.
  • iOS: learn about what’s new in Xamarin.iOS and iOS 8, binding Objective-C libraries, and memory management tips and tricks.
  • Android: get the scoop on Material design in Android L, the latest in Xamarin.Android, and effective navigation.
  • Cross-Platform: gain new skills in hybrid app development, Xamarin.Forms, iBeacons, augmented reality, and code-sharing architectures.
  • Mobile Best Practices: see how experts are achieving great mobile UI and UX, using functional reactive programming, and navigating the tricky world of app stores.
  • Enterprise Mobility: hear from a panel of experts on mobile security, building a modern DevOps solution, and learn from real world case studies from top companies.
  • Emerging Devices: mobile is rapidly moving beyond phones and tablets, so this is your chance to learn how Xamarin helps you get C# to all of these new form factors.
  • Gaming: From building games in iOS 8 to some secret announcements, you’ll be well equipped to build the next with Xamarin.
  • Testing: crashes and regressions are the top reasons for poor app adoption. Learn how to incorporate automated UI testing into your development workflow. Your users with thank you.
  • Mobile Ecosystem: add more awesome to your apps by leveraging the rich ecosystem of cloud services, libraries and controls that integrate with the Xamarin platform.

Register now to get your ticket to mobile expertise!

Register Now

Team Xamarin

TwitterFacebookGoogle+LinkedInEmail
July 21, 2014

Live Webinar: Test Apps on Hundreds of Devices with Xamarin Test Cloud

By

Xamarin Test Cloud

There are hundreds of mobile devices, OS versions, form factors and screen resolutions in use today, and your app needs to run on all of them. Xamarin Test Cloud makes it fast and easy to test your mobile apps on hundreds of real iOS and Android devices in the cloud, automatically.

Join Chris King, Xamarin’s Sr. Customer Success Engineer, for a live webinar this Thursday, July 24th at 8am PDT/ 11am EDT to find out why Xamarin Test Cloud is the easiest and fastest way to automate UI testing to ensure that you find bugs before your users do.

All registrants will receive a copy of the webinar, so please feel free to register even if you can’t attend.

Register Here

Want to get a head-start for the webinar? Take a few minutes to learn more about Xamarin Test Cloud.

TwitterFacebookGoogle+LinkedInEmail
July 17, 2014

Using Custom Controls in Xamarin.Forms on Windows Phone

By

Xamarin.Forms lets developers create native user interfaces on iOS, Android and Windows Phone from a single, shared C# codebase. Since the UI is rendered using the native controls of the target platform, it gives you great flexibility in customizing the controls separately on each platform. Each control is rendered differently on each platform using a Renderer class, which in turn creates a native control, arranges it on the screen and adds the behavior specified in the shared code.

Previously, we showed you how to build custom renderers in Xamarin.Forms on iOS and Android platforms to extend custom built controls. In case you missed it, its all here:

In practice,  you will use the same techniques to create custom renderers on Windows Phone as well.

WP-CustomControls-Xamarin.Forms

Windows Phone Custom Controls

.NET third party vendors provide you with wide range of top quality reusable UI controls on the Windows Phone platform. Sometimes it is easier to buy and use them than to build something on your own. Especially, the data visualization controls such as charts that transform your tabular data into something beautiful on the Windows Phone screen.

In this blog post, I will take you through steps involved in integrating a Infragistics XamDataChart control for Windows Phone in Xamarin.Forms. Xamarin.Forms-CustomControl-Charts

There are two main parts to implementing a custom control with a renderer -

  1. Create your own custom Xamarin.Forms control with bindable properties in Shared Project so that Xamarin.Forms API can refer them.
  2. Create a renderer in Windows Phone platform that will be used to display the Infragistics XamDataChart control and subscribe to property changed notifications

CustomChartView Control

In my shared project, I’m going to create a new control called CustomChartView that will be used in my Xamarin.Forms page. CustomChartView must inherit from Xamarin.Forms.View.

public class CustomChartView : View
{
  public static readonly BindableProperty ItemSourceProperty =
    BindableProperty.Create<CustomChartView, StockMarketDataSample>(p =>
    p.ItemSource, new StockMarketDataSample());
  public StockMarketDataSample ItemSource
  {
    get { return (StockMarketDataSample)GetValue(ItemSourceProperty); }
    set { SetValue(ItemSourceProperty, value); }
  }
  // Additional bindable properties
}

Notice the BindableProperty called ItemSourceProperty - this property is my DataModel which is of type StockMarketDataSample that has some necessary logic to simulate live data. In a real scenario, this will be replaced with the data that comes from a web service or something similar. In the code, you will see two more properties PriceDisplayType and ShowSpline. These are the properties that will help us interact with the chart for e.g. for changing the Price Type (CandleStick or OHLC) or Show/Hide a SplineAreaSeries from Xamarin.Forms controls.

CustomChartView Renderer

Now, with my Xamarin.Forms control in place I can write some Windows Phone platform specific code. I will implement a CustomChartViewRenderer class that inherits from a ViewRenderer and layout the XamDataChart on it.

public class CustomChartViewRenderer : ViewRenderer<CustomChartView, XamDataChart>
{
  XamDataChart DataChart;
  public CustomChartViewRenderer()
  {
    DataChart = new XamDataChart();
    //..code
  }
  //.. code
}

Since this renderer on Windows Phone inherits from View, which means Xamarin.Forms will handle all of the size calculations and will have the normal properties of a standard Windows Phone View. Add the XamDataChart to the project and update the references accordingly. Additionally, you will need to add more code to set your XAxis, YAxis and the FinancialPriceSeries to the XamDataChart. That code has been omitted from this post for brevity.

Now, I will set my renderer to display the XamDataChart control when the CustomChartView is added to the page layout. This is done by overriding the OnElmentChanged method and calling the SetNativeControl method in it.

protected override void OnElementChanged(ElementChangedEventArgs<CustomChartView> e)
{
  base.OnElementChanged(e);
  if (e.OldElement != null || this.Element == null)
    return;
  UpdateChart();
  SetNativeControl(DataChart);
}

UpdateChart() method is a private method that sets the DataContext of the XamDataChart control to the Xamarin.Forms CustomChart control’s ItemSource property.

private void UpdateChart()
{
  DataChart.DataContext = this.Element.ItemSource;
  DateXAxis.ItemsSource = this.Element.ItemSource;
  series.ItemsSource = this.Element.ItemSource;
  //.. code
}

Export Renderer Attribute

[assembly: ExportRenderer((typeof(CustomChartView)), typeof(CustomChart.WinPhone.ViewRenderers.CustomChartViewRenderer))]
namespace CustomChart.WinPhone.ViewRenderers
{
  public class CustomChartViewRenderer : ViewRenderer<CustomChartView, XamDataChart>
  {
  }
}

To get the control to show up in the actual view, I need to set an attribute ExportRenderer to the CustomChartViewRenderer class.

Wiring up the UI in XAML

Finally, I will add our custom control to the Page.  There are two approaches to create user interfaces in Xamarin.Forms. The first one is to create UI views entirely with source code using the Xamarin.Forms API. The other option available is to use Extensible Application Markup Language (XAML) which is the approach I’ve taken to build this demo.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
			 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
		     x:Class="CustomChart.HomePage"
             xmlns:custom="clr-namespace:CustomChart.CustomControls;assembly=CustomChart.WinPhone">
    <Grid HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" >
        <Grid.RowDefinitions>
            <RowDefinition Height="80"/>
            <RowDefinition Height="80"/>
            <RowDefinition Height="*" />
            <RowDefinition Height="1" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="1"/>
        </Grid.ColumnDefinitions>
        <Grid.Padding>20</Grid.Padding>
        <StackLayout Orientation="Horizontal" Grid.Row="0" Grid.Column="0" HorizontalOptions="Center">
            <Button Text="Start" x:Name="StartButton" />
            <Button Text="Stop"  x:Name="StopButton"  />
            <Label Text="Spline:" VerticalOptions="Center"/>
            <Switch x:Name="ShowSplineSwitch"/>
        </StackLayout>
        <Picker x:Name="chartPicker" Title="Chart Type" HorizontalOptions="FillAndExpand" VerticalOptions="Center" Grid.Row="1"/>
        <custom:CustomChartView x:Name="chart" Grid.Row="2" />
    </Grid>
</ContentPage>

This page contains a Start Button – that starts a live feed, a Stop Button – thats stops the live feed, a Switch – that lets you show/hide a SplineAreaSeries in the Chart, and a Picker – that let’s you choose the Price Display Type (CandleStick or OHLC).

Xamarin.Forms-CustomControl-Charts-Spline

Handling Property Changes 

In the CustomChartControl of the shared project, along with the ItemSourceProperty, I have exposed the PriceDisplayTypeProperty and ShowSplineProperty as well. We can now easily set these property to interact with the XamDataChart. To make this work, we need to listen to the property changed event and set appropriate property of the XamDataChart. We will override the OnElementPropertyChanged method in the CustomChartViewRenderer class to do so.

protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
  base.OnElementPropertyChanged(sender, e);
  if (Control == null || Element == null)
    return;
  if (e.PropertyName == CustomChart.CustomControls.CustomChartView.PriceDisplayTypeProperty.PropertyName)
    series.DisplayType = Element.PriceDisplayType.ToIGPriceType();
  if (e.PropertyName == CustomChart.CustomControls.CustomChartView.ShowSplineProperty.PropertyName)
    ShowHideSpline();
}
private void ShowHideSpline()
{
  if (this.Element.ShowSpline)
    DataChart.Series.Add(splineSeries);
  else if (DataChart.Series.Contains(splineSeries))
    DataChart.Series.Remove(splineSeries);
}

Bringing it all together

That’s it! Now we can set these properties in the appropriate event handlers of the controls. Also, setting the ItemSource property to a StockMarketDataSample will populate the chart with the values.

public HomePage ()
{
  InitializeComponent ();
  chart.ItemSource = _data = new StockMarketDataSample();
}
void ShowSplineSwitch_Toggled(object sender, Xamarin.Forms.ToggledEventArgs e)
{
  chart.ShowSpline = e.Value;
}
void chartPicker_SelectedIndexChanged(object sender, EventArgs e)
{
  PriceDisplayType priceDisplayType;
  if (Enum.TryParse<PriceDisplayType>(chartPicker.Items[chartPicker.SelectedIndex], out priceDisplayType))
    chart.PriceDisplayType = priceDisplayType;
}

To simulate a Live Data, StockMarketServiceClient is used which has a timer that ticks every few milliseconds and raises an event with new value. Subscribing to that event and updating the ItemSource will change the visualization in the chart.

Xamarin.Forms-CustomControl-WPTo learn more about customizing your Xamarin.Forms controls and applications be sure to read our documentation.

Infragistics controls were used as an example in this post to show you how well Xamarin.Forms can integrate with third party controls. You can use any third party controls or custom controls that you have built with Xamarin.Forms and the procedure to get that working remains the same. 

Source Code

You can download the full source code for this project from my GitHub. Make sure you download and install Infragistics libraries before compiling.

Discuss this blog post in the Xamarin Forums

TwitterFacebookGoogle+LinkedInEmail