Disclaimer: this is an automatic aggregator which pulls feeds and comments from many blogs of contributors that have contributed to the Mono project. The contents of these blog entries do not necessarily reflect Xamarin's position.

July 30

Put Some Office 365 in Your Apps

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

July 29

Frame Debugger in Unity 5.0

Have you ever looked at some graphics issue in Unity, and thought “if only I could see how the final frame is rendered, step-by-step?”. I know I do want that, all the time.

You can achieve that with some external tools, especially if you’re on Windows. Build a standalone player, run it through Visual Studio graphics debugger, Intel GPA, RenderDoc, NVIDIA NSight or AMD GPU PerfStudio, then capture a frame of rendering, and step through the draw calls and other rendering events to see what’s going on.

The above is a very powerful approach, since these tools can provide you with a lot of information to really drill down. It’s also very involved; you need to build a player and launch external tool.

During one hack week we thought: “hey, can we build something really simple, but really quick to use in Unity?”… So we did.

Enter Frame Debugger

You select Frame Debugger from the Window menu and you see a list of draw calls made during that frame. Step through them and see what was rendered up to that point. Inspect shadow maps, temporary render textures, deferred g-buffer and whatnot.

Looking into deferred shading g-buffer here, as it is being rendered

 

The UI for the frame debugger is pretty simple. There’s a tree of draw calls and other interesting events on the right and details about selected event on the left. Most draw calls display a mesh preview and highlight object being drawn in the hierarchy.

Here we are stepping through the draw calls of depth texture creation, in glorious animated GIF form:

FrameDebugAnimDepth

And later on in the frame, a light is rendering it’s shadow map:

FrameDebugAnimShadow

Even later on, image post-processing effects start. You can see the bloom & flares effect downscaling the image, blurring it and adding it back, followed by a brief flash of a tonemapper:

FrameDebugAnimFx

Render target display options

For some effects, it is convenient to see individual channels of a render target. Here’s a screenspace buffer produced by Unity’s directional light shadows:

FrameDebugShadowAll

And here’s only the red channel displayed:

FrameDebugShadowR

The range of colors displayed can be tweaked via a Levels slider in the toolbar. This is particularly useful for HDR rendering:

FrameDebugLevels1

FrameDebugLevels2

When rendering into multiple render targets at once you can select which one to display in the game view. Shown here are the diffuse, specular, normals and emission/lighting buffers in 5.0 deferred shading mode, respectively:

FrameDebugMRTDiffuse FrameDebugMRTSpec Looking into deferred shading g-buffer here, as it is being rendered FrameDebugMRTLight

Implementation notes

The current implementation of the Frame Debugger could be seen as a cute hack (we weren’t quite sure ourselves whether it would work at all). There’s no actual “frame capture” going on; pretty much all we do is stop rendering after some number of draw calls. So if you’re looking at a frame that would have 100 objects rendered and you’re looking at object #10 right now, then we just skip rendering the remaining 90. If at that point in time we happen to be rendering into a render texture, then we display it on the screen.

This means the implementation is simple; getting functionality working was only a few days of work (and then a few weeks iterating on the UI). The downsides of this approach is that it only works in the Editor. If actual rendering changes while you’re debugging the frame (e.g. you disable some objects, or resize game view), then you’ll suddenly start looking at a different list of draw calls. However, even with these limitations we think it can be a very useful tool for tracking down graphics issues in your games.

Happy frame debugging!

FrameDebugCat

July 28

Image Detection in iOS 8

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

Unit testing at the speed of light with Unity Test Tools

It’s time to tell a little bit more about NSubstitute library that ships with our Unity Test Tools and patterns of it’s effective usage.

Each software system consists of units of functionality. In object oriented languages, the minimal unit of functionality is a method. These methods usually depend on other methods and classes. If you have to test a method, some challenges will arise.

  • First challenge is that external dependencies are not easy to set up, e.g. some objects with complex initialization might be required.
  • Second challenge is that the test verifies specific execution path that requires certain behavior from other classes that are used.
  • Finally, calling methods of external classes might lead to some changes in an environment that could not be rolled back, e.g. deleting a real record from a database.

Unit test is about testing unit of functionality in an isolated environment. Isolated means with all dependencies mocked up. Which means that test works in a test specific environment where only one execution path is possible.

Test doubles substitute real dependencies of unit under test, forming test specific environment and making unit tests fast and robust.

There are five test double patterns: Dummy object, Test stub, Test spy, Mock and Fake.

Dummy object

