Mike's Dev Blog

[Video] Xamarin Designer for iOS in Visual Studio

Posted in iOS, Visual Studio, Xamarin by mikebluestein on August 21, 2014

Here’s a recording of the recent video I did for the Microsoft Flashcast series showing how to use the Xamarin Designer for iOS in Visual Studio:

Be sure to check out my colleague James’ Flashcast on Xamarin.Forms on August 27th.

Video – Build Your First iOS App with Visual Studio and Xamarin

Posted in iOS, Visual Studio, Xamarin by mikebluestein on August 4, 2014

Here’s a video I made for Microsoft’s Flashcast series showing how to develop an iOS application using Visual Studio:

My colleague James did one for Android as well: http://flashcast.azurewebsites.net/stream/episode/5

Later this month we’ll have more Flashcasts, including one that shows how to use Xamarin’s iOS Designer for Visual Studio, and another on Xamarin.Forms. Keep an eye out for these, as well as other great topics at http://flashcast.azurewebsites.net

Using Twilio with Xamarin

Posted in Xamarin by mikebluestein on July 23, 2014

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:


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


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:


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);

            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 :)

Xamarin Getting Started Sampler

Posted in Xamarin by mikebluestein on July 1, 2014

There are many great resources for learning Xamarin, ranging from docs, samples and videos, to full-blown training via Xamarin University. If you’re just getting started, here are a list of resources to get you off to a good start. There are many other articles and samples as well in the Xamarin Developer Center, so it really depends upon your interests, but these are good fundamental topics in any case:




Also see:

And check out the recipes, samples and videos sections as well:

iOS 8 Scene Kit sample in F#

Posted in iOS by mikebluestein on July 1, 2014

Here’s an F# iOS 8 Scene Kit port of the C# code from the Xamarin blog, ported with some help from Larry O’Brien.

namespace FSHelloSceneKit
open System
open MonoTouch.UIKit
open MonoTouch.Foundation
open MonoTouch.SceneKit
type FSHelloSceneKitViewController () =
    inherit UIViewController()
    let CreateDiffuseLightNode (color: UIColor, position: SCNVector3, lightType: NSString): SCNNode = 
        new SCNLight ( Color = color, LightType = lightType )
        |> fun lightNode -> new SCNNode ( Light = lightNode, Position = position )
    override this.ViewDidLoad () =
        let scene = new SCNScene ()
        let view = new SCNView (this.View.Frame, Scene = scene, AutoresizingMask = UIViewAutoresizing.All, AllowsCameraControl = true)
        new SCNCamera (XFov = 40.0, YFov = 40.0)
        |> fun c -> new SCNNode (Camera = c, Position = new SCNVector3(0.0F, 0.0F, 40.0F))
        |> scene.RootNode.AddChildNode
        let material = new SCNMaterial ()
        material.Diffuse.Contents <- UIImage.FromFile ("monkey.png")
        material.Specular.Contents <- UIColor.White
        new SCNNode( Geometry = SCNSphere.Create(10.0F), Position = new SCNVector3(0.0F, 0.0F, 0.0F) )
        |> fun node -> node.Geometry.FirstMaterial <- material; node
        |> scene.RootNode.AddChildNode
        new SCNLight ( LightType = SCNLightType.Ambient, Color = UIColor.Purple)
        |> fun lightNode -> new SCNNode ( Light = lightNode )
        |> scene.RootNode.AddChildNode
            ( UIColor.Blue, new SCNVector3 (-40.0F, 40.0F, 60.0F) );
            ( UIColor.Yellow, new SCNVector3 (20.0F, 20.0F, -70.0F) );
            ( UIColor.Red, new SCNVector3 (20.0F, -20.0F, 40.0F) );
            ( UIColor.Green, new SCNVector3 (20.0F, -40.0F, 70.0F) )
        |> Seq.map (fun (color, pos) -> CreateDiffuseLightNode(color, pos, SCNLightType.Omni))
        |> Seq.iter scene.RootNode.AddChildNode

You can read more about Scene Kit on the Xamarin blog.

Draw a PDF in Landscape with Core Graphics

Posted in iOS, Xamarin by mikebluestein on March 15, 2014

