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 28

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 weapon 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.

July 16

New Collection View Features in iOS 8

Collection Views are a powerful user interface technology for laying out collections of data. With fantastic support for high performance grid layouts, flexible line based layouts, and fully custom layouts, along with integrated animation capabilities, they make creating beautiful data-driven UIs a wonderful experience both for the developer and the end user.

collection views

iOS 8 adds some nice enhancements to Collection Views, including the ability to self-size cells without the need for using a delegate. Likewise, the layout attributes of individual cells can now be adjusted directly from within the cell class without having to use a delegate. This makes it easier to make small layout changes that are related to a particular cell.

Self-sizing Cells

First, let’s look at how to self-size cells. Before iOS 8, creating cells that sized to their content required working within a layout class directly or via a layout’s delegate, such as the UICollectionViewDelegateFlowLayout.

For example, the following code adjusts the cell size to fit cells comprised of simple UILabels, presented using a UICollectionViewFlowLayout:

class FlowLayoutDelegate : UICollectionViewDelegateFlowLayout
{
  string[] items;
  UIStringAttributes attr;
  public FlowLayoutDelegate (string[] items)
  {
    this.items = items;
    attr = new UIStringAttributes {
      Font = new UILabel ().Font
    };
  }
  public override SizeF GetSizeForItem (UICollectionView collectionView, UICollectionViewLayout layout, NSIndexPath indexPath)
  {
    string text = items [indexPath.Row];
    return new NSString (text).GetSizeUsingAttributes (attr);
  }
}

This code results in a Collection View where each cell fits the text it contains:

self sizing cells

Creating cells that are self-sized is much easier in iOS 8. Simply set the EstimatedItemSize on the UICollectionViewFlowLayout and implement SizeThatFits or use AutoLayout in the cell class.

For example, to self-size the cells in the example above, set EstimatedItemSize as shown below:

flowLayout = new UICollectionViewFlowLayout (){
  EstimatedItemSize = new SizeF (44, 144)
};

Then, simply adding the following implementation of SizeThatFits in the cell class produces the same result, without the need for the UICollectionViewDelegateFlowLayout implementation:

public override SizeF SizeThatFits (SizeF size)
{
  label.Frame = new RectangleF (new PointF (0, 0), label.AttributedText.Size);
  return label.AttributedText.Size;
}

Adjusting Layout Attributes in Cells

iOS 8 also makes it easier to manipulate the layout attributes returned from within the cell class without resorting to a UICollectionViewDelegateFlowLayout. Just override PreferredLayoutAttributesFittingAttributes in the cell class.

The following code changes the font of every other label and adjusts the layout for each cell appropriately:

public override UICollectionViewLayoutAttributes PreferredLayoutAttributesFittingAttributes (UICollectionViewLayoutAttributes layoutAttributes)
{
  var newLayoutAttributes = (UICollectionViewLayoutAttributes)layoutAttributes.Copy ();
  if (layoutAttributes.IndexPath.Row % 2 == 0) {
    //
    label.TextColor = UIColor.Red;
    ContentView.BackgroundColor = UIColor.LightGray;
    var attr = new NSAttributedString (Text, UIFont.SystemFontOfSize (28.0f));
    label.Font = UIFont.SystemFontOfSize (28.0f);
    //
    newLayoutAttributes.Frame = new RectangleF (new PointF (0, 0), attr.Size);
    label.Frame = new RectangleF (new PointF (0, 0), attr.Size);
  } else {
    //
    newLayoutAttributes.Frame = new RectangleF (new PointF (0, 0), label.AttributedText.Size);
    label.Frame = new RectangleF (new PointF (0, 0), label.AttributedText.Size);
  }
  return newLayoutAttributes;
}

This allows fine-grained control at the cell level, as shown below:

layout attributes

As you can see, iOS 8 adds flexibility to Collection Views, allowing granular control of cells directly from the cell class and making it easier to control cell layout and sizing when needed.

The code from this post is available here.

Discuss this blog post in the Xamarin Forums

Java Method Overriding Is FUBAR Part 10 of ∞

Yesterday's JDK 7u65 and 8u11 updates changed method overriding yet again and, of course, it is still broken.

Take this example:

package pkg1;

public class A {
  { foo(); }
  void foo() { System.out.println("A.foo"); }
}

package pkg2;

public class B extends pkg1.A {
  { foo(); }
  void foo() { System.out.println("B.foo"); }
}

package pkg1;

public class C extends pkg2.B {
  { foo(); }
  void foo() { System.out.println("C.foo"); }
}

package pkg2;