This article uses a simple Space Trader game clone to demonstrate the usage of test doubles and the NSubstitute library. This game is centred around the spaceship controlled by the player.

The player can equip weapons to fight pirates. The spaceship has weapon slots and a weapon can be equipped if an empty weapon slot is available.

Test scenario: make sure that weapon slot is occupied when weapon is equipped.

  • Take a spaceship with one free weapon slot
  • Take any weapon
  • Equip the weapon
  • Check that no weapon slots are available

unit-testing-at-the-speed-of-light-with-unity-test-tools-image15

Test with dummy object created manually Test with dummy object created manually.

Test with NSubstitute based dummy object Test with NSubstitute based dummy object

Weapon object is nominal in this scenario which means that its methods and properties are not intended to be used in this execution path. It is just a required parameter and anything that implements IWeapon interface can be used, including null when method has no null parameter check. This object usage is called dummy object pattern.

There are two approaches to create dummy objects.

The first approach is to create dummy object manually. It makes sense to have only one dummy object per real object/interface and IDE functions will help you to generate classes that implement interface. Creating dummy objects this way and storing them with your tests is not a big deal.

unit-testing-at-the-speed-of-light-with-unity-test-tools-image10

The second approach is to use NSubstitute that is shipped with Unity Test Tools:
unit-testing-at-the-speed-of-light-with-unity-test-tools-image07

Remember that passing null as a parameter when method has no null parameter check is also considered to be dummy object pattern. Null is not descriptive though.

All described methods are valid and very easy to use.

Test Stub

But what if spaceship’s method should return some value and this value is taken from weapon object? In this case, weapon is not a Dummy object anymore. It’s time for a test stub.

Test stub returns values for testing one specific execution path. E.g. BrokenWeaponStub, IncompatibleWeaponStub and others that let you test specific scenarios.

Test scenario: make sure that ship shoots at least one shot if functional weapon is equipped

  • Take a spaceship with a single weapon slot;
  • Equip weapon;
  • Shoot;
  • Check that spaceship’s round contains at least one shot;

unit-testing-at-the-speed-of-light-with-unity-test-tools-image12Test with test stub created manually.

FunctionalWeaponStub implements IWeapon interface but return hardcoded value.

unit-testing-at-the-speed-of-light-with-unity-test-tools-image01

Unlike Dummy object that does nothing, Stub contains hardcoded values and is intended to return them as this values result in specific execution path.

It is possible to create the same stub using NSubstitute:
unit-testing-at-the-speed-of-light-with-unity-test-tools-image02

The object created by Substitute.For implements IWeapon interface and is returned as IWeapon type. But it is actually a proxy object whose behaviour could be changed. Returns is an extension method of NSubstitute library that changes the behavior of this proxy. When Shoot method is called, the value specified in Returns() method is returned. It is also possible to provide a sequence of values or a delegate.

A sequence of values would be returned In the example below.
unit-testing-at-the-speed-of-light-with-unity-test-tools-image08

First call to randomNumberService.Range() with any parameters will result in 0. Next call will return 2 and so on.

Other useful function of NSubstitute is the ability to match arguments by template.

In the example below the default behavior would be overridden making any call to Range(10,100) return 80. For more details read the NSubstitute manual.

The approach with random number generator stub is highly effective in testing random events, because it is possible to emulate required sequence of random numbers.

Making stubs manually is easy and naming them correctly leads to creation of clean and readable tests. NSubstitute can decrease the amount of code and provide additional flexibility.

Test Spy

But what if it is needed to log the behavior of an object? How many hits has an opponent received? If the test double has logging functionality, then it is called a Test Spy.

Encounter means meeting someone in space en route to a star system. The player can choose an action to take in an encounter. For example, the police could be ignored and a pirate attacked.
Test scenario: make sure that opponent gets hit in an encounter

  • Take an opponent;
  • Take a spaceship with two weapons slots;
  • Equip two weapons;
  • Create an encounter;
  • Choose attack action in the encounter;
  • Check that opponent got hits;

unit-testing-at-the-speed-of-light-with-unity-test-tools-image05

Encounter requires two spaceships and a random number generator to calculate probable outcomes. AlwaysMaxRandomNumber is passed which will always return maximum number and this will leave no chances for the opponent to evade the hit. The test is following a very specific execution path.

The player spaceship is real in this encounter, but the opponent is a spy. The spy combines stub and logging functionality. It logs the hits that would be checked later in the test.

unit-testing-at-the-speed-of-light-with-unity-test-tools-image14

