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.

January 23

Xamarin MVPs Expand with More Awesome!

Since the introductionXamarin MVP of the Xamarin MVP program in 2013, our MVPs have been busy sharing their love and understanding of mobile app development with a growing community of more than than 880,000 Xamarin developers worldwide. Supporting this growth are amazing community members who show their passion for all things C# and F# by sharing their experience and knowledge with the world.

Xamarin MVPs have earned recognition for significant contributions to the community, including:

  • Writing great articles, books, and blog posts
  • Speaking in public and online
  • Sharing and building amazing libraries
  • Helping developers online in our forums, on Twitter, Stack Overflow, and other communities
  • Shipping awesome apps

Today, we’re extremely excited to recognize and welcome our latest Xamarin MVPs, below, for their remarkable contributions to the community!

enrique Enrique Aguilar Laurent Bugnion laurent
cheesebaron Tomasz Cielecki Jesse Liberty liberty
lipsky Jon Lipsky Roger Peters roger
rachel Rachel Reese Brent Schooley brent
snider Ed Snider Michael Stonis stonis
alec Alec Tucker

If you know of an outstanding developer who would make a great Xamarin MVP, please nominate him or her here.

In Defense of the Selfie Stick

From the sophisticated opinion of the trendsetters to Forbes, the Selfie Stick is the recipient of scorn and ridicule.

One of the popular arguments against the Selfie Stick is that you should build the courage to ask a stranger to take a picture of you or your group.

This poses three problems.

First, the courage/imposition problem. Asking a stranger in the street assumes that you will find such a volunteer.

Further, it assumes that the volunteer will have the patience to wait for the perfect shot ("wait, I want the waves breaking" or "Try to get the sign, just on top of me"). And that the volunteer will have the patience to show you the result and take another picture.

Often, the selfista that has amassed the courage to approach a stranger on the street, out of politeness, will just accept the shot as taken. Good or bad.

Except for a few of you (I am looking at you Patrick), most people feel uncomfortable imposing something out of the blue on a stranger.

And out of shyness, will not ask a second stranger for a better shot as long as the first one is within earshot.

I know this.

Second, you might fear for the stranger to either take your precious iPhone 6+ and run, or even worse, that he might sweat all over your beautiful phone and you might need to disinfect it.

Do not pretend like you do not care about this, because I know you do.

Third, and most important, we have the legal aspect.

When you ask someone to take a picture of you, technically, they are the photographer, and they own the copyright of your picture.

This means that they own the rights to the picture and are entitled to copyright protection. The photographer, and, not you, gets to decide on the terms to distribute, redistribute, publish or share the picture with others. Including making copies of it, or most every other thing that you might want to do with those pictures.

You need to explicitly get a license from them, or purchase the rights. Otherwise, ten years from now, you may find yourself facing a copyright lawsuit.

All of a sudden, your backpacking adventure in Europe requires you to pack a stack of legal contracts.

Now your exchange goes from "Can you take a picture of us?" to "Can you take a picture of us, making sure that the church is on the top right corner, and also, I am going to need you to sign this paper".

Using a Selfie Stick may feel awkward, but just like a condom, when properly used, it is the best protection against unwanted surprises.

January 22

Infographic: Build Right, Shift Left

You’re at the end of your mobile development cycle and just need to test your app before submitting to the app store. After testing on a handful of devices, you find several showstopper bugs that push your ship date out to weeks past your deadline. Is there a better alternative to this “build then test” workflow that slows your time to market, forces rework, causes bugs, and costs you money?

Download this infographic to learn why shifting your testing processes “left” in the development cycle to the start of your mobile project makes it faster and easier to find bugs before your users do.

Build Right, Shift Left infographic

Plastic meets Docker

Docker seems to be the new trend in application virtualization, and it is growing so fast that even Microsoft is getting ready to run Docker containers on Azure. They are also getting Windows ready to be dockerized.

This blogpost explains how to run a pre-built Plastic server Docker image that we have published at https://hub.docker.com. It explains the container structure we’ve prepared and how to isolate the server container from the data container to ease upgrades.

Meeting Docker

I’ve been playing with Docker these days, studying the integration possibilities it offers and finding an initial approach to wrap our beloved Plastic SCM server in a Docker container. And after some hours toying with our own Docker containers, I must say that I’m very excited about its potential!

But first things first: what’s actually Docker?

Docker: Sharing standardized module containers

Docker, as they define themselves, is an open platform for developers and sysadmins to build, ship and run distributed applications. It allows developers to create their own isolated environments according to their needs, define communication points (disk volumes or TCP/UDP ports) and save these settings into a Docker image.

Once the image has been set up, any other developer or sysadmin can run a new instance of the image, instantiating it into a Docker container.

Each one of those containers is run and virtualized on top of the Docker server, ensuring there’s no interference between them or the host OS.

Also, any change made in a container is persistent: all containers have their own local filesystem, which is managed by Docker. It won’t be accessed by any other container unless explicitly told to do so.

Continue reading »

Staying ahead with DirectX 12

Last year at GDC Microsoft announced DirectX 12. During yesterday’s Windows 10 media briefing, Phil Spencer of Microsoft mentioned that Unity is going to add support for DirectX 12. Here are some more details we can share with you today!

Direct3D 12 is a new graphics API with the promise of reducing driver overhead and allowing better use of multi-core systems. In those aspects it is comparable to AMD’s Mantle and Apple’s Metal.

The architecture of Direct3D 12 differs greatly from that of Direct3D 11 both in the way memory is accessed and GPU commands are issued. Rather than having a single context on which to set states and issue draw calls, we can now build command lists on multiple threads and retain them over multiple frames if necessary, saving precious CPU cycles and eliminating the dreaded my-render-thread-does-most-of-the-work problem. This has the potential to both reduce total frame time and increase battery life.

3DMark have ported one of their benchmarks to DirectX 12 and reported a 50% improvement in CPU utilization. See this blog post for more details.

3DMark DirectX 12 gains

Tested on GIGABYTE BRIX Pro (Intel Core i7-4770R + Iris Pro Graphics 5200)

Intel have also demonstrated what can be done on a Surface Pro 3 with Intel HD4400 graphics. This blog post has all the details.

Intel DirectX 12 gains

Close up of another CPU/GPU power graph taken during a locked framerate Intel Asteroids demo showing over 50% CPU power usage reduction

Direct3D 12 is expected to run on all Microsoft devices: mobiles, laptops, desktops and Xbox One, all of which Unity already supports. It is only logical for us to adopt the new universal API. However a significant amount of work is required to reap all the benefits this architectural switch can provide and that is why we have started early. Over the past several months we have worked closely with Microsoft to bring Unity to DirectX 12 and our initial port is now passing over 95% of our graphics tests.

Passing all the tests is only the first step. Once we are happy with the implementation feature-wise we shall move on to the new features of Direct3D 12 and invest heavily in optimization. There is ongoing work to allow our renderer to better use multiple cores which will apply directly to Direct3D 12 and hopefully provide the promised performance improvement. Right now, it’s too early to discuss performance due to the alpha state of Windows 10 and DirectX 12 drivers, however we are happy with the numbers we’re seeing.

Both Nvidia and Intel have given us ample support, and we now have code running on both Nvidia and Intel hardware. All of our demos are behaving well on Direct3D 12. That makes us very confident that your games will too.

Currently our plan is to release DirectX 12 support early in the Unity 5 cycle (well in time for the release of Windows 10), and to target standalone builds and Windows Store Apps first. Then we’ll follow up with Windows Phone and Xbox One support, aligning with the plans Microsoft has for their platforms.

Keep checking our blog for more DirectX 12 news. We should have more announcements in the next few months. In the meantime you can find more general information on the subject on the Microsoft DirectX 12 blog.

January 21

Authenticate Xamarin Mobile Apps Using Azure Active Directory

When developing mobile apps, you often run into an instance where your app needs some kind of authentication mechanism to protect its contents. iPhone Active DirectorySome mobile app developers choose to create their own repository to create a username/password based solution. Others choose a social media authentication provider such as Facebook, Twitter, or LinkedIn. Using Xamarin.Auth makes authenticating to services such as these extremely simple to implement.

However, in the case of enterprise apps, people don’t want to remember ‘yet another’ username/password combo and social media authentication is the least expected solution. Users expect their organization account to allow them to use different resources and apps within their system. Welcome to the world of Azure Active Directory (or Azure AD for simplicity).

Azure AD allows developers to secure resources such as files, links, and Web APIs using the same organizational account that employees use to sign in to their systems or check their emails. This should sound a bit familiar, as it is the same authentication mechanism behind Office 365.

Let’s take a look at how to integrate Azure AD into your mobile app with two simple steps.