I just got a question from a Core Graphics presentation I gave a while back (from the first Xamarin Seminar) about how to use Core Graphics to render a PDF with 2 pages side-by-side in landscape. Since this question has come up a couple times in the past I figured I’d write a blog post about it.

The solution I use for this is to create a rectangle to display each page and then apply a transform to render the page within the rectangle. CGPDFPage has a handy GetDrawingTransform function that returns the transform. To get back a transform that crops the page to the rectangle while preserving the aspect ratio simply call:

CGAffineTransform transform = 
    pdfPage.GetDrawingTransform (CGPDFBox.Crop, pageRectangle, 0, true);

To do this for 2 pages, use the SaveState and RestoreState functions of the CGContext to get the transformation matrix back to its intial state, so that the transformation of the first page isn’t applied to the second page.

The following code shows how to implement this in a UIView subclass:

public override void Draw (RectangleF rect)
    base.Draw (rect);

    var rect1 = new RectangleF (0, 0, Bounds.Width / 2, Bounds.Height);
    var rect2 = new RectangleF (Bounds.Width / 2, 0, Bounds.Width / 2, Bounds.Height);
    using (CGContext gctx = UIGraphics.GetCurrentContext ()) {
        gctx.TranslateCTM (0, Bounds.Height);
        gctx.ScaleCTM (1, -1);

        gctx.SaveState ();

        using (CGPDFPage page = pdf.GetPage (page1)) {
            CGAffineTransform transform = 
                page.GetDrawingTransform (CGPDFBox.Crop, rect1, 0, true);
            gctx.ConcatCTM (transform);
            gctx.DrawPDFPage (page);

        gctx.RestoreState ();

        using (CGPDFPage page = pdf.GetPage (page2)) {
            CGAffineTransform transform = 
                page.GetDrawingTransform (CGPDFBox.Crop, rect2, 0, true);
            gctx.ConcatCTM (transform);
            gctx.DrawPDFPage (pdfPg);

This renders the PDF to the screen as shown below:


Use Nokia X HERE Maps with Xamarin.Android

Posted in Xamarin by mikebluestein on February 27, 2014

Earlier this week Nokia announced their new line of Nokia X Android phones. C# developers using Xamarin can target this platform via the Nokia components in the Xamarin Component Store.

Let’s take a look at using the Nokia HERE Maps API in a Xamarin.Android applcation.

Nokia HERE Maps have a wealth of features ranging from 3D landmarks, to street-level imagery and venue maps.


See the HERE Maps section of the Nokia developer site for more information on the entire feature set.

The first thing you need to do is set up the Nokia X Platform, which can be done via the Android SDK Manager. The following doc on the Nokia developer site explains how to do this:


Note, when you create a Nokia X emulator, be sure to set the target to Nokia X services (Nokia) – API Level 16 as shown below:


Once you have your environment set up, create a new Android project that targets API level 16. To use Nokia HERE Maps from Xamarin, simply add the Xamarin component:


The component brings everything you need directly into the project in either Visual Studio or Xamarin Studio. The sample projects included with the component show you how to get started.

Adding a Map

Basically, to include a map:

  1. Add your AppID and AppToken
  2. Set the required permissions
  3. Add a MapFragment
  4. Initialize the MapFragment
  5. Setup the map after the fragment has been initialized

AppID and AppToken

The AppID and AppToken can be set using attributes:

[assembly: MetaData("com.here.android.maps.appid", Value = "YourAppID")]
[assembly: MetaData("com.here.android.maps.apptoken", Value = "YourAppToken")]

Also, enable hardware-accelerated rendering:

[assembly: Application(HardwareAccelerated = true)]

Required Permissions

Next, the following required permissions need to be set in the Android manifest:

  • AccessFineLocation
  • AccessNetworkState
  • AccessWifiState
  • ChangeNetworkState
  • Internet
  • WriteExternalStorage


The Sample.HERE application included with the component adds the MapFragment in code via the FragmentManager:

fragment = new MapFragment ();
FragmentManager.BeginTransaction ()
  .Replace (Resource.Id.fragmentcontainer, fragment).Commit();

Additionally, you can add the MapFragment in the axml file, which is what I’ve done in this example:

Then in the Activity’s OnCreate method, retrieve the MapFragment and initialize it as follows:

mapFragment = FragmentManager.FindFragmentById (Resource.Id.mapfragment);
mapFragment.Init (this, this);

Accessing the Map Object

To get a reference to the map itself after the fragment initialization has completed, implement the IFragmentInitListener from the Nokia.Here.Mapping namespace, where you can access the map via the MapFragment’s Map property. Then you can call methods on the map such as SetCenter and SetZoomLevel:

public void OnFragmentInitializationCompleted (InitError error)
  if (error == InitError.None) {
    map = mapFragment.Map;

    double lat = 30.2652233534254;
    double lon = -97.73815460962083;

    map.SetCenter (MapFactory.CreateGeoCoordinate (lat, lon, 0.0), MapAnimation.None);
    map.SetZoomLevel (18.0, MapAnimation.None);

This displays a map in the application as shown below:


There are variety of map schemes that can be easily set via the MapScheme property. For example, setting map.MapScheme = MapScheme.SatelliteDay will show a map with daytime satellite imagery:


See Nokia Map Schemes documentation for the other schemes that are available.

As you can see, it’s pretty easy to get started. There are wealth of additional feature as well. For example, you can add a polygon to a map using the MapFactory class to create an IMapPolygon:

var geoPolygon = MapFactory.CreateGeoPolygon (new JavaList {
  MapFactory.CreateGeoCoordinate (30.2648461170005, -97.7381627734755),
  MapFactory.CreateGeoCoordinate (30.2648355402574, -97.7381750192576),
  MapFactory.CreateGeoCoordinate (30.2647791309417, -97.7379872505988),
  MapFactory.CreateGeoCoordinate (30.2654525150319, -97.7377341711021),
  MapFactory.CreateGeoCoordinate (30.2654807195004, -97.7377994819399),
  MapFactory.CreateGeoCoordinate (30.2655089239607, -97.7377994819399),
  MapFactory.CreateGeoCoordinate (30.2656428950368, -97.738346460207),
  MapFactory.CreateGeoCoordinate (30.2650364981811, -97.7385709662122),
  MapFactory.CreateGeoCoordinate (30.2650470749025, -97.7386199493406)

MapPolygon’s are one of many MapObjects. These are added to the map by calling AddMapObject:

map.AddMapObject (mapPolyline);

With this, we get an overlay of the specified coordinates:


You can download the sample code shown here from my github repo.

Tagged with: , ,

Creating Collection View Cells from a Xib

Posted in Uncategorized by mikebluestein on February 6, 2014

I’ve had the question of how to create a collection view cell using a xib file come up a few times, so I figured I would put together a quick example to show how to do it. In this case, I just created a collection view with 100 cells each containing a label:


Basically, you need to register the cell using the CollectionView.RegisterNibForCell method like this:

CollectionView.RegisterNibForCell (UINib.FromName ("CVCell", NSBundle.MainBundle),

There is a template file in Xamarin Studio you can use to create a collection view cell. This will create a xib to design the cell in, along with a class that is wired up to the xib. The template adds a bit of additional code but all you really need is the constructor that takes an IntPtr, as the class will be created by iOS via the call to DequeueReusableCell.

For example, here’s the code for the cell I’m using in this simple example:

public partial class CVCell : UICollectionViewCell
    public string Text {
            Label.Text = value;

    public CVCell (IntPtr handle) : base (handle)

The Text property simply sets the text on a UILabel that is added in Interface Builder.

The code to create the cell in the UIViewController is just like when you create the cell entirely in code:

public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath)
    var cell = (CVCell)collectionView.DequeueReusableCell (cellId, indexPath);

    cell.Text = indexPath.Row.ToString ();

    return cell;

The project is available in my github repo here.

Core Animation Resources for Xamarin.iOS Developers

Posted in iOS, Xamarin by mikebluestein on February 2, 2014

If you are an iOS developer, you owe it to yourself to try and learn the Core Animation framework because it isn’t just about animation. Core Animation makes much of what you see in iOS applications possible.

Here are some resources to get  you started:

Going through these resources will give an understanding of how the Core Animation framework is at the heart of iOS, which will help you to create experiences that differentiate your application.

Advanced Collection Views

Posted in iOS, Xamarin by mikebluestein on January 25, 2014
Tagged with: , ,

Get every new post delivered to your Inbox.