It is possible to assemble a test spy using NSubstitute’s Arg.Do<> and When… Do… constructs.

unit-testing-at-the-speed-of-light-with-unity-test-tools-image04

NSubstitute uses special argument matcher Arg.Do to execute a delegate when argument to it passes to the substitute. Which means that hitCount+=x.Count() would be executed on each method call.

Mock Object

The spy only logs the data, leaving verification to the programmer. What will happen if a spy is given the right to verify the data?

Test Spy with verification capability is called Mock object. (Note: This article shows non strict mocks.)

Test scenario: make sure that each weapon shoots when spaceship shoot method is called

  • Take a spaceship with two weapon slots;
  • Equip two weapons;
  • Shoot;
  • Check that each weapon got call to Shoot method.

unit-testing-at-the-speed-of-light-with-unity-test-tools-image11

This test case is special, not just because it uses Mock object pattern, but because it verifies the behaviour of the spaceship instead of the state. (Learn more about London and Chicago schools of TDD)

The test does not care about returning values of test doubles, it makes sure that certain methods with certain parameters were called. We use an assumption that if a spaceship has called correct methods with correct parameters on external systems, then it works correctly.

Making mocks manually might be rather time consuming. Using NSubstitute framework to get mock objects for cheap is a good choice.

NSubstitute can also verify if methods were called in a specific sequence.

unit-testing-at-the-speed-of-light-with-unity-test-tools-image03

A mock object not only logs the calls but also verifies them. It is a test spy with built-in assertions.

Fake object

But what if a test double needs some logic?

A test double that contains logic is called a Fake object and it is a dangerous beast. It is the only test double that contains logic and emulates a real system component. As the Fake itself is complex, it is used to substitute real system components which could not be substituted by stubs. The most common example is the substitution of a real database with an in-memory database or using fake web service instead of a real one.

The best solution is to avoid fake objects when possible, as they know too much about the behaviour of the component they substitute and contain logic that should be tested and is a subject to change as well.

Summary

As a brief conclusion:

  • Making stubs, dummies and spies manually is not complex and giving them proper names will make code readable and clean.
  • NSubstitutes is designed for mocking and using it is preferable to designing mock objects by hand.
  • Checking the behaviour and state based testing are both powerful. Use the one that makes the test simpler.
  • Avoid fakes (logic) in test doubles when possible.

Happy unit testing !

Examples are on the GitHub.

P.S.:

Different books use different terminology see terminology in books
NSubstitute is very powerful and taking a look at the documentation is a good idea.
Good principles to follow.
If you still don’t feel the difference between mocks and stubs read “Mocks aren’t Stubs”.
Arrange Act Assert (AAA) pattern was used to structure unit tests in the article.
There is an open source implementation of a Space Trader game worth playing with.

July 25

Contest: Code Monkeys in the Wild

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.

Build Your First F# Mobile App Contest Winners

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!

July 24

Mixing Sweet Beats in Unity 5.0

One of the big areas of focus for Unity 5.0 has definitely been in audio. After a quiet period of feature development in this area, we have been working hard at taking audio to a first class feature within Unity.

To make this work we first had to take a step back and re-work a lot of the underlying asset pipeline and resource management of audio within Unity. We had to make our codec choices solid and ensure we had a framework that allowed you guys to have a lot of good quality sounds in your game. I’ll try and cover this in detail in a later post, but right now I want to talk about our first big audio feature offering in Unity 5.0, the AudioMixer.

Our First Move

Besides creating a solid foundation for future audio development in Unity, we wanted to give you guys a shiny new feature as our first big ‘we want you to make awesome audio’ offering. Something to show we mean business and want to empower you as best we can on the audio front.

There are a number of areas within the audio system we will be improving over the coming release cycles. Some of them are small and address the little issues that have been outstanding in Unity thus far, things you could consider as fixing the existing feature set. Some of them will be larger, like the ability for users to make amazing interactive sounds, immersive music systems and control to a high detail the mix of the audio soundscape.

Why the AudioMixer?

The question of why we chose the AudioMixer as the first big feature to push in Audio 5.0 can be answered pretty simply. Previously there was no way in which true sub mixing of audio was possible within Unity. Sounds could be played on an AudioSource where effects could be added as Components, from there all the sounds within the game were mixed together at the AudioListener where effects could be added to the entire soundscape.

We decided to address this with the AudioMixer, and while we were there we thought we would take it to the next level, incorporating many features you would find in established Digital Audio Workstation applications.