Step 1: Registering the application with Azure AD

  1. First navigate to https://manage.windowsazure.com and log in with your Microsoft Account or Organization Account in the Azure Portal. If you don’t have an Azure Subscription, you can get a trial from http://www.azure.com
  2. After signing in, go to your Active Directory (1) and select the Active Directory where you want to register the application (2)
    01. Active Directory in Azure Portal
  3. After selecting the desired Active Directory, ‘Add‘ a new application by either clicking the link at front or at the bottom. Then select ‘Add an application my organization is developing
    02. Add New Application
  4. On the next screen, give your app a name. In my case it is ‘XAM-DEMO‘. On this screen, make sure you select ‘Native Client Application‘ as the type of application.
    03. App Name
  5. On the final screen, provide a ‘Redirect URI‘, which is unique to your application as it will return to this URI when authentication is complete.
    04. App Redirect URI
  6. Once the app is created, navigate to the ‘Configure‘ tab. Write down the ‘Client ID’, which we’ll use in our application later. Also, on this screen you can give your mobile application access to Active Directory or add another application like Web API, which can be used by mobile application once authentication is complete.
    05. Configure Application

Step 2: Authenticating the application with Azure AD

In your application, add a reference to Azure Active Directory Authentication Library (Azure ADAL) using the NuGet Package Manager in Visual Studio or Xamarin Studio. Make sure you select ‘Show pre-release packages’ to include this package, as it is still in preview.

Note: Azure ADAL 3.0 is currently a preview and there may be breaking changes before the final version is released. I have included references at the end of this post where you can find more information on Azure ADAL.

06. ADAL NuGet Package

In your application, you will now need to add the following class level variables that are required for the authentication flow.

//Client ID from from step 1. point 6
public static string clientId = "25927d3c-.....-63f2304b90de";
public static string commonAuthority = "https://login.windows.net/common"
//Redirect URI from step 1. point 5<br />
public static Uri returnUri = new Uri("http://xam-demo-redirect");
//Graph URI if you've given permission to Azure Active Directory in step 1. point 6
const string graphResourceUri = "https://graph.windows.net";
public static string graphApiVersion = "2013-11-08";
//AuthenticationResult will hold the result after authentication completes
AuthenticationResult authResult = null;

One thing to note here is commonAuthority. When the authentication endpoint is ‘common’, your app becomes ‘multi-tenant’, which means any user can use login with his Active Directory credentials. After authentication, that user will work on the context of his own Active Directory – i.e. he will see details related to his Active Directory.

At this time, you can modify the default button.Click event from the default Android application (or create your own flow to start the authentication). This will start the authentication and upon completion assign the result in authResult

button.Click += async (sender, args) => {
  var authContext = new AuthenticationContext(commonAuthority);
  if (authContext.TokenCache.ReadItems().Count() == 0)
    authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);
  authResult = await authContext.AcquireTokenAsync(graphResourceUri, clientId, returnUri, new AuthorizationParameters(this));
}

In the above code, the AuthenticationContext is responsible for the authentication with commonAuthority. It has an AcquireTokenAsync method, which take parameters as a resource which needs to be accessed, in this case graphResourceUri, client ID, return URI. The app will return to the returnUri when authentication completes. This code will remain the same for all platforms, however, the last parameter, AuthorizationParameters, will be different on different platforms and is responsible for governing the authentication flow.

In the case of Android or iOS, we pass ‘this’ parameter to AuthorizationParameters(this) to share the context, whereas in the case of Windows, it is passed without any parameter as new AuthorizationParameters().

Along with it, we also need to override the OnActivityResult method in Android to resume the application.

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
  base.OnActivityResult(requestCode, resultCode, data);<br />
  AuthenticationAgentContinuationHelper.SetAuthenticationAgentContinuationEventArgs(requestCode, resultCode, data);<br />
}

For Windows Phone, modify the OnActivated method in the app.xaml.cs file with the below code:

protected override void OnActivated(IActivatedEventArgs args)
{
#if WINDOWS_PHONE_APP
  if (args is IWebAuthenticationBrokerContinuationEventArgs)
  {
     WebAuthenticationBrokerContinuationHelper.SetWebAuthenticationBrokerContinuationEventArgs(args as IWebAuthenticationBrokerContinuationEventArgs);
  }
#endif
  base.OnActivated(args);
}

Now if you run the application, you should see an authentication dialog. Upon successful authentication, it will ask your permissions to access the resources (in our case Graph API).
08. Authentication-Flow
If authentication is successful and you’ve authorized the app to access the resources, you should get an AccessToken and RefreshToken combo in authResult. These tokens are required for further API calls and for authorization with Azure AD behind the scenes.
07. Access_Token For Authentication

For example, the code below allows you to get a user list from Active Directory. You can replace the Web API URL with your Web API which is protected by Azure AD.

var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, "https://graph.windows.net/tendulkar.onmicrosoft.com/users?api-version=2013-04-05");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
var response = await client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();

This way you can authenticate your mobile apps against Microsoft Azure Active Directory. ADAL makes it much easier with fewer lines of code, while keeping most of the code the same and thus making it shareable across platforms.

Learn More:

  • Azure ADAL is in preview. So, there can and most likely will be changes before the final release. Follow Vittorio Bertocci’s blog for more details and changes to the library.
  • The Azure Team has shared a complete example with Azure ADAL for each platform. Download it from here.

AddComponent(string): API Removal in Unity 5.0

GameObject::AddComponent(string) has been removed in Unity 5.0.  The alternatives are two overloads of this API, one taking the component type as a generic type argument and another one taking a reference to the component type. Automatic API updating has been configured but not all cases can be handled automatically.

In our quest to improve Unity we realized that we should let GameObject::AddComponent(string) go; in our first attempt we were too “aggressive” and removed GetComponent(string) as well. However, after receiving some great feedback, we reevaluated this decision and reintroduced it.

Unfortunately we could not do the same with AddComponent(string) (it would reintroduce the very same dependencies we are aiming to break, i.e, from core to subsystems). If your project uses this method you have two possible alternatives (depending on the accessibility of the type as explained in the rules related to compilation order and how the type name is specified). We’ll further describe these options in the following paragraphs (examples are written in C# but the same concepts applies to UnityScript (js) / Boo).

Scenario 1: Name of the type being added is passed as a constant / string literal and the type is known at build time

This scenario is straightforward and easily identifiable: AddComponent() is called with a constant string and you are able to declare local variables (or parameters, or fields) of the type being added. In this case you can simply use the generic version of AddComponent(), as shown in the following example:

// each class declared in its own file
namespace N1
{
      class C1 : MonoBehaviour { }
}

class C2 : MonoBehaviour { }

class MyObj : MonoBehaviour
{
      public void Start()
      {
          AddComponent(“C1”); // only the class name, no namespace information....
          AddComponent(“C2”);
      }
}

should be changed to:

// C1 / C2 declared as before.

class MyObj : MonoBehaviour
{
      public void Start()
      {
          AddComponent< N1.C1>();
          AddComponent< C2>();
      }
}

when porting the project to Unity 5.0.

Note that classes declared inside namespaces (C1) will require the namespace to be specified (line 8). This is unlike the version of this API that used to take a string, it only expects the class name).

Scenario 2: Parameter  / field / local variables are passed as the argument to AddComponent.

This scenario is also easily identifiable by simply checking the call to AddComponent() (it will use a field / local variable / parameter as the argument). Unfortunately, in this case the alternative is to rely on Type.GetType(string) to retrieve a reference to the type at runtime and call AddComponent(type) – which comes with some drawbacks:

  1. Scenarios involving  AOT / stripping
    The same constraints that apply to platforms apply here. For instance, the AOT compiler may not include a type in the final binary if no reference to that type exists in the code (i.e, only the type name, as a string, is used). Also, keep in mind that on IL2CPP backend, stripping is always enabled.

  2. Requires the type’s assembly fully qualified name
    This is more an annoyance than an issue, nevertheless, assembly qualified names can be pretty big, intimidating and prone to syntax errors.

  3. Requires an actual .Net type to exist
    Some Unity components only existed in native code (i.e, no .Net counterpart) (for instance, EllipsoidParticleEmitter). We added .Net representation for such components (from UnityEngine) but we may always have overlooked one or more types ;)

  4. Performance overhead involved in type lookup and / or other tasks.
    Usually this should not be an issue unless Type.GetType(string) gets called in a tight loop, nevertheless, you should keep it in mind.

Automatic API Updating

Since we want to make project updates as easy as possible, we configured our API Updater to take this change into account. When calls to AddComponent(string) are found, the updater analyzes the value used as the argument and, if it succeeds in resolving the type (which excludes the cases described by scenario 2 as the type name is only known at runtime) it simply applies the mechanics described in scenario 1 replacing the call to AddComponent(string) with a call to:

AddComponent< T>() // for C#

 

AddComponent.< T>() // for UnityScript (js) 

and AddComponent[of T]() for boo.

(“T” being the type of the component being added)

While planning how to handle the scenario in which the updater is unable to resolve the type being passed as the argument (scenario 2 and also some sub cases of scenario 1 – classes declared in namespaces for instance), we’ve tried to achieve a balance between usefulness, reliability and ease of use. After our first evaluation we came up with the following options:

  1.  Do not touch the script at all (not good);
  2. Simply replace all invocations to AddComponent(string) with its generic version (or the one taking System.Type as its parameter) and assume / hope it works;

  3. Replace such invocations with more elaborate, possibly slow, code that tries to resolve the type at runtime looking in multiple assemblies.