public class D extends pkg1.C {
  { foo(); }
  void foo() { System.out.println("D.foo"); }
}

public class test {
  public static void main(String[] args) {
    new pkg2.D();
  }
}

Running this with JDK 8u5 yields:

D.foo
D.foo
D.foo
D.foo

Which is, of course, wrong. In yesterday's updates they tried to fix this, but only partially succeeded:

D.foo
D.foo
C.foo
D.foo

The sensible output would be:

C.foo
D.foo
C.foo
D.foo

Java Security Fixes

In Februari I reported two Java vulnerabilities to Oracle. Yesterday they released the update that fixed them, so here are the descriptions of the two issues.

@java.lang.invoke.LambdaForm.Compiled

Internally, the JDK uses the LambdaForm.Compiled annotation to mark methods that should be skipped in a security stack walk. In JDK 7 it was possible to apply this annotation to untrusted code. Here's an example:

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@interface java_lang_invoke_LambdaForm$Compiled { }

class test {
  @java_lang_invoke_LambdaForm$Compiled
  public static void main(String[] args) throws Throwable {
    System.out.println(Class.forName("sun.misc.Unsafe"));
  }
}

If you compile and run this with JDK 1.7.0_60 with a security manager, you get the appropriate AccessControlException. However, if you edit test.class to replace java_lang_invoke_LambdaForm with java/lang/invoke/LambdaForm and run it again, you see that the main method is now skipped in the security check and hence is allowed to access a privileged class.

The fix can be seen here.

MaxArityBug

This example demonstrates that the JDK 1.7.0_60 LambdaForm method handle implementation has a type safety bug when dealing with method signatures with the maximum number of parameters.

July 15

Mobile .NET Meetups and Xamarin 3 Celebrations in July

We’ve had some amazing Xamarin 3 celebrations over the last few months, but we aren’t done just yet. This month, Mobile .NET developer groups around the world are joining in to celebrate the latest Xamarin release with pizza, cake, and in-depth sessions on all of the new features in Xamarin 3. We have also launched a brand new Twitter account, @XamarinEvents, which will regularly tweet about upcoming Xamarin and community events.

Xamarin Cake

Here are some upcoming Xamarin developer group meetups:

Nashville Xamarin User Group us

  • Nashville, TN: Tuesday, July 15th 6:30PM

  • Xamarin.Forms Demo & Lab

Austin Mobile .NET Developers Group us

  • Austin, TX: Wednesday, July 16th 6:30PM
  • Cross Platform Development with Portable Class Libraries

Portland Area .NET Users Group in

  • Portland, OR: Thursday, July 17th 6:00PM
  • Creating UIs for Cross-Platform Apps with Xamarin, with Xamarin’s James Montemagno

Los Angeles Mobile .NET Developers Group in

  • Los Angeles, CA: Monday, July 21st 7:00PM
  • Xamarin Basics

Israel .NET Developer Group il

  • Tel Aviv, Israel: Tuesday, July 22nd 5:30PM
  • Building Cross Platform Apps with Xamarin

Minnesota Enterprise Mobile in

  • Wayzata, MN: Tuesday, July 22nd 5:30PM
  • Building iOS User Interfaces with Xamarin

Northwest Valley .NET User Group in

  • Glendale, AZ: Wednesday, July 23rd 6:00PM
  • Building iOS, Android, and Windows Apps in C# with Xamarin, with Xamarin’s James Montemagno

Boston Mobile C# Developers Group us

  • Cambridge, MA: Thursday, July 24th 6:00PM
  • Introduction to Xamarin.Forms, with Xamarin’s Pierce Boggan

Arizona – Xamarin us

  • Scottsdale, AZ: Thursday, July 24th 6:00PM
  • Xamarin 3! iOS and Android Development in C# with Xamarin

Chicago .NET Mobile Developers us

  • Chicago, IL: Thursday, July 31st 5:45PM

  • Introduction to the MVVMCross Cross Platform Framework

Xamarin events are always happening around the world, so if you don’t see your city listed above, be sure to also check out the Xamarin Events forum where new meetups are being added all the time. Additionally, don’t forget to follow our brand new @XamarinEvents Twitter account to make sure you never miss an upcoming Xamarin event.

Don’t see a developer group in your area and want to get one started? We’re here to help! We have a tips and tricks guide on starting a developer group, our introduction to Xamarin slide deck, and of course our community sponsorship program to get you on your way. We also want to hear from you, so please feel free to send us an email or tweet @XamarinHQ so we can help spread the word and continue to grow the Xamarin community.

Securing a Plastic SCM system

Motivation:

The two main motivations behind the Plastic SCM security system are:

  • Provide a mechanism to control access to the repositories and restrict certain operations.
  • Define custom policies for both development and deployment. Even in widely open organizations, the access to certain parts of a repository can be restricted, not only for security related reasons but to prevent mistakes.
  • After installing Plastic SCM, you can check that any authenticated user of the system will have full access granted.

    The first step should be to assign a specific user (or group) as the repository server owner, and then, you can start defining your custom security restrictions. The repository server owner will be the “root” Plastic server user.

    After that, it doesn´t matter if you, for some reason, misconfigure any permission because this user will be able to restore them again.

    Whether they are to prevent unwanted access or enforce certain development policies, you should consider the following:

  • Define the different users and groups that will have access to the Plastic SCM system, and give them the right access on the repository server. Later on, you can customize specific privileges to repositories, branches and even items if required.
  • The next step should be to change the repository server permissions. Changing the permissions to the top level element in the security hierarchy will ensure that all the rest of the objects get secured.
  • ACL´s and Permission inheritance:

    Each user (SEcured IDentifier or SEID in Plastic terms) or group who has granted or denied permissions will have an entry in a given ACL. Each entry, will have allowed and denied permissions.

    Permissions in Plastic SCM are inherited from the top object in the hierarchy (the server) down to the lower ones.

    This way, it is very simple to set a group of permissions at the server level that will apply to all the inheriting objects: repositories, branches...

    Disable or deny permission ?

    This is a question that you will probably need to answer when defining your permission policies. You need to take in account that disabling a permission is not the same as denying a permission.

    Consider the following example; a certain user is a member of the “developers” group and at the same time of the “integrators” group. Developers are not allowed to commit at the “main” branch but integrator certainly are.

    If we actively deny the checkin permission to the “developers” group on the main branch, this specific user won´t be allowed to perform the operation. The permission is granted due to he is an integrator but it’s denied because he is also a developer, the denied permission prevails over the granted.

    On the contrary, if we disable the permission (but not deny it) to the “developers” group, he will be allowed to perform the checkin operation at the main branch because he also belongs to the “integrators” group, and combining a disabled permission with an allowed one results in an allowed permission.

    Case studies:

    After this brief introduction to the Plastic SCM permissions system, I would like to review some examples that may help you to implement different permission policies based on your organizational needs.

    Case 1: Restrict permissions for integration branches

    Imagine you are developing your project using a branch per task branching pattern. Developers create task branches to perform their work.

    There are two different groups of people involved in the development: integrators and developers (but certain developers can act as integrators too).

    The recommended workflow is the following: developers can’t "checkin","applylabel" or "rmchangeset" on the integration branches, and only integrators can perform these operations.

    To handle this scenario, the proposed permissions configuration is:

    Disable the "checkin", "applylabel" and "rmchangeset" permissions to developers (not deny but disable). Integrators will have these permissions allowed, but the developers won´t be able to execute the mentioned operations.

    Remember that a user belonging to both groups will have the operations allowed: combining a disabled permission with an allowed one result in an allowed permission, meanwhile the users belonging only to “developers” won’t be able to perform the operations.

    Case 2: Restrict access to branches:

    In this second scenario, we have a development team that has the following roles: a system administrator group, a development group and an integration group.

  • Developers can only work on development branches.
  • Integrators can only make changes on integration branches.
  • Administrators have full access.
  • If a user belongs to several groups, he will have all the combined benefits (if a user is both a developer and administrator, he should be given full access).

    Steps to set up the scenario:

  • The "mkbranch" permission will be disabled at the repository level for both integrators and developers.
  • Development branches: integrators will have the "checkin" and "applylabel" permissions disabled. Developers will have the permissions allowed.
  • Integration branches: developers will have the "checkin" and "applylabel" permissions disabled. Integrators will have all permissions allowed.
  • Case 3: Restrict access to directories:

    In this case study, we have two different user profiles working on a branch: developers and artists. And we want to restrict the access to specific directories per user profile.

    A possible solution for this scenario could be:

  • Developers have all the path permissions enabled.
  • Artists have all the path permissions enabled, but the "src" folder.
  • Note: If you need to completely hide the directory to a user, the best solution would be to create a new repository per user profile using Xlinks and then customize the "view" permissions per repository.

    Summary:

    We have reviewed the main Plastic SCM features to secure a server and also some classic scenarios where you can customize the rules depending on your requirements.

    What are the permission policies that you are using in your company? Could you share your configuration with us?

    Unity’s test automation team

    Hello everybody, my name is Elvis Alistar and I have been working with Unity for more than 2 years. I am responsible for leading the team of Software Development Engineers in Test (SDET), which is part of Unity’s QA department. As the job title implies, we are a team of software developers that absolutely love testing. In this post, I would like to let you know why it is so critical for Unity to have a team of expert developers focusing on test automation.

    The Challenge

    Unity is a rapidly growing company with more than 450 employees from 50 different nations, working in 27 locations. The wide-spread, distributed nature of our company means that we have to be able to work with developers on all the different time-zones, from different cultures and with different backgrounds. We also have more than 2.5 million registered developers and often we interact with them through our forums, feedback website, and alpha and beta groups and by handling some of the bug reports we receive from them. Close collaboration with our development teams means that good communication skills become key.

    Unity supports 12 major platforms and a few smaller ones. Users can also use three different scripting languages for writing their game code. Multiply these with the fact that we have runtime tests, graphics tests, integration tests, unit tests, UI tests, performance tests, etc. and the number of different combinations our test automation infrastructure has to support and cope with is phenomenal. Take our runtime tests for example. We now have more than 1.300 unique Runtime API test cases. More than 13.000 test cases are run in a single automated build verification suite. We work in more than 100 development branches at the same time, which means that there are around 500.000 test points executed on our build farm every day. SDETs have to write, maintain, optimize and improve these on a daily basis.

    Just two years ago, we only had a few test frameworks, which were not very well documented, we didn’t have too many tests and nobody owned, maintained or improved the frameworks or the test code. The SDET team was formed with the mission of taking ownership of these frameworks and drive the effort of cleaning up, documenting and optimizing all our tests. We also made sure that all developers know how to use these frameworks and that they can easily create new tests using them.

    Unity’s code base is growing very fast and we need to make sure the product performs rock solid with every new release we are shipping. That is why we place great emphasis on test automation here at Unity. Just to put things in perspective, we now have somewhere around 2.2 million lines of code, out of which about 400.000 are test code spread over more than 7.000 files. This ensures that we can keep the quality bar high, avoid introducing new regressions and make sure that known bugs that were resolved will never show up in our product again.

    Now that is what I call a challenge!

    Team organization

    We are a distributed team of 8 developers working on tools, frameworks and feature automation, with a big emphasis on the latter. Two of us are located in Copenhagen (Denmark), one in Silicon Valley (USA) and five in Odessa (Ukraine). Our job is to figure out ways to improve the overall workflow for everyone involved in the development of Unity, by improving the automation on the build farm, making regression suites to prevent bugs flowing in and also evangelizing the usage of the frameworks to both testers and developers.

    Unity is a very complex product and to help work more efficiently we have split it into different areas: Scripting, Lightmapping, 2D, Animation, etc. Every SDET is responsible for writing, maintaining and reviewing tests in one or more of these areas. New SDETs will usually start with one area and work on it until they become proficient with using our processes, frameworks and strategies. After they gain enough knowledge and build enough confidence they take on more areas. All SDETs eventually work on improving our existing frameworks or adding new ones. We have 7 different kinds of automation frameworks at Unity and SDETs have to be able to work with all of them and help anyone else that has to work with them.

    Our job requires a strong collaboration with the other teams inside QA and across teams in our R&D department. We have to communicate well with developers and Software Test Engineers (STE) to make sure we know who is working on any given feature, which parts of it have been developed and tested and what needs to be automated. We all participate in QA’s main test activities on any given release, even if they don’t involve test automation: Exploratory Testing, Full Test Pass and Release Acceptance Testing (see Manual Testing session on our Testing Unity 4.0 blog post).

    Our automation work is rarely tied to a specific Unity release and that gives us a lot of freedom and flexibility to focus on what we want to improve. This also allows us to travel to our different offices to assist developers or to work with other testers on location. We attend the bigger testing conferences and we speak at conferences whenever we have the chance. We participate in our now famous HackWeeks where we can experiment with whatever ideas and projects we want, no matter how outlandish they are.

    Skills and attitude

    As SDETs we are required to have extensive knowledge about programming, object oriented design and test automation (unit testing, TDD, high level tests, etc.). We have to be able to spread the word about testing frameworks and practices, offer great feedback in code reviews and be able to work well together with developers. We value clean code and development best practices.

    At Unity, we also need to be able to work efficiently with many tools we use internally like FogBugz, QMetry, TeamCity, RhodeCode, Sikuli, NUnit, Moq, Unittest++, Atomiq and others.

    We’re hiring…

    So, there you have it! Being an SDET at Unity is both awesome, very rewarding, and the diversity of tasks we take part in is simply mind-blowing. The challenge is on! Are you up for it?

    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