Sound Categories

CategoryExamples_edited

As many sound engineers know, it is super useful to be able to combine collections of sounds into categories and apply volume control and effects over the entire category in one place. Hooking up those volumes and effect parameters to game logic is effectively having a master control over an entire area of the game’s soundscape.

This control over the mix of the entire soundscape is super important! Its a fantastic way of controlling the mood and immersion of the audio mix. A good mix and music track can take players through the full range of emotions during gameplay, and create atmospheres that are not possible with graphic flair alone.

Mixing In Unity

This is the purpose of the AudioMixer. Its an asset that users can incorporate into their scenes that control the overall mix of all the sounds in the game. All the sounds playing in a scene can be routed into one or more AudioMixer which will categorise them and apply all sorts of modifications and effects to the mix of those sounds.

MixerWindow_edited

Each AudioMixer can have a hierarchy of categories defined, which in the case of the AudioMixer are called AudioGroups. You also view a lineup of these AudioGroups with a traditional mixing desk layout which many from the music and film industry with be used to.

DSP

SingleStripThe AudioMixer is, of course, more than just setting up mixing hierarchies. As one would expect, each AudioGroup can contain a bunch of different DSP audio effects that are applied sequentially as the signal passes through the AudioGroup.

Now we are getting somewhere!  Not only can you now create custom routing schemes and mixing hierarchies, but you can put all sorts of DSP goodies anywhere in the signal chain, allowing all sorts of effect options over your soundscapes. You can even add a dry path around effects to allow only a portion of the signal to be processed by it.

But what if you want more DSP control that just the inbuilt effects of Unity? Previously this was handled exclusively with the OnAudioFilterRead script callback, which allowed you to process audio samples directly in your scripts.

This is great for lightweight effects or prototyping your fancy filter ideas. Sometimes though, you want the ability to write native compiled effects for the best performance. Allowing you to write more heavy weight ideas, perhaps like your custom convolution reverb or multi band EQ.

ConvolutionReverb

Unity now also supports custom DSP plugin effects, with users having the ability to write their own native DSP for their game, or perhaps distributing their amazing effect ideas on the Asset Store for others to use. This opens up a whole world of possibilities, from writing your own synth engine to interfacing other audio applications like Pure Data. These custom DSP plugins can also request sidechain support and will be supplied sidechain data from anywhere else in the mix! Hawtness!

One of the cool things possible with the effect stack in an AudioGroup is that you can apply the groups attenuation anywhere in the stack. You can even boost the signal now as we allow volume levels up to +20dB. The inspector even has a integrated VU meter to show you exactly what is happening with the signal at the point of attenuation.

AtenuationMetering

When combined with non-linear DSP, Sends / Receives and our new Ducking insert (which will be explained later in this post), it becomes a super powerful way of controlling the flow of audio signal through a mix.

Mood Transitions

I talked earlier about controlling the mood of the game with the mix of the soundscape. This can be achieved with bringing in and out new stems of music or ambient sounds. Another common way to achieve this is to transition the state of the mix itself. Changing the volume of sections of the mix and transitioning to different parameter states of effects is an effective way of taking the mood of a player where you want them to go.

Inside all AudioMixers is the ability to define snapshots. Snapshots capture the state of all of the parameters in the AudioMixer. Everything from effect wet levels to AudioGroup pitch levels can be captured and transitioned between.

Snapshots

You can even create complex blend states between a whole bunch of Snapshots within your game, creating all sorts of possibilities and uses.

Imagine walking from an open field section of your map into a sinister cave and have the mix transition to highlight more subtle ambiences, bring in different instruments of your music ensemble and change reverb characteristics of the foley. Imagine setting this up without having to write a line of script code..

Divergent Signal

But the power of Snapshots becomes especially augmented when combined with Sends, Receives and Ducking.

Sends

SendDialog

Aside from traditional insert DSP effects available in Unity, you can also insert a “Send” anywhere into the mix. A Send effectively branches the audio signal wherever the Send is inserted, and within Sends you can choose how much of the signal you wish to branch off.

Things are now becoming even more interesting! Given that the level of signal you branch is part of the snapshot systems, you can start to see how you can incorporate signal flow changes with snapshot transitions. From here the potential setup possibilities start snowballing.

But where does this branched signal go? Currently there two options in Unity for a Send to target, Receives and Volume Ducking.

Receives

Receives are fairly straight forward processing units. They are inserts just like any other effect and they simply take all the branched audio from all the Sends that target them and mix it together, passing it off to the next effect in the AudioGroup.