Option 1 got discarded really quick and option 2 did not look very user friendly / reliable or professional to us, so we’re left with option 3 which, to be fair, didn’t sound like a great solution either. In the end we settled on what we consider to be a good compromise:  calls to AddComponent(string) that fall into this category (type cannot be resolved at compile time because it is passed through non constants / non literals) are replaced by a call to APIUpdaterRuntimeServices::AddComponent(…) which, in the editor, is implemented as described in option 3 with extra logging to provide developers hints on how to replace the call with something that is production quality. Below you can see a screenshot of such a log:

Log when game enter in play mode

Log when game enter in play mode

(note that the line / column displayed in the log may be slightly off due to other updates being applied; also it is worth mentioning that the explanation uses C# generic method syntax – so if your scripts are written in UnityScript/Boo make the appropriate changes).

In the above example, even though the updater was unable to resolve the type, when in play mode, i.e, when using the editor version of UnityEngine assembly, APIUpdaterRuntimeServices::AddComponent() found out that the component being added can in fact be resolved and suggested replacing that call with a call to the generic overload of GameObject::AddComponent().

Due to platform constraints (this method uses methods / types not supported on all platforms) and performance implications for players, this method is marked as obsolete and you’ll get an error if you try to build the game, meaning that you do need to take some action to make your code ready for production.

While we understand that this is not a perfect solution we do believe that this is a necessary step to untangle this dependency, and we feel that the Unity 5.0 launch is the perfect time to make this change.

Was this information useful? Do you have any compliments? comments? complaints? Drop me a message!

@adrianoverona

mono-project.com Linux packages, January 2015 edition

The latest version of Mono has released (actually, it happened a week ago, but it took me a while to get all sorts of exciting new features bug-checked and shipshape).

Stable packages

This release covers Mono 3.12, and MonoDevelop 5.7. These are built for all the same targets as last time, with a few caveats (MonoDevelop does not include F# or ASP.NET MVC 4 support). ARM packages will be added in a few weeks’ time, when I get the new ARM build farm working at Xamarin’s Boston office.

Ahead-of-time support

This probably seems silly since upstream Mono has included it for years, but Mono on Debian has never shipped with AOT’d mscorlib.dll or mcs.exe, for awkward package-management reasons. Mono 3.12 fixes this, and will AOT these assemblies – optimized for your computer – on installation. If you can suggest any other assemblies to add to the list, we now support a simple manifest structure so any assembly can be arbitrarily AOT’d on installation.

Goodbye Mozroots!

I am very pleased to announce that as of this release, Mono users on Linux no longer need to run “mozroots” to get SSL working. A new command, “cert-sync”, has been added to this release, which synchronizes the Mono SSL certificate store against your OS certificate store – and this tool has been integrated into the packaging system for all mono-project.com packages, so it is automatically used. Just make sure the ca-certificates-mono package is installed on Debian/Ubuntu (it’s always bundled on RPM-based) to take advantage! It should be installed on fresh installs by default. If you want to invoke the tool manually (e.g. you installed via make install, not packages) use

cert-sync /path/to/ca-bundle.crt

On Debian systems, that’s

cert-sync /etc/ssl/certs/ca-certificates.crt

and on Red Hat derivatives it’s

cert-sync /etc/pki/tls/certs/ca-bundle.crt

Your distribution might use a different path, if it’s not derived from one of those.

Windows installer back from the dead

Thanks to help from Alex Koeplinger, I’ve brought the Windows installer back from the dead. The last release on the website was for 3.2.3 (it’s actually not this version at all – it’s complicated…), so now the Windows installer has parity with the Linux and OSX versions. The Windows installer (should!) bundles everything the Mac version does – F#, PCL facades, IronWhatever, etc, along with Boehm and SGen builds of the Mono runtime done with Visual Studio 2013.

An EXPERIMENTAL OH MY GOD DON’T USE THIS IN PRODUCTION 64-bit installer is in the works, when I have the time to try and make a 64-build of Gtk#.

January 20

Apple Watch Kit programming with C# (and Xamarin)

For my "Your First Xamarin.Forms App" talk at Evolve this year I built a very simple version of the classic "Magic Eight Ball" fortune-telling app. Seemed like a perfect example to adapt for my First Apple Watch App. It's built in C# using Xamarin (of course); Xamarin's Watch Kit Preview came out today!

Here is the finished app: a simple display that answers any question you ask ;-) Force Touch on the screen to pop-up the menu to ask another question (Shake), or simply say "Thanks". Grab the code from Github.
^ watch frame screenshots generated with Bezel thanks to the fine folks at infinitapps.

Apple Watch Projects

The solution structure for watch apps consists of three projects (notice that watch apps are split in two parts):
  • an iPhone app which delivers the watch app to the user (and is also obviously a regular iPhone app),
  • an Watch Kit Extension where the code for the watch app runs (on the iPhone, but separate to the iPhone app),
  • a Watch app which is only the storyboard and image resources that go to the watch itself.

Storyboard User Interface

After creating the three projects in a new solution, the first step is to draw the user interface in Interface Builder. Right-click on the Interface.storyboard (already in the template) and open in Xcode.

I did the following:
  • gave the interface controller a Title: 8Ball
  • dragged a Label and centered it
  • Ctrl + dragged an outlet from the label into the header file called result
  • dragged a Menu onto the scene (this is triggered by Force Touch)
  • added and named the two MenuItems: Shake & Back
  • Ctrl + dragged an action from the first menu item called shake
Remember: the storyboard (and any image resources) are the the only things that get installed on the watch itself.

WatchKit C# Code

With the user interface defined in the storyboard, I just needed to wire-up the outlet and action I created in C# to make the app work. The C# code will run in the Watch Kit Extension - on the iPhone itself, not on the CPU of the watch.

First I copied the Magic Eight Ball responses from my Xamarin.Forms app (it's a simple string array, called options) and then I started to implement methods in the InterfaceController.

The Awake method is called when the scene is created, so this is where the code selects its first random response to show the user. I store it in a local variable lastResult and also in NSUserDefaults (for the Glance, explained later).

public override void Awake (NSObject context)
{
base.Awake (context);
var rnd = new System.Random();
lastResult = options[rnd.Next(0, options.Length - 1)];
NSUserDefaults.StandardUserDefaults.SetString
(lastResult, "lastResult");
}

Then in WillActivate I set the label's text to the random value:

public override void WillActivate ()
{
result.SetText (lastResult);
}
Finally, the menu's Shake button should choose a new random response, so the action is implemented to generate new new answer, set the local lastResult variable, the NSUserDefault, and also the label's text.

partial void shake () {
var rnd = new System.Random();
lastResult = options[rnd.Next(0, options.Length - 1)];
result.SetText (lastResult);
NSUserDefaults.StandardUserDefaults.SetString
(lastResult, "lastResult");
}

That's all the code required to get the app running! I did a couple more things, however, to demonstrate how to programmatically modify the Menu...

In the Awake method I add another menu item called Thanks:

AddMenuItem (WKMenuItemIcon.Accept, "Thanks", new ObjCRuntime.Selector ("tapped"));
The Selector is implemented as shown - notice the [Export] is required:
[Export("tapped")]
void MenuItemTapped () {
result.SetText ("You're welcome!");
}

Glance Mode

I also implemented Glance mode, which simply displays the last response generated by the app.

The watch app template already includes a GlanceInterfaceController so I just had to drag a couple of Labels onto it, and Ctrl + drag an outlet for one, so I could change the text programmatically.



Because I always store a generated result in NSUserDefaults the GlanceInterfaceController, the code for the glance is really simple:
var r = NSUserDefaults.StandardUserDefaults.StringForKey("lastResult");
lastResult.SetText (r);


Currently you cannot test Glances from within Xamarin Studio, but it's easy to trigger it using Terminal and the following command (make sure you update path to match your app):

/Library/Frameworks/Xamarin.iOS.framework/Versions/Current/bin/mtouch --sdkroot=/Applications/Xcode-Beta.app/Contents/Developer/ --device=:v2:runtime=com.apple.CoreSimulator.SimRuntime.iOS-8-2,devicetype=com.apple.CoreSimulator.SimDeviceType.iPhone-6 --launchsimwatch=/Users/craigdunn/Projects/Watch8Ball/Watch8Ball/bin/iPhoneSimulator/Debug/Watch8Ball.app --watchlaunchmode=Glance

The finished glance display looks like this:

And that's it! Around 10 lines of C# code to build an Apple Watch app.

Download the Xamarin Watch Kit Preview, get the code from Github and try it for yourself!

An introduction to advertising

Welcome to the big bad world of advertising. As a game developer, advertising can be a little overwhelming. How do I make money? How do I acquire users? What do all of those weird acronyms even mean?

Let’s take a step back and look at look at both sides of the game advertising coin:

  • Monetizing your game by displaying ads for other products within your game.

  • Advertising your game in order to acquire users.

Monetization – Displaying ads inside your game

There are, of course, several strategies you can employ to make money from your game – by displaying ads, by using in-app purchases and so on. These strategies aren’t necessarily exclusive. Games that feature in-app purchases often display ads as a complementary revenue source. Games without in-app purchases can generate significant revenue if they have sufficient numbers of users.

If you decide to display ads within your game, you’ll become what’s known within the industry as a publisher making inventory (the facility to display ads within your game) available to advertisers.

Advertisers will look to target particular player demographics (players with specific characteristics, those living in a particular region of the world, for example). In order to connect you as a publisher with advertisers who find your players particularly attractive, you’ll need the services of an advertising network.

Advertising networks, such as Unity Ads (currently, probably the fastest-growing Game Ad network in the world) receive money from advertisers for providing them with inventory. Ad networks use algorithms to determine when it’s relevant to display a particular advert within a given game, both to match up advertisers’ demographic requirements with a particular game’s players and, more importantly, to optimize the chances of players clicking ads.

If you’re considering becoming a publisher and making advertising inventory available within your game, there are a number of strategies you can employ to ensure that your users don’t find those ads intrusive.

A particularly successful one, in our experience, is linking ad views to in-game rewards (coins and the like). More on how best to integrate ads into your game in a later post…

Unity Ads in Crossy Road

Advertising – Acquiring users through in-game ads

Every developer needs players for their game, but not every developer knows if spending time and money on advertising makes sense. If you’re considering advertising your game, the first thing you need to work out is how much each player is worth to you.

If your game makes a relatively large amount of money per player from in-game purchases or ads you display inside your game, using advertising to acquire new users may well make sense.

If the cost per install of advertising your game is less than the amount of revenue you make from each install the difference between the two is pure profit. In the jargon, this is expressed as follows:

ARPU – Average Revenue Per User

        Each user you bring in typically brings in X dollars in revenue

CPI – Cost Per Install

Acquiring a new user through advertising, will cost you Y dollars.

        ARPU – CPI = Profit

Once you really get into advertising, there’s a lot more to discuss: advertising creatives, optimization, targeting… we’ll go into all of that in future blog posts.

Final screen of an ad from Crossy Road

Unity Ads

Crossy Road developers Hipster Whale chose to monetize their game by publishing ads (amongst other things). With Unity Ads, they were able to generate over $1 Million in revenue in just a few weeks.

Getting started with Unity Ads is very simple – just import the free Unity Ads plugin from the Asset Store and you’re good to go!

Introducing the Xamarin WatchKit Preview

Today, we are are happy to announce the release of our WatchKit Preview for Xamarin Studio, enabling you to build, run, and test your Apple Watch apps directly from Xamarin Studio.

frontpic_bezel

WatchKit Templates

We’ve added new templates for Watch apps and Watch extensions inside Xamarin Studio. Start with a new or existing iOS app, add a Watch App to house your interface, and then add a Watch extension to power the interaction. Xamarin Studio does all of the heavy lifting for you.

projects

Test in the Simulator

Get started testing your applications in the simulator so you can be ready when devices hit the market. Xamarin Studio has support for building, running, and debugging your Watch apps in app mode. You can also test your app in Glance and Notifications mode from the command line.

simulator

Get Started Today

You can download the bits for WatchKit Preview directly from the Xamarin Developer site. To get started with WatchKit, check out the WatchKit Preview guide.

Please note that this release is a Preview. It is not available on the Stable, Beta, or Alpha channels and is a separate install. We are working hard on adding even more features for WatchKit, including support for the Xamarin Designer for iOS and Visual Studio, in future releases.

Very Important: Since this release is missing our designer support, you must follow the steps outlined in the WatchKit Preview guide to build your UIs.

See everything that WatchKit support has to offer by running the WatchKit Catalog sample from our sample gallery.

January 19

How Spry Fox harnessed Cloud Build

As an early adopter of Unity Cloud Build, prolific developer Spry Fox has found work on its next game Alphabear moving forward at a tremendous pace. Spry Fox developer Andrew Fray explains just how the power of efficient builds helped the studio.

Like many teams today, Spry Fox isn’t based in a single location. It employs talent across several continents, because they value talent and creativity more than proximity.

But managing the build process and the multitude of iterations a game goes through during development is a huge challenge; something Spry Fox Developer Andrew Fray knows well.

Aphabear

Unity Cloud Build has handled the entire compilation and bundling process for Alphabear during development, automatically processing any changes the team pushed to their source control repository, and delivering the result as a new build sent instantly via email. In short, it meant changes to the art, audio and copy appeared in new builds in minutes, on-device, without the need to ask engineers to export a build manually.

“Having our builds in the cloud, and giving people the ability to fetch it from wherever they are, out and about, is amazing,” explains Fray.

“Being spread across different continents, I can’t just call everyone over to my desk to see a new build, or pass a device around the office. That’s just not possible. It can make it very hard to share builds with your team efficiently.”

Creating and sharing builds is at the core of game development:  in order to test and gather feedback from teammates, beta players, clients, publishers and partners, game developers need to have a streamlined and effective method for building new versions and delivering them to the appropriate people. Otherwise, the process is not just merely time-consuming, but destructive to timelines and creativity.

“With our game Triple Town for mobile I needed to get builds out to the team,” offers Fray. “I needed to show them new features and get feedback quickly. Exporting the game could take some time, and that would be time looking at my machine not able to get on with my work. Once a day that might not be so bad, but then I’d be limited to feedback once a day. Really, as you iterate on a game, you want that feedback coming in all the time; it’s what helps you make a better game.”

For Spry Fox’s forthcoming word puzzler Alphabear, the team turned to the power of Unity’s currently-in-beta Cloud Build platform. “I’m even able to push a change, and then head out to pick my daughter up from school. It’s only just down the road, but I can already be testing the latest build on my phone when I’m waiting for her at the gates.”

Triple Town

But for Fray, Unity Cloud Build isn’t just about maximizing the potential of the school run; it’s about efficiency, simplicity and speed.

“When we look back at previous projects we’ve worked on that are comparable to Alphabear, Cloud Build has increased the speed and ease with which we’ve made the game,” he says. “We’ve been able to iterate so much faster, get feedback so much quicker, and have our artists more involved with the process by letting them see their output live on device.”

In the case of Spry Fox, the benefits of Unity Cloud Build have had an exponential effect which Fray is convinced results in a better quality game all round.

“The artists aren’t having to constantly ask the programmers to make builds, so the programmers have more time. And the artists themselves can iterate faster and build more confidence in the work they’re producing. It really benefits everybody’s work beyond the build process.”

Speaking with Fray it is clear Unity Cloud Build has introduced faster iteration, simplified the build process, given team members more time to focus on their core roles, and let Spry Fox continue working in the same way they always have.

And so it is that Alphabear is progressing smoothly and quickly, and a soft launch is imminent.

Unity Cloud Build is currently available as a free beta for Unity Pro users, and will in time be available for users of the free version of Unity.

Webinar Recording: Migrating Apps to the Unified API and 64-Bit

Earlier this month we announced that Xamarin.iOS 8.6, featuring the Unified API, is available in the stable channel. This release comes perfectly timed for Apple’s February 1st deadline for new iOS app submissions and June 1st deadline for all new and existing iOS app submissions or updates to include 64-bit support.

In this webinar recording, Xamarin Evangelist Mike James provides an overview on how to make sure your libraries and apps are 64-bit ready by Apple’s deadlines, including how to migrate apps to the Unified API. In addition to the Q&A at the end of the video, we have also included an extended Q&A, below, covering more of the many questions asked during the webinar.

Additional Resources

The sample used in the demo can be found here.

If you’d like to learn more about the Unified API and 64-bit, our documentation has everything you need to get started here. You can also read our blog posts on the Unified API here and here.

Q&A

General

Do we need 64-bit versions of portable libraries coming as NuGet packages to use in a ‘unified’ project?

Library creators will need to update to the new Unified API, and we’ve got some excellent documentation about this here.

Why does the compiler not decide to use int or nint for us? This does not seem to be very “.NET like”.

In a 32-bit world, NSInteger could very easily be mapped to the System.Int32 (short: int) and it worked very well. With NSInteger now being both 32-bit and 64-bit (depending on the underlying architecture of the platform), this approach no longer works.

We’ve gone through all of our iOS and Mac API’s and found every instance of the Objective-C API using NSInteger that originally was mapped to int and these now take an nint.

You can learn more about our decisions behind nint here.

What is a Type Registrar?

On startup, Xamarin.iOS will registered managed classes (which include the [Register] attribute) and methods (which include the [Export] attribute) with the Objective-C runtime. This allows managed classes to be created and managed methods to be called from Objective-C. This is how methods and properties are linked between the C# and Objective-C worlds.

You can learn more here.

How should we handle the new “n” types in shared code?

The new native types found in the Unified API should only be shared in iOS and Mac projects. When creating libraries for consumption outside of these platforms (PCL, Share libraries, etc.) you should be using Int for 32-bit values and Long for 64-bit values.

Learn more about the new type here.

So with non-64-bit devices, will we have to do something different or will it just work?

When you build your Unified API based app, it will by default build dual 32/64-bit binaries transparently.

You alluded to new garbage collection; please elaborate.

We now have a garbage collector called sgen, which is now the default (as opposed to Boehm) which was used for the Classic iOS apps. We’ve also shipped support for our new reference counting system, which helps solves a number of problems that caused apps to crash. Another benefit of the change means your app consumes less memory. (The new reference counting can also be enabled in the Classic API from the project settings)

Learn more here.

Xamarin.Forms

Should I migrate my UI shared project on Xamarin.Forms? Or just the iOS Project?

You will only need to update the iOS project rather than the shared project. You can find our documentation on Xamarin.Forms migration here.

What about migration of an existing Plugin for Xamarin.Forms? How do we keep compatibility with existing apps that might be using our control and also provide the 64-bit support?

You simply need to upgrade your plugins to 1.3.1 and add a unified Library. I have already updated mine on GitHub. You can also check out other examples here and here.

Discuss this blog post in the Xamarin Forums

January 18

Optimizing Shader Info Loading, or Look at Yer Data!

A story about a million shader variants, optimizing using Instruments and looking at the data to optimize some more.

The Bug Report

The bug report I was looking into was along the lines of “when we put these shaders into our project, then building a game becomes much slower – even if shaders aren’t being used”.

Indeed it was. Quick look revealed that for ComplicatedReasons(tm) we load information about all shaders during the game build – that explains why the slowdown was happening even if shaders were not actually used.

This issue must be fixed! There’s probably no really good reason we must know about all the shaders for a game build. But to fix it, I’ll need to pair up with someone who knows anything about game data build pipeline, our data serialization and so on. So that will be someday in the future.

Meanwhile… another problem was that loading the “information for a shader” was slow in this project. Did I say slow? It was very slow.

That’s a good thing to look at. Shader data is not only loaded while building the game; it’s also loaded when the shader is needed for the first time (e.g. clicking on it in Unity’s project view); or when we actually have a material that uses it etc. All these operations were quite slow in this project.

Turns out this particular shader had massive internal variant count. In Unity, what looks like “a single shader” to the user often has many variants inside (to handle different lights, lightmaps, shadows, HDR and whatnot – typical ubershader setup). Usually shaders have from a few dozen to a few thousand variants. This shader had 1.9 million. And there were about ten shaders like that in the project.

The Setup

Let’s create several shaders with different variant counts for testing: 27 thousand, 111 thousand, 333 thousand and 1 million variants. I’ll call them 27k, 111k, 333k and 1M respectively. For reference, the new “Standard” shader in Unity 5.0 has about 33 thousand internal variants. I’ll do tests on MacBook Pro (2.3 GHz Core i7) using 64 bit Release build.

Things I’ll be measuring:

  • Import time. How much time it takes to reimport the shader in Unity editor. Since Unity 4.5 this doesn’t do much of actual shader compilation; it just extracts information about shader snippets that need compiling, and the variants that are there, etc.
  • Load time. How much time it takes to load shader asset in the Unity editor.
  • Imported data size. How large is the imported shader data (serialized representation of actual shader asset; i.e. files that live in Library/metadata folder of a Unity project).

So the data is:

Shader   Import    Load    Size
   27k    420ms   120ms    6.4MB
  111k   2013ms   492ms   27.9MB
  333k   7779ms  1719ms   89.2MB
    1M  16192ms  4231ms  272.4MB

Enter Instruments

Last time we used xperf to do some profiling. We’re on a Mac this time, so let’s use Apple Instruments. Just like xperf, Instruments can show a lot of interesting data. We’re looking at the most simple one, “Time Profiler” (though profiling Zombies is very tempting!). You pick that instrument, attach to the executable, start recording, and get some results out.

shaderopt01-instruments shaderopt02-attach shaderopt03-timeprofile

You then select the time range you’re interested in, and expand the stack trace. Protip: Alt-Click (ok ok, Option-Click you Mac peoples) expands full tree.

shaderopt04-expand

So far the whole stack is just going deep into Cocoa stuff. “Hide System Libraries” is very helpful with that:

shaderopt05-hidesystem

Another very useful feature is inverting the call tree, where the results are presented from the heaviest “self time” functions (we won’t be using that here though).

shaderopt06-inverttree

When hovering over an item, an arrow is shown on the right (see image above). Clicking on that does “focus on subtree”, i.e. ignores everything outside of that item, and time percentages are shown relative to the item. Here we’ve focused on ShaderCompilerPreprocess (which does majority of shader “importing” work).

shaderopt08-focused

Looks like we’re spending a lot of time appending to strings. That usually means strings did not have enough storage buffer reserved and are causing a lot of memory allocations. Code change:

shaderopt09-reserve

This small change has cut down shader importing time by 20-40%! Very nice!

I did a couple other small tweaks from looking at this profiling data – none of them resulted in any signifinant benefit though.

Profiling shader load time also says that most of the time ends up being spent on loading editor related data that is arrays of arrays of strings and so on:

shaderopt10-loadprofile

I could have picked functions from the profiler results, went though each of them and optimized, and perhaps would have achieved a solid 2-3x improvement over initial results. Very often that’s enough to be proud!

However…

Taking a step back

Or like Mike Acton would say, ”look at your data!” (check his CppCon2014 slides or video). Another saying is also applicable: ”think!

Why do we have this problem to begin with?

For example, in 333k variant shader case, we end up sending 610560 lines of shader variant information between shader compiler process & editor, with macro strings in each of them. In total we’re sending 91 megabytes of data over RPC pipe during shader import.

One possible area for improvement: the data we send over and store in imported shader data is a small set of macro strings repeated over and over and over again. Instead of sending or storing the strings, we could just send the set of strings used by a shader once, assign numbers to them, and then send & store the full set as lists of numbers (or fixed size bitmasks). This should cut down on the amount of string operations we do (massively cut down on number of small allocations), size of data we send, and size of data we store.

Another possible approach: right now we have source data in shader that indicate which variants to generate. This data is very small: just a list of on/off features, and some built-in variant lists (“all variants to handle lighting in forward rendering”). We do the full combinatorial explosion of that in the shader compiler process, send the full set over to the editor, and the editor stores that in imported shader data.

But the way we do the “explosion of source data into full set” is always the same. We could just send the source data from shader compiler to the editor (a very small amount!), and furthermore, just store that in imported shader data. We can rebuild the full set when needed at any time.

Changing the data

So let’s try to do that. First let’s deal with RPC only, without changing serialized shader data. A few commits later…

shaderopt12-optimizerpc

This made shader importing over twice as fast!

Shader   Import
   27k    419ms ->  200ms
  111k   1702ms ->  791ms
  333k   5362ms -> 2530ms
    1M  16784ms -> 8280ms

Let’s do the other part too; where we change serialized shader variant data representation. Instead of storing full set of possible variants, we only store data needed to generate the full set:

shaderopt14-optimizestorage

Shader   Import              Load                 Size
   27k    200ms ->   285ms    103ms ->    396ms     6.4MB -> 55kB
  111k    791ms ->  1229ms    426ms ->   1832ms    27.9MB -> 55kB
  333k   2530ms ->  3893ms   1410ms ->   5892ms    89.2MB -> 56kB
    1M   8280ms -> 12416ms   4498ms ->  18949ms   272.4MB -> 57kB

Everything seems to work, and the serialized file size got massively decreased. But, both importing and loading got slower?! Clearly I did something stupid. Profile!

shaderopt15-rebuildprofile

Right. So after importing or loading the shader (from now a small file on disk), we generate the full set of shader variant data. Which right now is resulting in a lot of string allocations, since it is generating arrays of arrays of strings or somesuch.

But we don’t really need the strings at this point; for example after loading the shader we only need the internal representation of “shader variant key” which is a fairly small bitmask. A couple of tweaks to fix that, and we’re at:

Shader  Import    Load
   27k    42ms     7ms
  111k    47ms    27ms
  333k    94ms    76ms
    1M   231ms   225ms

Look at that! Importing a 333k variant shader got 82 times faster; loading its metadata got 22 times faster, and the imported file size got over a thousand times smaller!

One final look at the profiler, just because:

shaderopt18-profileimport

Weird, time is spent in memory allocation but there shouldn’t be any at this point in that function; we aren’t creating any new strings there. Ahh, implicit std::string to UnityStr (our own string class with better memory reporting) conversion operators (long story…). Fix that, and we’ve got another 2x improvement:

Shader  Import    Load
   27k    42ms     5ms
  111k    44ms    18ms
  333k    53ms    46ms
    1M   130ms   128ms

The code could still be optimized further, but there ain’t no easy fixes left I think. And at this point I’ll have more important tasks to do…

What we’ve got

So in total, here’s what we have so far:

Shader   Import                Load                 Size
   27k    420ms-> 42ms (10x)    120ms->  5ms (24x)    6.4MB->55kB (119x)
  111k   2013ms-> 44ms (46x)    492ms-> 18ms (27x)   27.9MB->55kB (519x)
  333k   7779ms-> 53ms (147x)  1719ms-> 46ms (37x)   89.2MB->56kB (this is getting)
    1M  16192ms->130ms (125x)  4231ms->128ms (33x)  272.4MB->57kB (ridiculous!)

And a fairly small pull request to achieve all this (~400 lines of code changed, ~400 new added – out of which half were new unit tests I did to feel safer before I started changing things):

shaderopt22-pr

shaderopt23-pr

Overall I’ve probably spent something like 8 hours on this – hard to say exactly since I did some breaks and other things. Also I was writing down notes & making sceenshots for the blog too :) The fix/optimization is already in Unity 5.0 beta 20 by the way.

Conclusion

Apple’s Instruments is a nice profiling tool (and unlike xperf, the UI is not intimidating…).

However, Profiler Is Not A Replacement For Thinking! I could have just looked at the profiling results and tried to optimize “what’s at top of the profiler” one by one, and maybe achieved 2-3x better performance. But by thinking about the actual problem and why it happens, I got a way, way better result.

Happy thinking!

January 17

Microsoft Band: the end

I had a lot of fun with the Band initially.

Then after literally two seconds in the shower after a long run, it died. I doubt it got that wet - I literally stepped into the shower, noticed the Band was still on my wrist, then took it off and placed it out to dry.

But that was enough to kill it. The screen went all crazy and illegible. It was dead.




I had paid the $20 'extended warranty' fee, so the guys at the Microsoft Store grudgingly replaced it. I say grudgingly because one staff member really didn't seem sure about it; luckily another guy got involved and was more than happy to help me. They made it clear that if I hadn't paid for the extended warranty, they would not be replacing it at all.

Then they asked for another $20. To cover this Band with extended warranty. I was very annoyed by this. I didn't pay. But now I'm too scared to use the Band. What if, while running outdoors, it rains? The Band apparently will die at the slightest hint of water, and next time Microsoft promised they would NOT be replacing it unless I paid the additional $20.

So now I hardly wear it. It's in a drawer somewhere. So long, Microsoft Band, I hardly knew yea...

Microsoft: if you put a GPS in a fitness device, you're saying it's okay to use it outdoors. If that same device fails in the slightest mist of rain, the device itself is a failure.

January 16

Global Game Jam 2015

It’s that time of the year again! Global Game Jam is on next weekend! Unity Pro trial licenses are available to download right now, so you can prepare your toolset for the jam. We’re also running a number of giveaways and shipping Unity people to game jams sites across the world.

Unity 4 Pro trial licenses are valid for thirty days and it doesn’t matter whether you’ve used a trial version before or not. To get it, head over to our Global Game Jam site and login. To use Unity Cloud Build with your Unity Pro GGJ trial license, use GA-MEJA-MGAM-EJAM-GAME-JAMG as a license code.

You can also enter a raffle to win Unity Pro licenses at a number of individual game jam sites (in countries that allow sweepstakes). We’ll announce the lucky winners on January 27.

Just like last year, we’re also running Twitter sweepstakes for jammers using Unity. Just tweet about whatever you’re making with #ggj15 #madewithunity before midnight San Francisco time on Sunday and you can win a $200 voucher for the Asset Store.

I’m heading out to Plovdiv, Bulgaria, for the jam. More than 30 other Unity and Unity affiliated folk will meet you in person in Cleveland, Moscow, Vancouver CA, Taipei, Washington D.C., Manila, Atlanta, Loveland (CO), Seoul, Okinawa, London-Google Campus, London-SAE, Singapore, Memphis, Staffordshire, Tokyo-Hachioji, Tokyo-Koutou-ku , Malmo, Melbourne, Shanghai, Vilnius, Paris, Los Angeles, Mexico City, Porto Alegre, Portland, Toronto, Cambridge (MA), Nagano and San Francisco.

Arturo Nunez will spend the weekend on Google Hangout with jam sites in Mexico, Guatemala, Peru, Chile and Colombia. He’s looking to add more jammers in Latin America, so let him now in the comments if you’d like to join the Spanish speaking hangout.

Contest: Show Us Your App!

Have you created a beautiful app with Xamarin? Here’s your chance to show the world what you’ve built!

In this contest, you will create a short video showing us the app you have created, how it works, and any other fun details about the development process while building your mobile application.

blog phone pic 2

How to Enter:

  1. Record a short video demoing your Xamarin app
  2. Post your video to the Show Us Your App forum thread
  3. Tweet your video with the hashtags #Xamarin #BuiltWithXamarin

Here is a sample from our own James Montemagno, demoing his Android app “Bike Now”:

Prize:

  • Best App: $100 App Store / Google Play credit to help promote your app!
  • Best Video: $100 App Store / Google Play credit to help promote your app!

All submissions must be made by Monday, February 2nd at 12pm EST. We will evaluate each video and choose the winner based on concept, video quality, and originality. A valid entry consists of a tweet and forum post with a demo video of your personal app. Contestants should follow @XamarinHQ to enable us to DM you for private follow-up. There is no purchase necessary to enter the Show Us Your App Video contest.

January 15

Xamarin Event: TechDays 2015 in Paris

Join Xamarin at Microsoft TechDays 2015 in Paris, France from February 10-12. Key members from Team Xamarin will be available all three days to answer your questions, discuss your apps and projects, and catch you up on our incredible 2015 roadmap.

Xamarin at TechDays 2015

Mike James, Xamarin Developer Evangelist, will speak about cross-platform development with Xamarin and Xamarin.Forms on Wednesday, February 11th at 11:00am.

Visit us at Booth S67, or schedule a dedicated time to speak with one of our team members.

À bientôt!

Announcing the Unity Analytics Open Beta

Many games don’t achieve the success they deserve, and that’s a real shame. If your game is underperforming, analytics can help you understand why that’s the case, so you can make informed decisions to dramatically improve its performance.

Informed game design decisions can keep players playing longer and spending more. If players spend more time in your game, it’s a fair bet that it’s because they like it. This also makes them more inclined to recommend it to others, potentially creating a virtuous circle.

It’s for these reasons that we’re now making powerful, easy to use analytics services available to Unity developers everywhere. Our current release is just the beginning – we first want to make sure we are delivering simple, high quality analytics to those developers who may not have the time or resources to use other solutions or to build their own. Over time, we’ll be rolling out more research, data, and analytics related products all with an eye towards the larger goal of democratizing game success. With better analytics and data, we strongly believe all developers will have an opportunity to build games that players love, and to find players that keep coming back.

Check out the (free) beta

How it works

Unity Analytics gathers data from your game and transfers that data to a cloud-based datastore. From there, our advanced segmentation technology processes and analyzes the data, which is then delivered to the Unity Analytics Dashboard for you to inspect.

Getting started

The web-based dashboard is your analytics command center. It’s the place where you monitor simple game performance metrics. As you gain greater knowledge of your game and become more familiar with Unity Analytics’ tools, you can set up custom metrics to help you pinpoint exactly where you want to make changes in your game.

The open beta dashboard comes with handy explanations and tips built into the interface to make the process of familiarizing yourself with workflows and tools as intuitive and simple as possible.

Here are a few tips to help you understand how you can make a start on using your Dashboard to understand your game’s engagement, retention, and monetization performance.

Your Dashboard will tell you the number of daily active users (DAU) and monthly active users (MAU).  DAU is the number of players who played at least one session on a given day. It is used to evaluate the “stickiness” of your game.

MAU is the number of unique players who played at least one session in the last thirty days. It’s a useful metric for measuring the growth of your game.  DAU and MAU are indicators of Engagement, the extent to which your game is constantly drawing people in and keeping them glued.

Another metric to examine in your Dashboard is the retention rate, the percentage of new players who return over a specified period of time after their first day in the game. Standard retention rates are calculated for 1, 7, 30 days. The retention rate indicates how frequently your player returns and engages with your game.

As your player population grows and retention rates are solid, you’ll want to consider boosting your monetization. The Dashboard provides ARPDAU and ARPU information. These are metrics you can use to gauge and boost your revenue stream.

ARPDAU is the Average Revenue Per Daily Active User. It is calculated as the Total Revenue for a Given Day / Number of Active Users that Day. For many games, an ARPDAU of $0.05 is a good first benchmark.

ARPU (Average Revenue Per User) is calculated as Total Revenue / Total Number of Users and describes your average earnings per user. The benchmark for ARPU varies widely depending on the type and genre of your game.

READY TO TRY OUT UNITY ANALYTICS BETA?

Sign up now. The beta is free to all Unity developers! We currently support iOS and Android applications, with support for additional platforms upcoming.

After signing up, if you have thoughts and experiences you want to share or features you want added, please stay in touch. At this time, the best place to request new features is the discussion area in the Unity Analytics forum. If you run into any difficulties, you can also send a note at https://analytics.unity3d.com/support!

Unity Analytics (formerly Playnomics) is a new member of the Unity family, but our industry-leading technology has been under development for five years. Game developers across the world rely on Unity Analytics tools to provide the very richest data insights in an easy-to-digest, actionable format.

image02

January 14

New Xamarin Profiler Preview

A new Xamarin Profiler preview is available for download today. This release focuses on boosting performance and improving usability. Here’s a rundown of some of our favorite features:

Time Range Selection

Screen Shot 2015-01-08 at 5.38.46 PM

Time range selection lets you highlight an interesting area in the instrument chart and limit the profiling data to a specific time period. Use it to explore a sudden peak in memory usage, keep tabs on performance while your app is running a particular task, or just limit your scope to a manageable amount of data.

Screenshot 2015-01-08 16.44.18

Better Snapshots

Snapshot automation allows you to set the profiler to take snapshots at regular intervals during your profiling session. The snapshots panel also supports rough snapshot comparison, so you can see when memory usage dropped between snapshots (marked in red).

Before memory fix:

Screen Shot 2015-01-09 at 5.18.37 PM

After memory fix:

Screen Shot 2015-01-09 at 5.18.22 PM

And More!

Xamarin.Mac Support – We’ve added initial support for profiling desktop applications built with Xamarin.Mac. Now, your Mac desktop apps can be just as polished as your mobile apps!

Preferences Panel – You can set all your preferences for sampling, snapshots, and more in one place.

Screen Shot 2015-01-09 at 4.25.09 PM

Drag & Drop for Windows – One of our favorite new features is the addition of drag & drop to the Windows version of the Xamarin Profiler. You can load saved files of previous runs by simply dragging and dropping them into the Profiler interface.

Screenshot 2015-01-08 16.44.46

Get it Now

The new Profiler preview is available for download from the Profiler landing page. In addition to the new features, we’ve addressed many customer-reported bugs, issues, and requests. A full list of improvements is captured in the release notes.

Get in touch with our team on the Xamarin Forums and let us know what you think of the new features!

January 13

Major Enhancements to Xamarin.Forms

Xamarin.Forms is a powerful library that enables developers to build native user interfaces from a shared C# code base for iOS, Android, and Windows Phone. The latest release, Xamarin.Forms 1.3, introduces several major enhancements to the platform to increase productivity and to extend your application even further. Additionally, this release also brings Unified support for iOS applications built with Xamarin.Forms to coincide with the release of Xamarin.iOS 8.6, which is required for this update.

crm-app

Application Lifecycle

It is now easier than ever to respond to application lifecycle events in your Xamarin.Forms applications. With the new Application base class you can tap into several lifecycle methods such as OnStart, OnSleep, and OnResume. The Application class also delivers a simplified solution for specifying your MainPage of your application. Here is an example of what your new Application class might look like:

public class App : Xamarin.Forms.Application
{
    public App ()
    {
        MainPage = new ContentPage { Title = "App Lifecycle Sample" }; // your page here
    }
    protected override void OnStart()
    {
        // Handle when your app starts
        Debug.WriteLine ("OnStart");
    }
    protected override void OnSleep()
    {
        // Handle when your app sleeps
        Debug.WriteLine ("OnSleep");
    }
    protected override void OnResume()
    {
        // Handle when your app resumes
        Debug.WriteLine ("OnResume");
    }
}

Be sure to read through our Xamarin.Forms Application Lifecycle documentation on how to get started using or transitioning your app to take advantage of these new events.

Styles

Xamarin developers love that they are able to use XAML to declare their user interfaces across iOS, Android, and Windows Phone. However, the immense amount of properties on controls can make your XAML cluttered. Additionally, if you wanted to change the look across all of your controls, you had to update each and every control. The introduction of Styles alleviates this issue by allowing you to define control defaults, known as styles, in your ResourceDictionary. Here is an example of what a few buttons might look like on a page:

<!--?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="StylesApps.MyPage">
  <ContentPage.Content>
    <StackLayout Padding="10" Spacing="10">
      <Button Text="Login"
              HorizontalOptions = "FillAndExpand"
              HeightRequest = "42"
              BackgroundColor = "#77d065"
              BorderColor = "Black"
              BorderRadius = "5"
              BorderWidth = "0"
              TextColor = "White"/>
      <Button Text="Logout"
              HorizontalOptions = "FillAndExpand"
              HeightRequest = "42"
              BackgroundColor = "#77d065"
              BorderColor = "Black"
              BorderRadius = "5"
              BorderWidth = "0"
              TextColor = "White"/>
      <Button Text="Register"
              HorizontalOptions = "FillAndExpand"
              HeightRequest = "42"
              BackgroundColor = "#77d065"
              BorderColor = "Black"
              BorderRadius = "5"
              BorderWidth = "0"
              TextColor = "White"/>
    </StackLayout>
  </ContentPage.Content>
</ContentPage>

You can see there are a lot of properties that are the same across all of these buttons. To clean this up, you simply need define a base style in the ContentPage’s Resources, and then set the Button’s Style property to the Key.

<!--?xml version="1.0" encoding="UTF-8"?-->
<?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="StylesApps.MyPage">
  <ContentPage.Resources>
    <ResourceDictionary>
      <Style x:Key="ButtonStyle" TargetType="Button">
         <Setter Property="HorizontalOptions" Value="FillAndExpand"/>
         <Setter Property="BackgroundColor" Value="#77d065"/>
         <Setter Property="BorderColor" Value="Black"/>
         <Setter Property="HeightRequest" Value="42"/>
         <Setter Property="BorderRadius" Value="5"/>
         <Setter Property="BorderWidth" Value="0" />
         <Setter Property="TextColor" Value="White"/>
      </Style>
    </ResourceDictionary>
  </ContentPage.Resources>
    <ContentPage.Content>
      <StackLayout Padding="10" Spacing="10">
        <Button Text="Login" Style="{StaticResource ButtonStyle}" />
        <Button Text="Logout" Style="{StaticResource ButtonStyle}"/>
        <Button Text="Register" Style="{StaticResource ButtonStyle}"/>
      </StackLayout>
  </ContentPage.Content>
</ContentPage>

Now, adjusting any of the properties in the style will automatically apply to all of the buttons on the page that have this style set.

Styles

Triggers

There are several types of triggers now available in Xamarin.Forms including event, data, and multi triggers. If you have never heard of a trigger in styling before, they are essentially objects that enable you to apply changes when certain conditions are met on a control. For instance, you may want to scale up an Entry field when it has focus and also turn the text green. The code to implement this is as simple as extending the Style for a control in the resources. When the trigger’s property is met, the setter will be executed automatically. When the trigger’s property is not met, or changes, the setters will be returned to their original values.

<!--?xml version="1.0" encoding="UTF-8"?-->
<?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="StylesApps.MyPage2">
  <ContentPage.Resources>
    <ResourceDictionary>
      <Style x:Key="EntryTrigger" TargetType="Entry">
        <Style.Triggers>
          <Trigger Property="IsFocused" Value="True" TargetType="Entry">
            <Setter Property="Scale" Value="1.1" />
            <Setter Property="TextColor" Value="Green" />
          </Trigger>
        </Style.Triggers>
      </Style>
    </ResourceDictionary>
  </ContentPage.Resources>
  <ContentPage.Content>
    <StackLayout Padding="20" Spacing="10">
      <Entry Placeholder="Username" Style="{StaticResource EntryTrigger}" />
      <Entry Placeholder="Password" Style="{StaticResource EntryTrigger}"/>
      <Button Text="Login" />
    </StackLayout>
  </ContentPage.Content>
</ContentPage>

Xamarin.Forms Triggers

Navigation Stack

The navigation system in Xamarin.Forms has also been overhauled in 1.3 to enable you to push, pop, and insert pages easily. In addition you can now specify whether you would like to animate pages in and out during navigation. Here is a look at the new INavigation API:

public interface INavigation
{
    IReadOnlyList NavigationStack { get; }
    IReadOnlyList ModalStack { get; }
    void RemovePage (Page page);
    void InsertPageBefore (Page page, Page before);
    Task PushAsync (Page page);
    Task PopAsync ();
    Task PopToRootAsync ();
    Task PushModalAsync (Page page);
    Task PopModalAsync ();
    Task PushAsync (Page page, bool animated);
    Task PopAsync (bool animated);
    Task PopToRootAsync (bool animated);
    Task PushModalAsync (Page page, bool animated);
    Task PopModalAsync (bool animated);
}

Xamarin.Forms navigation

In addition to these updates you will also find a new virtual method on any of your Pages: OnBackButtonPressed(), which allows you to tap in to find out when the physical back button was pressed on the device. Combining these updates together give you much more flexibility when building your application.

So Much More

These features are just the beginning of everything packed into Xamarin.Forms 1.3. You can read about the plethora of features and fixes in this release on the Xamarin Forums. Additionally, you will find new additions and updates to our comprehensive documentation on our developer portal to help you get started with this release.

*Note: Versions 1.3.0 and 1.3.1 have identical APIs except that the latter has support for the Unified API in Xamarin.iOS 8.6.

Learn More Live

To see Xamarin.Forms 1.3 in action covering these new features and many more, join Xamarin’s Craig Dunn for a live webinar on Thursday, January 29th at 11am EST.
 

Register Now

 

Crossy Road and Unity Ads

Crossy Road is fun, adorable, addictive and full of cultural references. It also earns money. Hipster Whale already grossed over a million dollars from using Unity Ads in the iOS version of the game alone. Why did they decide to go with free to play? Why did the chicken cross the road?

Andy Sum and Matt Hall met in October 2013 during a monetization talk at a conference and after doodling a whale on their notes, started talking game ideas. Inspired by Froggy and Flappy Bird, as well as Disco Zoo and Fez, Crossy Road was a twelve-week project. The Australian duo collaborated remotely the whole time. The game released on the App Store November 20.

Matt has developed three other App Store number one games. For Andy, Matt’s junior by 15 years, Crossy Road is his first commercial mobile release. So Matt got the responsibility for the mobile-specific details, while Andy experimented with the design in the Unity editor. “I did a lot of fine tuning on the difficulty to keep the curve satisfying. I always tested it on Matt first,” he says.

Monetization was an integral part of the design. “We wanted it to be free, so that everyone has a chance to play,” says Matt. At the same time, he wanted to shoot for a big financial hit that would allow the developers total creative freedom on their future projects.

Unity Ads in Crossy Road Final screen of an ad from Crossy Road Crossy Road profile on Everyplay Dark Lord's demise in Crossy Road Hipster Whale ran into a train

“I played Disco Zoo and thought that video ads were a really good way to earn money without getting into people’s faces. We just needed to figure out a fun reason for players to watch them”. In the game, watching ads earns coins. Players can use coins to buy new characters that hop across the endless dangerous road in new and often hilarious ways. But it’s also possible to simply buy them with real money or just collect coins in the game.

“We didn’t want any consumable purchases, we wanted to do something that everybody could pay a little bit for if they wanted to, but where it wasn’t necessary to keep paying,” says Andy. This makes the game really transparent, which is especially important to parents of small children.

Hipster Whale heard good things about Unity Ads and since they were already familiar with the Unity engine, it was a pretty easy decision. “It worked straight away. Plugins can make your game unstable sometimes, but we didn’t have any problems with this one,” says Matt. “It’s great that the ads are only fifteen seconds and exclusively for other games”.

Playing the game, it’s striking how the visual UI makes the whole “watch ads to earn coins, but you can simply skip this if you don’t care” message extremely clear. Another detail that makes Crossy Road so kid-friendly, but also helps with localization.

It’s fun to die in the game. A chicken, a black sheep, PewDiePie’s dog or a hipster whale get smashed by trains, run over by trucks and drowned in water, just like in classic cartoons (think Wile E. Coyote). Players can take screenshots and videos, then share them with their friends. “Let’s Play videos inspired us to try out Everyplay,” says Matt. “Over 200,000 people have shared their replays, that definitely helps”.

H65A8921(colour)

Crossy Road recently launched on Android. The monetization model is the same, but you can also play as the Android robot and score on Google leader boards. At the end of January, Hipster Whale will celebrate Australia day by adding Aussie animals (yes, that includes a platypus) and environments.

What’s next? “When you get into ‘development hell’ during a project, you get a lot of ideas for games you could be making in the future. Now both me and Andy can work on our own projects without worrying and stressing about making money,” says Matt. “At the same time, we would be crazy not to keep building on Crossy Road.”

What’s their advice for up and coming indies?

“Don’t believe that success in the market is random. You can definitely make it work! Just start thinking about it very early on. The Casual Connect conference is a good place to learn from games that make money.  Don’t copy them, but try to understand why they’re working.” says Matt.

Andy adds that practice makes perfect: “Just make games! We’ve been both developing since we were kids. I also got a lot of the skills I needed through game jams. Even when developing Crossy Road, I took part in the 7DFPS.”

Getting started with Unity Ads is very simple – just import the free Unity Ads plugin from the Asset Store and you’re good to go!

January 12

Xamarin.iOS Unified API with 64-bit Support

64bit-150x150We are pleased to announce that Xamarin.iOS 8.6, featuring the Unified API, has been released and is available in the stable channel. The entire team has been working hard on this release for over a year to bring you the Unified API with 64-bit support. Please note that Apple announced two important deadlines for when your app must include 64-bit support:

  • February 1st: New iOS app submissions
  • June 1st: All new and existing iOS app submissions or updates

Updated Components and Libraries

We are rolling out updates for official Xamarin Components and NuGet packages with support for the Unified API. If you are a library creator and have not updated your component or NuGet package yet, please do so as soon as possible so that app publishers have time to migrate and test apps before Apple’s February 1st deadline.  Check out Matt Ward’s blog post on how to update your library for the new Unified API.

Get Started Today

You can begin migrating your apps today by using our built in migration assistant for both Xamarin Studio and Visual Studio. If you need more guidance on migrating your app to the Unified API, make sure to read through our full guide on our documentation site, or check out this Xamarin University Lightning Lecture.

Live Webinar Recording

If you’d like to see migration in action, we have the recording of Xamarin Evangelist Mike James’ webinar “Migrating Apps to the Unified API and 64-Bit” here, including an extended Q&A.

Celebrating our first Cloud Hack Week

In December, Unity engineers from all over the world descended on our Seattle office for our first ever Hack Week focused on cloud services.  Teams attended from our Austin, Montreal, San Francisco, Seattle, and Helsinki offices.

Hack Week is one of the ways we inspire and promote innovation at Unity.  Broadly stated, the purpose is to collaborate across different engineering teams and work on projects outside of our day to day roles.  Hack Week gives our engineers time to experiment building out new products and services, to work directly with customers and colleagues from across the company.

Traditionally, our Hack Weeks have focused on the Unity engine, and many of our graphics, audio and physics features evolved from projects created at Hack Week. With our new focus on helping developers create great games, and connecting those games with an audience, the theme of Hack Week this time around was cloud services that would support the development and distribution of games.

DSC_0091

We kicked it off Monday with developers pitching their ideas from a huge list of over thirty potential projects. The only rule is that anything goes! Engineers then self organized into teams and work on projects they feel most passionate about. Five long days and four busy nights later, the entire company tunes in to see what has been created.

We were fortunate to be visited during the week by local developers Camouflaj, Refract, Spryfox and V1 Interactive who talked about how they develop their games with Unity, and gave us a sneak preview of what they are working on. It was great to hear about their successes and challenges developing their games and learn how Unity can do more to help on the services side.

At the end of the week, seven projects reached demo stage, and we also got a list of cool projects, features and ideas to share with the Unity community.

Projects included:

  • Unity Cloud Data – Ever needed to change a variable in your game, but don’t want to make a new build? Are players telling you the game is too easy or hard? Cloud Data lets you store variables and values of your game in Unity Cloud, minimizing development time for quick changes. In the demo, the team tweaked gravity values, spawn rate and fire rate in a game, which automatically updated the variables on launch.

  • Heatmap Analytics – Numbers and charts can be interesting but a little dry, especially for creative people. This project unlocked player event data from a game to show “heat maps” in our Analytics dashboard. The heat map tracks events in game space so that the developer can identify spatial groupings where important events (point gain, death, kills, etc) occur.  It also created incredible visuals. During the week, the project went live with one game, and the designer told us the feedback immediately improved his game!

Screen Shot 2014-12-10 at 12.27.48 PM

  • Unity Devstream – With so much going on around a Unity project, the DevStream is a new type of dashboard where every Unity service can report events to a master API. This gives all devs on a project a high-level view as to what is going on. If you’ve used Slack.com to work together on a project, you know exactly how useful this can be.

  • VR SceneShot – VR games powered by Unity are appearing everywhere, and a VR project was inevitable at Hack Week. This team created a tool that takes a static 360 degree rendering of a Unity scene and display so it can be viewed on a mobile device with a VR headset. You can take sceneshots directly in the editor, then use the service to view and share them via WebGL and a mobile app. Great for sharing VR ideas with anyone that has a headset.

  • Mobile analytics dashboard – We’ve already got Unity Cloud Analytics in a Web page, but how about a Unity mobile app that displays analytics for your games? The app can receive API feeds from all Unity Cloud services (Analytics, Build, etc.) to show metrics that developers care about (e.g., current DAU, revenue, build stats, etc.). You can further drill-down into specific stats and see a time-series chart with historical data. Stretch goal: Create a fun game with the charts!

  • Chat in Unity – Many game dev teams use third party chat clients when working together in Unity. This project added a new chat window directly to the editor, so you could see activity and communicate with other devs working on the same project. It was fun, once everyone quit chatting about Star Wars and got back to coding!

  • Cloud editorAce is a beautiful, high performance code editor for the Web. Wouldn’t it be cool to edit your Unity project code directly from a Web page, and remotely debug? Our devs thought so too, and created a great prototype that did exactly that.

So when can you get these services? It always take time to determine which projects turn into production services, but we are moving ahead with one of these projects already in alpha. We look forward to sharing more of them with our community in 2015.

It was a great week to write code and spend time with our fellow engineers and we can’t wait to do it again. Did you like the ideas above? Which ones would you like to use? Have a better idea for a service you’d like to see developed?  Throw us a comment.  Want to be a part of Hack Week by joining Unity Technologies? Check out our open positions.

DSC_0045 DSC_0034 DSC_0075 DSC_0080 DSC_0079 DSC_0078 DSC_0076 DSC_0067 DSC_0060 DSC_0061 DSC_0056 DSC_0055 DSC_0053 DSC_0052 DSC_0048 DSC_0050 DSC_0046 DSC_0033

IKVM.NET 8.0 Release Candidate 1

The second release candidate is available. It can be downloaded here or from NuGet.

What's New (relative to rc 0):

  • Fixed build error when using Java 8u25 or newer.
  • Bug fix. Unsafe.compareAndSwapObject should resolve field before passing it to MakeTypedReference.
  • Implemented OperatingSystemMXBean.getFreePhysicalMemorySize and OperatingSystemMXBean.getTotalPhysicalMemorySize.

Binaries available here: ikvmbin-8.0.5449.1.zip

Sources: ikvmsrc-8.0.5449.1.zip, openjdk-8-b132-stripped.zip

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