Receives can of course be placed anywhere in a group of effects and the attenuation point of an AudioGroup, which gives huge flexibility on when the branched signal should be introduced to the mix.

Volume Ducking

Sends can also target Volume Ducking insert units. Much like Receives, these units can be placed anywhere in the mix alongside your other DSP effects.

DuckVolumeEffect

When a Send is targeting a Volume Ducking insert, it acts much like a side chain compressor setup, meaning you can side chain from anywhere in the mix and apply volume ducking anywhere else from it!

What does this mean for the layman? Imagine you and mixing your FPS game and you want to avalanche the player with the sound of gunfire and explosions. Fair enough, but what about when you walk up to an NPC in the field of battle and you need to hear the sagely words they utter? Volume Ducking allows you to dynamically lower the volume of entire sections of the mix (in this case, all the ordnance sounds) off other sections of the mix (the NPC talking). You simply have to Send from the AudioGroup containing all the NPC dialog to a Volume Ducking unit on the Ordnance AudioGroup.

You could even apply side chain compression to your musical setup dynamically, having the rest of your instruments compressed off the bass track.

The best thing is you can set this all up in the editor without a line of code!

Parting Words

Even though I have really only scratched the surface of possibilities the AudioMixer provides in this post, I hope its enough to sparks peoples interest in the possibilities of audio in Unity 5.0.

Unity 5.0 and beyond we really want to push the future of audio in games, giving you the suite of tools you need to make awesome sounding stuff!

Let us know your thoughts!

The Audio Team

PS: Wayne will talk about  New Audio Radness in Unity 5.0 at Unite 2014, August 22, 13:30-14:30. See you there!

Bonus Video: Beat mixing in Unity!

July 23

Using Twilio with Xamarin

Twilio recently published a great component to enable iOS and Android apps developed with Xamarin to easily add VoIP capabilities.

twilio component

This post walks through making a simple app to call a phone number.

Setting up the Twilio Server

The first thing you need to do is sign up for a Twilio account. They have a free trail version, which you can sig nup for at https://www.twilio.com/try-twilio, that will work fine for our purposes.

Before getting started there is a bit of setup you’ll need to perform in the Twilio portal.

When you set up a Twilio account, you’ll be given a Twilio phone number. You can view your phone number at any time by selecting the “Numbers” section in the Twilio user account page:

twilio_numbers

You’ll also need your account SID and auth token, which you can get under the “dashboard” section of the account page.

dashboard

The last thing you’ll need to create is a TwiML app, which you can do under “Dev Tools” > “TwiML Apps”. Set the app url to http://YourDomain/InitiateCall as shown below:

twiml_apps

Note the SID here is the application SID,as opposed to the account SID shown earlier.

We these things in place, you’re ready to get started coding. Twilio requires a server to handle token generation and in this case, the TwiML app to initiate the call.

A free ASP.NET MVC website in Azure works fine. Here’s the full code for the ASP.NET MVC controller for this example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Twilio;
using Twilio.TwiML;
using Twilio.TwiML.Mvc;

namespace TokenGenerator.Controllers
{
    public class ClientController : Controller
    {
        public ActionResult Token(string clientName = "default")
        {
            string accountSid = "Your account SID";
            string authToken = "Your auth token";
            string appSid = "Your app SID";
                
            var capability = new TwilioCapability(accountSid, authToken);
            capability.AllowClientIncoming(clientName);
            capability.AllowClientOutgoing(appSid);

            return Content(capability.GenerateToken());
        }

        public ActionResult InitiateCall(string source, string target)
        {
            var response = new TwilioResponse();
            response.Dial(target, new { callerId = source });

            return new TwiMLResult(response);
        }
    }
}

For the above code, you’ll also need to add a couple NuGet packages:

  • Twilio.Mvc
  • Twilio.Client

Then, simply replace the accountSid, authToken and appSid with the values obtained above and publish the site to Azure.

Using the Xamarin Twilio Component

For this example I’m just going to create a simple iOS client to make an outgoing call. However, Android is supported as well.

In a new iOS project create 3 buttons named callButton, hangUpButton and sendKeyButton (I used a storyboard to create the UI) and add the following code to the view controller.

using System;
using System.Net.Http;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using TwilioClient.iOS;

namespace HelloTwilio
{
    public partial class HelloTwilioViewController : UIViewController
    {
        TCDevice device;
        TCConnection connection;

        public HelloTwilioViewController (IntPtr handle) : base (handle)
        {
        }

        public async override void ViewDidLoad ()
        {
            base.ViewDidLoad ();

            var client = new HttpClient ();
            var token = await client.GetStringAsync ("http://YourSite/Client/Token");

            device = new TCDevice (token, null);
			
            callButton.TouchUpInside += (object sender, EventArgs e) => {

                string twilioNumber = "Your twilio number";
                string numberToCall= "Some number to call";

                var parameters = NSDictionary.FromObjectsAndKeys (
                    new object[] { twilioNumber, numberToCall }, 
                    new object[] { "Source", "Target" }
                );
        
                connection = device.Connect (parameters, null);
            };

            sendKeyButton.TouchUpInside += (object sender, EventArgs e) => {
                if (connection != null) {
                    connection.SendDigits ("1");
                }
            };

            hangUpButton.TouchUpInside += (object sender, EventArgs e) => {
                if (connection != null) {
                    connection.Disconnect ();
                }
            };
        }
    }
}

In the code, set the domain name you published to earlier where it says “YourSite” and add your Twilio number and a phone number to call respectively.

Adding the Twilio component is easy. Just right-click on “Components” in the Solution Explorer, select “Get More Components”, and pick the Twilio component.

Once the component is added, run the application and click “Call”. After hearing the trial account message, press the “Send Key 1″ button and the phone call will be initiated.

phone app

There you have it, VoIP added to an iOS app. Pretty cool :)


Mono Performance Team

For many years a major focus of Mono has been to be compatible-enough with .NET and to support the popular features that developers use.

We have always believed that it is better to be slow and correct than to be fast and wrong.

That said, over the years we have embarked on some multi-year projects to address some of the major performance bottlenecks: from implementing a precise GC and fine tuning it for a number of different workloads to having implemented now four versions of the code generator as well as the LLVM backend for additional speed and things like Mono.SIMD.

But these optimizations have been mostly reactive: we wait for someone to identify or spot a problem, and then we start working on a solution.

We are now taking a proactive approach.

A few months ago, Mark Probst started the new Mono performance team. The goal of the team is to improve the performance of the Mono runtime and treat performance improvements as a feature that is continously being developed, fine-tuned and monitored.

The team is working both on ways to track performance of Mono over time, implemented support for getting better insights into what happens inside the runtime and has implemented several optimizations that have been landing into Mono for the last few months.

We are actively hiring for developers to join the Mono performance team (ideally in San Francisco, where Mark is based).

Most recently, the team added a new and sophisticated new stack for performance counters which allows us to monitor what is happening on the runtime, and we are now able to export to our profiler (a joint effort between our performance team and our feature team and implemented by Ludovic). We also unified both the runtime and user-defined performance counters and will soon be sharing a new profiler UI.

New Sprite Kit Physics Features in iOS 8

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

July 22

Plastic SCM server address changed, what now?

Sometimes you just need to change the server IP or port because of security reasons; sometimes the server is moved somewhere else and then the address changes. Ideally the IT team will notify you about the change and you’ll have time to prepare it.

Now we’ll review the steps you will need to follow to achieve a smooth transition.

Notify the developers about the change

It’s important to share the information with the developers using Plastic about the server address change since they’ll need to carry out some actions, don’t worry everything is pretty easy. The only action they need to accomplish prior to the address change is the following one:
  • Checkin all the pending changed files/directories inside the workspaces before the server address changes. Basically, leave the “Pending changes view” clean.

Why? The Plastic SCM changes metadata info is internally stored inside a binary file called “plastic. changes”; you’ll find it at the hidden “.plastic” directory at your root workspace path. This is the key reason finding checkouts in a huge workspace (>300K files) is so fast. The pending changes are stored along with the Plastic SCM repository and the server they belong to. Keeping this file during the address change will lead into future issues while committing the changes since the old server stored will not be valid.

Reconfigure the client connection info

When the server address changes the Plastic SCM client will not detect the new address, the client will keep trying to connect with the old configuration over and over again and you will much likely see something like the image below.


Don’t worry; it’s just the Plastic SCM client complaining about the server not answering the start-up queries. That’s why we need to run the Plastic SCM client configurator, to tell the client the new server address to work with.
Remember that you’ll find the client configurator at the Windows start button programs or simply running “plastic --configure"


Once the client is configured to use the new server address and port the Plastic SCM Client will start.
We didn’t finish but we are almost there.

Metadata references matters

The Plastic SCM client is still having a file storing references to the old server address; the name of the file is “plastic.wktree”. The workspace tree file, unlike the “plastic.changes” file, can be easily updated to fetch the new server address so it’s safe to preserve it during the transition.

The “plastic.wktree” file is a really important file for the Plastic SCM client, it stores the loaded changeset metadata info, that is the files name, size, hash, owner, repository and so on. It also stores the server address the workspace is working with, in order to update it you will need to open a command line window, change the directory to the Plastic SCM workspace path and run a “cm update .” operation.

That will update not only your workspace but also the metadata referencing the old server address, now the Plastic SCM client can continue working, perhaps you may see the following error message:

No channel found trying to connect to [colada:8091 (unreachable)]

That means your plastic SCM selector is hardcoded to work with a certain repository spec, “code@colada:8081” for example, if that’s the case please issue the “cm sts” command and choose one of the following two alternatives, you can remove the absolute server spec from the selector, preserving only the repository name or you can fix the old server address and set the new one.

Old selector:
repository "code@colada:8090"
path "/"
smartbranch "/main"

New selector (Option 1, relative repo spec):
repository "code"
path "/"
smartbranch "/main"

New selector (Option 2, full repo spec):
repository "code@tizona:9091"
path "/"
smartbranch "/main"

Alternatively to the “cm sts” command you can issue an absolute repspec switch operation providing the new server address, for example:

cm switch br:/main@code@tizona:9091

Assuming “colada:8090” is your old Plastic SCM address and “tizona:9091” is the new one.

Announcing the Xammy Awards

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!

Xamarin Evolve 2014: Announcing Training Classes & 39 Conference Sessions

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

July 21

Assets that rock

Sometimes, it’s hard to put a finger on what makes the Asset Store so special. Is it the relief that you feel when you find out that “there’s an asset for that? Or just the breathtaking diversity? For me, it’s that Asset Store is a real ecosystem, with assets battling for dominance in their respective niches. This constantly drives the quality upwards while keeping prices down.

Reading this thread about rock models on Polycount got me wondering: How many rock assets can we have on the Asset Store? I counted around 75, from hot lava to weathered pebble asphalt.

And that’s not counting assets like this one:

Hard Rock Title (Steve Vai style) by Alchemy Studio – Matteo Bosi

Here’s a little selection of a few assets that really, well, rock. They deliver rock solid quality for prices that range from zero to forty dollars. Check them out and start your own fascinating rock collection or, you know, use them in that awesome game you’re working on.

Better Rocks and Cliffs by Quantum Theory786639a8-7555-4219-9a6f-4e6a665fcdf1_scaled

With the tagline: “Tired of iced cream scoop rocks?”, Quantum Theory delivers a step up in quality with ridiculously realistic textures and pixel perfect shading. Each rock has a unique surface variance.

Rock and Boulders by Manufactura K4 (Michael O.)55f11288-734f-423b-a2a8-ef02752fb381_scaled

The demo included in this package is only missing dramatic music to be the perfect opening scene for an epic adventure. This detail oriented package has huge boulders, small pebbles, stones covered with snow, five skyboxes and even a few trees.

Rock Pack 01 by Alex S.

4b615747-e3f6-4a15-b4c0-7e89aec93be4_scaled

Working on a next gen Rock Simulator? Get your main heroes from this package! This affordable asset has seven rock models and three tileable textures. You can customize everything to your heart’s desire, since .ztl source files are also a part of the deal.

Cave Rocks Kit by Chad Travis

Mysterious cave? Check. Stone corridor leading into darkness? Double check. A strange device with a potentially deadly light beam? So much check! If you’re making a dark adventure game, don’t miss this highly original package. Warning – you might get inspired!

042b2d86-6f30-4f4f-b94e-be1f05632b85_scaled

Rock cliff or cave by Allegorithmic

7a8053eb-9894-45e6-b9e3-89d00333141e_scaled

Allegorithmic sells literally hundreds of different textures on the store for a few dollars. It’s really easy to just slap this on your models and tweak all those parameters until perfection. In the end, you’ll have your own unique pet rock.

Rock Pack – Freebies by Nobiax / Yughues

1d00b968-ae9c-4f7d-aec7-6f20d9966a3e_scaled

This is exactly what it says, seven free models of rock, with seven prefabs and their respective colliders. It can be a great placeholder art for prototyping or an alright final solution for any budget-conscious project.

 

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

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.

July 19

Transition tracker

Friday was my last day at Collabora, the awesome Open Source consultancy in Cambridge. I’d been there more than three years, and it was time for a change.

As luck would have it, that change came in the form of a job offer 3 months ago from my long-time friend in Open Source, Miguel de Icaza. Monday morning, I fly out to Xamarin’s main office in Boston, for just over a week of induction and face time with my new co workers, as I take on the title of Release Engineer.

My job is to make sure Mono on Linux is a first-class citizen, rather than the best-effort it’s been since Xamarin was formed from the ashes of the Attachmate/Novell deal. I’m thrilled to work full-time on what I do already as community work – including making Mono great on Debian/Ubuntu – and hope to form new links with the packer communities in other major distributions. And I’m delighted that Xamarin has chosen to put its money where its mouth is and fund continued Open Source development surrounding Mono.

If you’re in the Boston area next week or the week after, ping me via the usual methods!

IMG_20140719_203043

July 17

Using Custom Controls in Xamarin.Forms on Windows Phone

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

Mocast

image

For the past couple months, I have been working on a top secret project that aims to redefine the way work will get done, address key industry mobility challenges and spark true mobile-led business change. I’m just kidding, it’s a podcast player!

Why?

Mocast is not going to redefine how work gets done, but I am hoping it redefines how you listen to podcasts.

I wrote Mocast because I was unhappy with the iOS podcast app selection. While there are almost as many iPhone podcast players as there are weather apps, I find that they all have two fatal flaws.

First, they take downloads way too seriously. Most UIs differentiate downloaded vs. not downloaded episodes and bifurcate their interface along those lines. This is silly to us podcastistas who aren’t the greatest at planning ahead.

Second, they take new episodes too seriously. Whole apps seem built with only new episodes in mind as they hide away the back catalog. I don’t know why this is. My favorite podcast, The Incomparable has an amazingly rich back catalog of episodes that I love to listen to. It’s nice when a new episode arrives but there’s no need over-emphasize them at the cost of the full catalog.

How?

First, and most importantly, downloads are completely optional when using Mocast. You can always play an episode immediately, whether you have downloaded it or not thanks to streaming.

Next, it’s a single-screen thumb-based UI. You see, I walk a lot in parks and can’t stand apps that have a complex navigation history with back buttons with crazy nesting - I need to be able to do everything with my thumb and I need the screen to be predictable. Mocast makes that possible. You will only ever see a list of episodes, a search box, and play controls. There is no Now Playing screen, no episode screens, just episodes and a big play button. I even tried to limit the number of buttons all together. This is a slide-happy, thumb loving app.

Mocast puts you in control with queues. Mocast presents four different lists of episodes: Per-podcast, New, Queued, and History. While Mocast manages most of those lists, The Queue is fully under your control. You can add episodes to listen to later or setup a nice set of old favorites to listen to when nothing new is coming in.

Mocast acknowledges and embraces our busy lives that prevent us from completing episodes. It keeps a running History of past played episodes (and of course where you left off) so that you can jump around between episodes without ever worrying about forgetting to finish one.

Lastly, and this is one of my favorite features, Mocast lets you perform offline full-text searches of all episodes’ show notes. Do you want to see all podcasts that mentioned WWDC 2014? Easy. How about all Star Wars episodes? Done. Every list Mocast shows is searchable and the search box is always ready for you at the top of the app.

A bit of fun

While I truly believe Mocast has a lot to offer in terms of usability, I think it’s a fun app too. Here are a few of my favorite features.

Siri is used to announce episodes. Yes, that Siri. It took some string pulling and I have to deal with a 150 page rider, but she’s there to let you know what you’re listening to.

The time scrubber is thumb friendly, velocity controlled, big and bold. I can’t stand apps with tiny scrubbers so I hope you will enjoy this one.

Dark disco theme that adapts to your episodes. Mocast is just a sad dark gray app until you start adding podcasts. But once they’re in, it lights up with their colors and keeps those colors moving around. It’s hard to describe in words, so I hope you’ll risk the $3 to see for yourself.

There are more features than this tucked away! I hope you’ll check them out!

Colophon

As with all my apps, I wrote Mocast in C# using Xamarin.iOS. She came out to be about 8,000 loc with about 60% of that code lying in the UI layer.

Monologue

Monologue is a window into the world, work, and lives of the community members and developers that make up the Mono Project, which is a free cross-platform development environment used primarily on Linux.

If you would rather follow Monologue using a newsreader, we provide the following feed:

RSS 2.0 Feed

Monologue is powered by Mono and the Monologue software.

Bloggers