April 01, 2015 8:00 GMT

TypeScript Support in Xamarin Studio

Xamarin Studio and MonoDevelop now have support for TypeScript on Linux, Mac and Windows with an alpha release of the TypeScript Addin.

Editing TypeScript in Xamarin Studio on the Mac

The TypeScript addin uses V8.NET which is a library that allows a .NET application to host Google’s V8 JavaScript engine and have JavaScript interact with .NET objects in the host application.

The ability to support Windows, Mac and Linux would not have been possible without the work done by James Wilkins and Christian Bernasko. James Wilkins created the V8.NET library and when it was first released it supported only Windows. Christian Bernasko then took V8.NET and modified it to make it work with Mono on Linux and the Mac. The TypeScript addin is using V8.NET binaries built by Christian from his port of V8.NET.

Please note that this is an alpha release and because V8.NET uses a native library it can cause Xamarin Studio or MonoDevelop to terminate if a bug is encountered.


  • TypeScript compilation on save or build.
  • Code completion.
  • Find references.
  • Rename refactoring.
  • Go to declaration.
  • Errors highlighted as you type.
  • Code folding.

The addin supports:

  • Xamarin Studio MonoDevelop 5 and above.
  • TypeScript 1.4
  • Linux, Mac and Windows.

Installing the addin

The addin is currently available from MonoDevelop’s Add-in Repository in the alpha channel. By default the alpha repository is not enabled so you will have to enable it before you can find and install the addin.

In Xamarin Studio open the Add-in Manager and select the Gallery tab. Click the repository drop down and if Xamarin Studio Add-in Repository (Alpha Channel) is not displayed then click Manage Repositories…. In the window that opens tick the check box next to Xamarin Studio Add-in Repository (Alpha Channel) and then click the Close button.

Enabling alpha channel addins

Back in the Add-in Manager dialog click the Refresh button to update the list of addins. Use the search text box in the top right hand corner of the dialog to search for the addin by typing in TypeScript.

TypeScript addin selected in Addin Manager dialog

Select the TypeScript addin and then click the Install… button.

Note that if you are using Linux 32 bit then you should install the TypeScript Linux 32 bit addin. The other TypeScript addin listed supports Linux 64 bit. Hopefully in the future it will be possible to support both Linux 32 bit and 64 bit using the same addin.

Getting Started

Now that the TypeScript addin is installed let us create a TypeScript file.

To add a TypeScript file open the New File dialog, select the Web category and select Empty TypeScript file.

New File Dialog - New TypeScript File

Give the file a name and click the New button.

Note that currently the TypeScript file needs to be included in a project. Standalone TypeScript project files are not supported. TypeScript files can be added to any .NET project.

Code Completion

When editing the TypeScript code you will have code completion when you press the dot character.

TypeScript dot code completion

Code completion also works when you type the opening bracket of a function.

TypeScript method completion

Go to Declaration

The text editor’s right click menu has three TypeScript menus: Go to Declaration, Find References and Rename.

Text editor context menu with TypeScript menu options

The Go To Declaration menu option will open the corresponding definition in the text editor.

Find References

Find References will show the references in the Search Results window.

TypeScript references shown in Search Results window


Selecting the Rename menu option in the text editor will open the Rename dialog where you can type in a new name and click OK to have it updated.

TypeScript rename dialog

Note that currently on Linux the Rename dialog will only be displayed if the keyboard shortcut F2 is used. Selecting the context menu will not show the Rename dialog on Linux but will work on Windows and on the Mac.

Error Highlighting

Errors in your TypeScript code will be highlighted as you are typing in the text editor.

TypeScript errors highlighted in text editor

Code Folding

Code folding is supported for TypeScript classes, modules and interfaces.

TypeScript code folding

Code folding by default is disabled. To enable code folding open the Preferences dialog and in the Text Editor section select the General category, then tick the Enable code folding check box.

Preferences - Enabling code folding

Compiling to JavaScript

By default the TypeScript files will be compiled to JavaScript when the project is compiled.

There are more compiler options available in the project options in the Build – TypeScript category.

TypeScript compiler options for the project

On this page you can change when the compiler is run and what options are passed to the compiler when generating JavaScript code.

If an Output file is specified then all the TypeScript files will be compiled into a single JavaScript file. If an Output directory is specified then the JavaScript files will be generated in that directory instead of next to the TypeScript files.

That is the end of our quick look at TypeScript support in Xamarin Studio and MonoDevelop.

Source Code

The source code for the addin and for the V8.NET engine that works on Mono are available on GitHub.

April 01, 2015 5:36 GMT

Spring Forward with Xamarin Events in April

It’s no joke – there are TONS of Xamarin events happening this month! Here are just a few to spring you into gear!

April Xamarin Events

iTexico Webinar

  • Online: April 2nd, 9:00am PT
  • The Benefits of Native Multi-Platform Development with Alexandre Popp

Infragistics Webinar

  • Online: April 9th, 8:00am PT
  • Using Infragistics’ Cross-platform Native UI Controls with Xamarin.Forms & Mike James

DotNet Fringe us

  • Portland, OR: April 12th -14th
  • Power C# Robots and control them with C# Mobile Apps w/ James Montemagno

Today and Tomorrow us

  • San Diego, CA: April 15th -18th
  • Mobile Impact on Development & Testing w/ James Montemagno

Xamarin Gaia it

  • Milan, Italy: April 16th -17th
  • Cross-platform Development with Xamarin & Xamarin.Forms Overview w/ Mikes James

Gids.Net & Cloud in

  • Bangalore, India: Tuesday, April 21st
  • .NET Everywhere – Programming Wearables in C# w/ Nish Anil

Gids.Web in

  • Bangalore, India: Tuesday, April 22nd
  • Automated UI Testing using Xamarin Test Cloud & Calabash w/ Nish Anil

Developer Summit in

  • Bangalore, India: Tuesday, April 22nd
  • Go Mobile with C#, Visual Studio, and Xamarin w/ Mayur Tendulkar


The Events Forum has MANY MORE upcoming Xamarin events, meetups, and presentations happening this month near you, so check it out if you don’t see an event in your area here.

Interested in getting a developer group started? We’re here to help! Here’s a tips and tricks guide on staring a developer group, an introduction to Xamarin slide deck, and of course our community sponsorship program to get you on your way. Also, we love to hear from you, so feel free to send us an email or tweet @XamarinEvents to help spread the word and continue to grow the Xamarin community.

The post Spring Forward with Xamarin Events in April appeared first on Xamarin Blog.

April 01, 2015 3:39 GMT

Wearables Day

Hot buzzword of the day is Wearables. We at XHackers are ready to create a buzz. Lot of us when we hear the word - Wearables, we think of Apple Watch, Android Wear, Microsoft Band, Google Glass or even Fitbit. But history of wearables dates back to 1961!


In 1961, a MIT Professor, Edward Thorp, whom we call the Father of Wearables, created and successfully used a first wearable computer to cheat at Roulette which gave them 44% edge over the game :) Since then, we had calculator watches (how many of you remember Casio watches ;) ), digital hearing aids, Nike+, Go Pros, Fitbits and similar clones.

And then one day, Google announced "Project Glass" with a mission statement -

We think technology should work for you — to be there when you need it and get out of your way when you don’t.

It was exciting! With the annoucement of GDK(Glass Developer Kit), Android developers could write native Google glass apps using the Android SDK. This opened up plethora of opportunities for developers into the Wearable Computing market. Parallely, came slew of watches powered by Android called Android Wear. If you didn't know - Xamarin has been supporting Google Glass & Android Wears ever since. Some exciting news about new watches are making rounds.. watch out! (pun intended).

Microsoft too joined the party by annoucing a cool looking wrist band called Microsoft Band. To our surprise, it came in with full support on all the leading phone Operating Systems like iOS, Android along with it's very own Windows. With the release of Band SDK for all platforms and Xamarin's same day support, it's now seamless to integrate with iOS and Android apps. What we hear is, very soon Cortona which used to work only on Windows Phone, will now work on iOS and Android too - which will open up more avenues for apps to integrate voice in their apps.

Apple Watch was one of the most exciting annoucements from Apple! As you may know, WatchKit has been in preview for quite some time now. Recently after WatchKit's official release, and the actual Watch yet to hit the Apple stores, nothing stops developers to make their apps ready for the D-Day.

With Xamarin platform, it's now a reality for C# developers to write a cross platform code across all the major wearable platforms. Not just write code for Apple Watch, Google Glass, Android Wears, or Microsoft Band but also share a good amount of code among them.

So are you excited to learn how to build your wearable apps on all these platforms in C#?


Here's your opportunity to peek into the wearable app development world. Come and learn more about Xamarin and how to program for Wearables in our upcoming meetup.


What we plan to cover -

  • 09:45 AM - 10:15 AM : Quick introduction to Xamarin, Xamarin Forms - Pooran
  • 10:15 AM - 10:45 AM : Getting started with Microsoft Band -Vidyasagar
  • 10:45 AM - 11 AM : Break
  • 11 AM - 11:45 AM : Apple Watch concepts -Pooran
  • 11:45 AM - 12:30 PM : Android Wear concepts - Vidyasagar

See you there!

Blog Credits : Pooran

Xhackers Core Team

March 31, 2015 2:00 GMT

Live APAC Webinar: Say Hello to Xamarin.Forms

Photo of Nish AnilIn this live webinar, Xamarin Developer Evangelist Nish Anil will introduce you to Xamarin.Forms. You’ll learn how to use the Xamarin.Forms API to quickly build shared screens for iOS, Android, and Windows Phone, and about various Xamarin.Forms components, including Pages, Views, Layouts, and DependencyServices, and how to use them to create truly native cross-platform apps.

At the end of this session, you’ll be able to build Xamarin.Forms apps for iOS, Android, and Windows Phone.

Thursday, April 16
11:30 AM – 12:30 PM IST


All of the registrants for the webinar will receive a copy of the recording, so please feel free to register even if you won’t be able attend the day of the event.

The post Live APAC Webinar: Say Hello to Xamarin.Forms appeared first on Xamarin Blog.

March 31, 2015 12:00 GMT

Xamarin.Forms in Anger – Phoenix Peaks

I’m a sucker for a crisp, white description overlaid onto a smokey rectangle sitting on top of a beautiful photo. I don’t know what I like more, the subtle transparency or how the white text pops off the surface.

I’ve recreated this look a dozen times with CSS and HTML but not with Xamarin.Forms until this weekend. I think it came out pretty good. Do you like the picture? I took it on a walk near my house here in Phoenix. Yes, it’s a dry heat.

The Blueprint

The top half of this Xamarin.Forms Page uses an AbsoluteLayout with a mix of All and Proportional LayoutFlags. The trickiest part was getting the overlay BoxView positioned properly. I had to position the 1/3 tall BoxView completely off the bottom of the AbsoluteLayout. This forced the AbsoluteLayout to push the overlay onto the screen and stick it to the bottom of the layout.

Phoenix Peaks

The Code

The code is really simple, just add this code to a new Xamarin.Forms shared projects App constructor method and supply your best Ansel Adams like photo and you’re all set. Check out the order that I added the views to the AbsoluteLayout (peakLayout). Try changing the order and see what happens.

AbsoluteLayout peakLayout = new AbsoluteLayout {
	HeightRequest = 250,
	BackgroundColor = Color.Black

var title = new Label {
	Text = "South Mountain",
	FontSize = 30,
	FontFamily = "AvenirNext-DemiBold",
	TextColor = Color.White

var where = new Label { 
	Text = "Phoenix, AZ 85044",
	TextColor = Color.FromHex ("#ddd"),
	FontFamily = "AvenirNextCondensed-Medium" 

var image = new Image () {
	Source = ImageSource.FromFile ("southmountain.jpg"),
	Aspect = Aspect.AspectFill,

var overlay = new BoxView () {
	Color = Color.Black.MultiplyAlpha (.7f)

var pin = new Image () {
	Source = ImageSource.FromFile ("pin.png"),
	HeightRequest = 25,
	WidthRequest = 25

var description = new Frame () {
	Padding = new Thickness (10, 5),
	HasShadow = false,
	BackgroundColor = Color.Transparent,
	Content = new Label () {
		FontSize = 14,
		TextColor = Color.FromHex ("#ddd"),
		Text = "With close to 17,000 acres, South Mountain Park is the world's largest city park. It's one of the Phoenix icons like \"Camelback Mountain\" and \"Superstition Mountain\". From a distance, South Mountain looks like one big dead mountain, but those that hike it realize that it features some gorgeous scenery and great horizon views in all directions. South Mountain features some of the most popular urban hiking and biking trails in the city and also very enjoyable horseback riding. The mountain is 11 miles across and is home to more than 150 animal species and two mountain ranges including \"Ma Ha Range\" and \"Guadalupe Range\"."

AbsoluteLayout.SetLayoutFlags (overlay, AbsoluteLayoutFlags.All);
AbsoluteLayout.SetLayoutBounds (overlay, new Rectangle (0, 1, 1, 0.3));

AbsoluteLayout.SetLayoutFlags (image, AbsoluteLayoutFlags.All);
AbsoluteLayout.SetLayoutBounds (image, new Rectangle (0f, 0f, 1f, 1f));

AbsoluteLayout.SetLayoutFlags (title, AbsoluteLayoutFlags.PositionProportional);
AbsoluteLayout.SetLayoutBounds (title, 
	new Rectangle (0.1, 0.85, AbsoluteLayout.AutoSize, AbsoluteLayout.AutoSize)

AbsoluteLayout.SetLayoutFlags (where, AbsoluteLayoutFlags.PositionProportional);
AbsoluteLayout.SetLayoutBounds (where, 
	new Rectangle (0.1, 0.95, AbsoluteLayout.AutoSize, AbsoluteLayout.AutoSize)

AbsoluteLayout.SetLayoutFlags (pin, AbsoluteLayoutFlags.PositionProportional);
AbsoluteLayout.SetLayoutBounds (pin, 
	new Rectangle (0.95, 0.9, AbsoluteLayout.AutoSize, AbsoluteLayout.AutoSize)

peakLayout.Children.Add (image);
peakLayout.Children.Add (overlay);
peakLayout.Children.Add (title);
peakLayout.Children.Add (where);
peakLayout.Children.Add (pin);

var page = new ContentPage { Content = new StackLayout () {
		BackgroundColor = Color.FromHex ("#333"),
		Children = {

MainPage = page;

To tell you the truth, this is the first time I’ve used an AbsoluteLayout in Xamarin.Forms. The LayoutFlags and LayoutBounds are still confusing to me but you can’t deny the results.

The layering of the text and BoxView on top of the photo is what makes this UI look so good. The more I look, the more I see layered UI’s on Dribbble and Behanced. If you want the layered UI look, then use an AbsoluteLayout.

This may be the first time but it won’t be the last time you see AbsoluteLayout here on the blog. I hope you like the post and the code that comes with it. No Xaml yet, maybe soon.

PS. If you see a UI out in the wild and you’re not sure if Xamarin.Forms can handle it, send it my way and I’ll add it to the hit list.


The post Xamarin.Forms in Anger – Phoenix Peaks appeared first on Syntax is my UI.

March 31, 2015 6:20 GMT

The Linker - Mono's virtual 400 HP code chainsaw

One behind the scenes tool that most Xamarin newbies don't know nothing about is the linker. The linker gets called during the build of your assemblies. It has a single purpose and that is to reduce the size of your assembly. So how does it do that you say! It does it by firing up a digital, virtual, 400-HP chainsaw and cuts away the parts that your code doesn't use.

GREAT! How do I enable it?!

For iOS and Android the linker is enabled by default for projects that targets actual devices and disabled if you target emulators/simulators. The reason for this is to reduce build time when deploying to a simulator.

You can edit the linker settings under project properties; iOS build for iOS and Android options for Android. 

Anything else I should know

Yes, there are three levels of linking;
  • Link all assemblies which means that all code is subject for linking
  • Link SDK assemblies only which means that only Xamarin Core assemblies will be linked. Default for deploy to actual devices.
  • Dont link which means, well, don't link... Default for deploy to simulators/emulators.

Outstanding, why don't I use Link all all the time then!?

The first reason is that deploy time increases since linking takes time. So when deploying to the simulator or for your device while testing, it simply is not worth the extra time.

The other more important reason that should've been first is that the linker can be slightly evil. It can remove stuff that you meant to keep. Linking is carried out through static analysis of the code, so any classes that are instantiated through reflection and sometimes through IoC will not be detected and so they will be cut away. You can save the day by using the [Preserve] attribute to decorate classes and tell them to hide from the linker. If you're coding in a PCL that doesn't have the PreserveAttribute references you can just roll your own. Simply call it "PreserveAttribute" and the linker will see it. Think of it as garlic for linker vampires...

The third reason not to use link all is that this might affect any third party libraries that you have referenced that isn't "linker friendly".

So what's the summary of all this

Simply leave the linker as is and carry on with your life. Nothing to see here, circulate!


March 30, 2015 4:00 GMT

Creating Beautiful iOS Controls with PaintCode

Delivering a beautifully designed app can be the difference between having an app that gets used, or having an app that no one notices. Of course, having a beautiful app doesn’t just happen – creating something different often means creating your own custom controls, and creating beautiful custom controls on iOS can be a difficult task without intimate knowledge of CoreGraphics. This is where PaintCode steps in. PaintCode is a vector drawing app that generates C# code in real-time, allowing you to design your iOS controls and export the resulting “drawing code”. This is great because it allows you to create resolution-independent controls that will look great on any size of device.

From the beginning, the Xamarin Designer for iOS has supported real-time rendering of custom controls, which allows you to see instant feedback on your code changes. A number of developers have been opting to use images for control customization, which leads to a series of issues including bloating your app store binary size and that these images simply won’t scale properly on new screen sizes that Apple may release in the future.

PaintCode on Mac


PaintCode can generate a special class that contains all of the drawings, colors, gradients, shadows, and other design assets used in your app. In the following example, I’ve named the StyleKit DemoStyleKit. You’ll want to make sure you’re regularly exporting the StyleKit from PaintCode into your Xamarin project in order for changes to be made available to you in your project. Exporting your style sheet will create a .cs style and copy any images your styles use into the directory of your choice. Once you’ve done this, you’ll need to add these to your existing Xamarin.iOS project.

Creating a custom control

Once you’ve added the exported files, you’re ready to consume the drawing code in a custom control. You will need to create a new class which will be your custom control; in this sample I’ve called it ‘MyTimerView’ and it inherits from UIView.

It’s here where we’ll consume the auto-generated C# from PaintCode and set it up to support the Storyboard designer. In this example, I annotate the class with the DesignTimeVisible attribute. This tells our iOS Storyboard designer that I wish to use this class within the Storyboard designer. A basic class with Storyboard support should look something like this:

[Register("MyTimerView"), DesignTimeVisible(true)]
public class MyTimerView : UIView
  public MyTimerView(IntPtr p) : base(p)
    Initialize ();
  public MyTimerView ()
   Initialize ();
  void Initialize ()
  public override void Draw(CoreGraphics.CGRect rect)

Because PaintCode exports the drawing code into the StyleKit, we can implement the drawing with just one line of code!

public override void Draw(CoreGraphics.CGRect rect)
  DemoStyleKit.DrawTimer(rect, Angle);

If you save and build the project now and open your Storyboard, you should find MyTimerView within the control toolbox. You can drag and drop this into your view and instantly see how it looks.

A custom control in the iOS storyboard designerAdvanced properties

It would be great to be able to control the angle of the green progress line from the Properties panel within our IDE. Fortunately, custom controls allow for design time properties for a number of types, including string, bool, SizeF, UIColor, and UIImage. To add an angle property to our properties pad, let’s add the following to our class:

float angle;
[Export("Angle"), Browsable(true)]
public float Angle
  get { return angle; }
    angle = value;
    SetNeedsDisplay ();

It’s also worth ensuring that the _angle property has an initial value by setting it in the Initialize method. Once you’ve done this, you’ll see a new property available to you and the changes to the value will automatically be updated in the custom control. This allows you to create very customizable controls without needing to drop into code to make tweaks.

Learn more

You can learn more about PaintCode on their website and purchase the app from the Mac App Store.

To get started, download the sample project from this blog post from GitHub.

The post Creating Beautiful iOS Controls with PaintCode appeared first on Xamarin Blog.

March 30, 2015 1:30 GMT

Episode 25: Performance Comparisons: Part Two with Harry Cheung

Performance is a huge and important topic, so one episode just wasn’t enough. In this episode we talk to Harry Cheung about the performance tests he’s been running to see just how all these different mobile app development approaches perform when it comes to raw computation.

Hosts: Greg Shackles, Jon Dick

Guest: Harry Cheung


Thanks to our Sponsors!


Raygun.io – Exceptional Error Tracking Raygun.io is the fastest and easiest way to track your application’s errors and get the level of detail you need to fix crashes quickly. Notifications are delivered right to your inbox and presented on a beautiful dashboard.

March 30, 2015 12:00 GMT

My 3 Favorite Xamarin Studio Add-ins

Xamarin Studio, like all good IDE’s, has an extensibility model. One of those extensibility points is through Add-ins. Add-ins allow third party developers to extend and enhance Xamarin Studio with things like version control options, languages and utilities.

I was recently reminded about the add-ins by Glen Stephens, a Xamarin University trainer on Twitter.

Addin Tweet

Xamarin Studio Add-ins

To add a new Add-in to your IDE, just head on over to the Xamarin Studio main menu and click on “Add-in Manager”.

Xamarin Studio Add-ins Manager

When you click the menu item the Add-in manager will appear. Click on the Gallery tab to view the different Add-ins built by Xamarin and the community.

Xamarin Studio Add-ins Manager dialog

My 3 Favorite Add-ins

My three favorite Add-ins to Xamarin Studio in no particular order are: the Android Signature Tool, Show in GitHub and the Image Multiplier. These three Add-ins extend Xamarin Studio with some neat features.

Android Signature Tool

If you have ever used the Maps component in Android, this Add-in will come in handy. The Add-in runs the Android keytool command line commands and puts a nice GUI user interface on it. The SHA1 is what you’ll need for the Google Maps API.

Here you can see it will default to the DEBUG keystore but you can select a production keystore and do the same thing. The Add-in is available right off the Tool menu.

Addin Android Key

Show in Github

I’m a big fan of GitHub and love using Git. This Add-in will open a browser onto the same file and line on GitHub. Very useful, especially for working on open source projects. The Add-in is available on the files right click menu.

Addin Show in GitHubImage Multiplier

Image Multiplier is my favorite Xamarin Studio Add-in. Image Multiplier makes icons from SVG files. Sounds simple enough, right!

From a single SVG file, ImageMultiplier can create the 3 icon sizes for iOS, the 4 icon sizes for Android and put them in the correct directories. If the design changes, which I do a lot, ImageMultiplier will regenerate the icons automatically. It will also create the 10 App icons sizes as well.

Addin Image Multiplier

Stay tuned for a post on ImageMultiplier in the near future. I did notice the current version has an issue with the root directory for the Android project. Xamarin has change the root name from Android to Droid. Don’t worry; I have already sent a pull request to the maintainer updating the template.

There are some great docs here and here about how to create Add-ins to Xamarin Studio. Theres even an Add-in to help make Add-ins. How meta is that!

I hope you take a look through the Add-in gallery. These three are my favorites. What add-ins do you use in Xamarin Studio? Let me know in the comments.

There’s more where that came from

Stay in the loop with the Syntax Newsletter packed with tips and tricks and the freshest updates - straight to your inbox.

Newsletter subscribers get access to my free training courses first and receive discounts to paid training courses during the opening week.

Sign Up for the Syntax Newsletter

The post My 3 Favorite Xamarin Studio Add-ins appeared first on Syntax is my UI.

March 30, 2015 8:44 GMT

Connecting to Android Player using VS and Parallels

This is a short guide for how to connect to Android Player in case you're using Visual Studio in Windows through Parallels. I use to do this in a way more complicated manor before I realized that it's just this simple. Looking ahead, In VS 2015, Microsofts gives us an x86/hyper-V Android emulator that looks great. But for now, this works the best.

Start your engines

Fire up Android Player (or any other emulator of your choice that runs Android) in OS X and get the address to the emulator. Click on the settings cog and note the IP Address.

Connect to the emulator

In Windows, open your project in Visual Studio and hit Tools -> Android -> Android Adb Command Prompt. Write adb connect [the IP address] and you should then be connected to your emulator like in the image below.

Run your project

You should now see your device in Visual Studio!


Of course, things can go wrong. The issues I've encountered are these.

1) I had to disable my wireless network while connected to the local wired network. Surely this is a configuration issue that I just haven't bothered with yet.

2) The emulator doesn't show up. Restart Visual Studio.

3) You have to reconnect each time your Mac goes to sleep...

4) Firewalls... Make sure port 5555 is open for TCP from Windows to OS X.

March 29, 2015 4:18 GMT

Macbook Pro Retina 16GB/512GB For Sale

15.4-inch MacBook Pro 2.3GHz Quad-core Intel i7 with Retina Display

16GB of memory and 512GB Flash drive. mac4sale

It is one year old, in excellent condition and has 2 years left on AppleCare.

Cost me $3200, asking $1600.

Email to jesseliberty@gmail.com or  339-201-6010



[Reason for sale, acquisition of another MacBook Pro, A Macbook Air and a MacPro. I gotta’ sell this or my wife will kill me. Save a life, call me.]

March 27, 2015 8:21 GMT

Contest: What’s Beggin’ for a Beacon?

Yesterday, we put the spotlight on our beacons partners and today we’re inviting you to put on your creativity hat and dive into the world of context.

What are Beacons?

Beacons are small pieces of hardware that use Bluetooth technology to transmit signals to mobile devices, allowing developers to create context-aware apps. Our Component Store partners make it easy to build apps that detect beacon signals and can act accordingly, sending push notifications, coupons, or other information to a central database.


The bottom line: beacon potential is everywhere, from simple life productivity hacks to innovative business improvements. Share a picture, video, or brief description of something you think should be beacon-enabled – however practical or impractical – and we’ll award prizes to our favorite ideas.

How to Enter:

  • Submit your idea, including why it’s “beggin’ for a Beacon,” using a written description, video, and/or photos
  • Tweet your idea to @xamarinHQ with the hashtag #BeaconPotential
  • Bonus points: link to your blog about your Beacon idea for the contest!

Example Tweet:

Always losin’ Fido. @XamarinHQ #BeaconPotential
Whiskey, Xamarin Office Dog


Most Creative Idea wins a Xamarin + Beacons extravaganza!

  • BKON hardware
  • MobStac swag and Rasberry Pi 2 kits
  • Estimotes beacon devkit & assorted swag
  • Xamarin swag

Real Potential

Do you have the next Fido finder app in the works? We’re on the lookout for submissions that have real potential! One submission will be eligible for a special prize from our beacons partners.

Special Prize:

Special prize for one lucky contestant whose submission has the most real-world applicability: our beacons partners are offering a 1:1 mentorship session to share their expertise. They will guide you through best practices for context-aware apps to help get your app off the ground – and provide beacon hardware to get you up and running.

Rules and Regulations:

All entries must be submitted by April 6th at 12pm EST. A valid entry is a tweet that highlights a unique, creative and useful Beacon use case and includes both @xamarinhq and the hashtag #BeaconPotential. We will review and evaluate your submissions based on a variety of factors, including creativity and number of likes, retweets, and shares. Contestants should follow @XamarinHQ to enable us to DM you for private follow-up if you win a prize. This contests is open to individuals and there is no purchase necessary to enter.

The post Contest: What’s Beggin’ for a Beacon? appeared first on Xamarin Blog.

March 27, 2015 6:03 GMT

Win an Apple Watch Contest Winner!

A couple of weeks ago we invited you to start creating your first WatchKit app using the Xamarin Storyboard designer for a chance to win an Apple Watch. With all of the excitement around this cool new device, we weren’t surprised when we got a ton of great submissions!

With a lot of thought and tough decision making, we’re pleased to announce that the winner of the contest is:

Car Parking App!

A huge thank you for all of the wonderful submissions; it was a truly difficult choice to pick just one. For more Apple Watch inspiration, check out this forum to see other examples from the contest!

The post Win an Apple Watch Contest Winner! appeared first on Xamarin Blog.

March 27, 2015 2:04 GMT

Weekly Xamarin Newsletter Issue #33

First Look at the Prism for Xamarin.Forms Preview
Brian Lagunas, announces that Microsoft has open-sourced Prism and it’s coming to Xamarin.Forms.

NControl – Cross Platform Custom Controls for Xamarin.Forms
Christian F released NControl, a library enabling developers to create custom controls.

Xamarin: Xamarin Webinar Featuring Gartner: The Next 20 Million Apps
Jo Ann Buckner, from Xamarin Inc., invites you to register now for the April 9th webinar with Featured Analyst firm Gartner.

Xamarin.Forms Slider View Recipe
I (Adam) add another recipe to the Xamarin.Forms Cookbook.

Xamarin Tech Partner Update: Spotlight on iBeacons
Joseph Hill, from Xamarin Inc, highlights the Xamarin beacon partners.

Building Context-Aware Apps with Beacons
Greg Shackles is on .Net Rocks again this time talking about context aware apps and beacons.

Decoupling Views In Multi-Screen Sequences
Adam Kemp gets more in depth on the topic of decoupling views.

Add Storage to Your Apps with Office 365
Mayur Tendulkar, from Xamarin Inc., adds storage to a mobile app with OneDrive syncing.

Xamarin.Forms Fonts for iOS and Android
I (Adam) wrote this article for myself. No more searching for fonts!

Get started with Xamarin.Forms for WinRT
Daniel Hindrikes shows off the new Xamarin support for WinRT.

Android Tips: Immersive Panoramic Google Maps
James Montemagno, from Xamarin Inc., takes a step into full immersive  experience on mobile.

Gone Mobile 24: Cross Platform Performance Comparisons with Kevin Ford
Greg Shackles and his guest Kevin Ford talk performance of different mobile frameworks.

Starting with Microsoft Band and Xamarin
Kevin Ford makes the tough choice to play with the Microsoft band.

Solving the “Event not found” issue in Xamarin #MVVMLight binding and commanding
Laurent Bugnion, from GalaSoft, fixes a thorny issue with the Xamarin Linker.

Application wide resources (reloaded)
Corrado Cavalli revisits his resource and modernizes them.

Authenticating with Touch ID and the iPhone pin
Nic Wise is in love with the Touch ID sensor and wants it in his apps.

Building Apple Watch Apps using Xamarin. Our development experiment
Lee Mallon has been experimenting with the Apple Watch and has some advice for you.


Don't miss out! Subscribe Today

Do you blog about Xamarin? Get your blog in the newsletter. Email me at adam [at] adamjwolf.com.

The post Weekly Xamarin Newsletter Issue #33 appeared first on Syntax is my UI.

March 26, 2015 5:19 GMT

Xamarin Webinar Featuring Gartner: The Next 20 Million Apps

Gartner logoIn the near future, nearly every transaction and interaction will need to have a mobile surface, and millions of new apps will be required over the next few years to really achieve the promise of enterprise mobility to transform customer relationships and business processes.

How will the enterprise achieve this? Through scalable ways to build, test, integrate, and manage apps across a diverse and dynamic device landscape that is quickly moving beyond smartphones and tablets to wearables and M2M computing.

To help mobile leaders navigate this next phase of mobility, we invite you to register now for our April 9th webinar with Analyst firm Gartner, featuring Richard Marshall, Research Director of Enterprise Mobility at Gartner, and Xamarin’s Director of Enterprise Mobility, Steve Hall.

Register Now

About the Speakers

Richard Marshall, GartnerRichard M. Marshall is a Research Director in the Mobile and Client Computing group, focusing on enterprise mobility and especially mobile apps and mobile app development.He has experience across a wide range of software industry skills, from coding to corporate governance. This includes all phases of product development from initial concept through implementation and on to sales, product management and marketing. He is an inventor of software technology and has lectured and written papers, articles and reports for many years. Mr. Marshall has held a variety of leadership roles, including CTO, VP of Engineering and CEO. He has had extensive success in raising capital from angel and institutional investors.
Steve HallSteve Hall works with Xamarin’s enterprise customers providing guidance and best practices for implementing mission-critical mobile solutions in an enterprise setting. He has over fifteen years of mobile experience that covers enterprise mobile architecture, security, and development. In the span of his career, Steve has also designed secure mobile solutions for large enterprises, consumer applications, and government agencies.

The post Xamarin Webinar Featuring Gartner: The Next 20 Million Apps appeared first on Xamarin Blog.

March 26, 2015 2:00 GMT

Xamarin Tech Partner Update: Spotlight on iBeacons

We’ve been busy growing our mobile ecosystem over the past year, and the Xamarin Component Store now features over 300 components that allow developers to easily integrate new functionality into their apps. Features ranging from cloud services and backend systems integration to charts, graphs, and datagrids can be added with just a few lines of code. Today, we’re excited to highlight our beacons partners BKON, Estimote, and MobStac.

These partnerships give Xamarin developers the power to detect beacons with simple integrations, expanding on our mission to make it fast, easy, and fun to build great mobile apps.
Estimote LogoIn mobile, context is king, and Estimote, MobStac, and BKON allow developers to build context-aware apps using micro-location data to send information to the users’ device. Beacons can be used to improve customer relationships by sending relevant information instead of “spam” ads, to drive increased revenue for businesses by informing shop associates when customers are interested in objects, and to speed transactions with automatic check-in.
Mobstac LogoBeaconstac by MobStac is a hardware-agnostic cloud service, allowing developers to use any beacon vendor of choice, including Estimote, to tap into MobStac’s robust content management, reporting, and analytics capabilities. With MobStac, users can use iBeacon data to detect high-traffic retail areas, to target specific users based on CRM data, or to push certain product catalog information based on in-store location.
BKON LogoBKON and Estimote provide both beacon hardware and Xamarin Components to detect beacon transmissions. BKON offers two beacon hardware variants, as well as security and management for deployed beacons, giving customers the ability to detect battery levels, set passwords, and more. With Estimote and Estimote Stickers, beacons become even more portable. Users attach a beacon to objects, allowing any device or item to become a “nearable”: a mini smart-machine, broadcasting data to devices in range. This takes contextual targeting even further, allowing, for example, sales associates to be alerted when a customer engages with an item or museum curators to adjust exhibit displays based on visitor interaction.

Our partnerships with Estimote, MobStac, and BKON make building native, context-aware apps simple, allowing your customers to remain relevant, gain competitive advantage, deliver better user experiences, drive additional purchases, and leverage user behavior to identify areas for growth.

Get started with BKON, Beaconstac by MobStac, and Estimote (iOS and Android) today.

The post Xamarin Tech Partner Update: Spotlight on iBeacons appeared first on Xamarin Blog.

March 26, 2015 11:56 GMT

Building Context-Aware Apps with Beacons

Recently I've been giving some talks on building context-aware apps with beacons, so I just wanted to quickly publish my content around that in one place. If it's not immediately obvious, I think beacons and context-based technologies are seriously awesome.

.NET Rocks!

First, Carl and Richard were nice enough to invite me back on .NET Rocks! to talk about this stuff as well. You can find that episode over on their site, or in any of the usual places you subscribe to podcasts.

Here are the slides from my talk at my NYC Mobile .NET Developers Group:

The sample app used as part of that talk can be found on my GitHub page, which is a super basic scavenger hunt type app for iOS and Android.

Hopefully some of this helps inspire you to try out this stuff if you haven't already, and start building awesome apps!

March 25, 2015 2:30 GMT

Add Storage to Your Apps with Office 365

Enterprises with a Bring Your Own Device (BYOD) strategy face the challenge of securing their resources on various types of devices. For example, organizations want to share documents with their employees, allow them to collaborate on documents with coworkers, and more. Employees want to sync these documents with a variety of devices, such as tablets, laptops and mobile phones, with a seamless search experience. These challenges can be tackled by using OneDrive for Business, which is part of Office 365.

Xamarin developers can use OneDrive for Business in their iOS and Android apps to download, open, edit, and upload files in Office 365 (O365). In this post, we’ll build a simple Xamarin.Android app that can connect to OneDrive for Business to show a list of files.

Note 1: To build apps that can connect to Office 365, you’ll need an active subscription. Also, to follow the steps manually as mentioned in this blog, you’ll need to access the O365 associated Active Directory.

Note 2: The APIs, libraries, sample code and registration process are currently in preview. This blog post is intended to show the possibilities of using O365 with Xamarin.

Step 1: Register the app

As we’ve seen before, Office 365 uses Azure Active Directory (AD) as the Identity Provider. Which means that Azure Active Directory is used to authenticate and authorize users. To allow OneDrive to be accessed from mobile apps, it is mandatory to register this app in AD. You can follow our guide to registering an app with Active Directory to learn how.

Step 2: Give access to the O365 APIs

On the Configure tab, click the Add Application button at the bottom.


On next screen, select Office 365 SharePoint Online to access the Files and Lists.


Once these services are selected, give access to the tasks that a user can perform with the app on the next screen.


Now we can Save this configuration and focus on the mobile part of our app.

Step 3: Build mobile app

Step 3a: Refer NuGet packages

In order to use O365 services in your Xamarin app, you will need to add the following NuGet packages to your project.

  • Azure Active Directory Authentication Library (ADAL) – v3.0.11xx (Preview/Alpha)
  • Microsoft Office 365 My Files Library for .NET – v1.0.22 (Stable)
  • Microsoft Office 365 Discovery Library for .NET – v1.0.22 (Stable)

Step 3b: Declare variables

Add a new class to your project and name it AuthenticationHelper. Declare the variable at class and global level as outlined below:

public static readonly string DiscoveryServiceResourceId = "https://api.office.com/discovery/";
public const string Authority = "https://login.windows.net/common";
public static readonly Uri DiscoveryServiceEndpointUri =
new Uri("https://api.office.com/discovery/v1.0/me/");
public static Uri returnUri = new Uri("http://Xam-O365-Integration");
public static string clientId = "32088804-9284-451f-9ee6-2b70507a99cf";
public static AuthenticationContext authContext = null;

Step 3c: Write method to acquire AccessToken

Using ADAL, this app will fetch the Access Token from AD, as shown below. In this method, the second parameter will depend on the platform on which the code is executing. For example, in Android an Activity is passed, but on iOS and Windows Phone the second parameter is not required.

public static async Task<AuthenticationResult> GetAccessToken (string serviceResourceId, Activity activity)
   authContext = new AuthenticationContext(Authority);
   if (authContext.TokenCache.ReadItems().Count() > 0)
      authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);
      var authResult = await authContext.AcquireTokenAsync(serviceResourceId, clientId, returnUri, new AuthorizationParameters(activity));
   return authResult;

Step 3d: Create DiscoveryClient

Discovery Service helps find Service Endpoints. Create a new method GetDocumentsList(), which will create DiscoveryClient for further use.

List<string> fileNames = new List<string>();
DiscoveryClient discoveryClient = new DiscoveryClient(
async () =>
var authResult = await AuthenticationHelper.GetAccessToken(AuthenticationHelper.DiscoveryServiceResourceId, this);
return authResult.AccessToken; });
var appCapabilities = await discoveryClient.DiscoverCapabilitiesAsync();
var myFilesCapability = appCapabilities.Where(s => s.Key == "MyFiles")
    .Select(p =>; new { Key = p.Key,
    ServiceResourceId = p.Value.ServiceResourceId,
    ServiceEndPointUri = p.Value.ServiceEndpointUri })

Step 3e: Create SharePointClient

Files in OneDrive or Lists from SharePoint in O365 can be accessed using SharePointClient. This object again encapsulates REST services provided by O365.

if (myFilesCapability != null)
SharePointClient myFilesClient = new SharePointClient(myFilesCapability.ServiceEndPointUri,
async () =>
var authResult = await AuthenticationHelper.GetAccessToken(myFilesCapability.ServiceResourceId, this);
 return authResult.AccessToken;
var myFilesResult = await myFilesClient.Files.ExecuteAsync();
var myFiles = myFilesResult.CurrentPage;
foreach (var myFile in myFiles)
myFilesResult = await myFilesResult.GetNextPageAsync();
} while (myFilesResult != null);

Step 3f: List files

By default, MainActivity is derived from Activity. Change this behavior to derive from ListActivity to display a list in the app.

Just after the above code, create an adapter and use it to show the list of documents.

this.ListAdapter = new ArrayAdapter(this,

Last, call this ‘fat’ GetDocumentsList method from the OnCreate method and run the app. It should show the following result, listing files from your OneDrive account.


Now you’ve got a fantastic foundation to build multi-tenant, intranet, integrated mobile apps using Office 365. Office 365 has a huge number of features which we’ll be highlighting in future guides and samples apps.

If you’re interested in exploring a sample project, you can download a copy of the source code from this blog post on GitHub and discuss this topic in forums.




The post Add Storage to Your Apps with Office 365 appeared first on Xamarin Blog.

March 25, 2015 12:00 GMT

Xamarin.Forms Fonts for iOS and Android

 Have you ever tried searching for a font list for Xamarin.Forms? Well I have and let me tell you, it’s crickets and tumbleweeds out there.

Every time I try to build an app I struggle to match the family, size and color of fonts. The numerous restarts of the debugger and the never ending fiddling with size and font attributes drives me crazy. And don’t get me started with Android. You wonder why I talk about “Xamarin.Forms in Anger”, now you know!

Xamarin.Forms Fonts App

The Font app (sample code included) helps me select the correct font for iOS and Android. Each font is displayed and you can change the font size, text color and background color to match any design without restarting the app. Yay! Future additions will allow you to change the text used to display the font.

Xamarin.Forms Fonts iOS
Xamarin.Forms Fonts Android

Xamarin.Forms Fonts for iOS

Here is a quick list of available fonts for the iOS operating system. This list was taken off the iOSFonts.com website

  • AcademyEngravedLetPlain
  • AlNile-Bold
  • AlNile
  • AmericanTypewriter
  • AmericanTypewriter-Bold
  • AmericanTypewriter-Condensed
  • AmericanTypewriter-CondensedBold
  • AmericanTypewriter-CondensedLight
  • AmericanTypewriter-Light
  • AppleColorEmoji
  • AppleSDGothicNeo-Thin
  • AppleSDGothicNeo-Light
  • AppleSDGothicNeo-Regular
  • AppleSDGothicNeo-Medium
  • AppleSDGothicNeo-SemiBold
  • AppleSDGothicNeo-Bold
  • AppleSDGothicNeo-Medium
  • ArialMT
  • Arial-BoldItalicMT
  • Arial-BoldMT
  • Arial-ItalicMT
  • ArialHebrew
  • ArialHebrew-Bold
  • ArialHebrew-Light
  • ArialRoundedMTBold
  • Avenir-Black
  • Avenir-BlackOblique
  • Avenir-Book
  • Avenir-BookOblique
  • Avenir-Heavy
  • Avenir-HeavyOblique
  • Avenir-Light
  • Avenir-LightOblique
  • Avenir-Medium
  • Avenir-MediumOblique
  • Avenir-Oblique
  • Avenir-Roman
  • AvenirNext-Bold
  • AvenirNext-BoldItalic
  • AvenirNext-DemiBold
  • AvenirNext-DemiBoldItalic
  • AvenirNext-Heavy
  • AvenirNext-HeavyItalic
  • AvenirNext-Italic
  • AvenirNext-Medium
  • AvenirNext-MediumItalic
  • AvenirNext-Regular
  • AvenirNext-UltraLight
  • AvenirNext-UltraLightItalic
  • AvenirNextCondensed-Bold
  • AvenirNextCondensed-BoldItalic
  • AvenirNextCondensed-DemiBold
  • AvenirNextCondensed-DemiBoldItalic
  • AvenirNextCondensed-Heavy
  • AvenirNextCondensed-HeavyItalic
  • AvenirNextCondensed-Italic
  • AvenirNextCondensed-Medium
  • AvenirNextCondensed-MediumItalic
  • AvenirNextCondensed-Regular
  • AvenirNextCondensed-UltraLight
  • AvenirNextCondensed-UltraLightItalic
  • BanglaSangamMN
  • BanglaSangamMN-Bold
  • Baskerville
  • Baskerville-Bold
  • Baskerville-BoldItalic
  • Baskerville-Italic
  • Baskerville-SemiBold
  • Baskerville-SemiBoldItalic
  • BodoniOrnamentsITCTT
  • BodoniSvtyTwoITCTT-Bold
  • BodoniSvtyTwoITCTT-Book
  • BodoniSvtyTwoITCTT-BookIta
  • BodoniSvtyTwoOSITCTT-Bold
  • BodoniSvtyTwoOSITCTT-Book
  • BodoniSvtyTwoOSITCTT-BookIt
  • BodoniSvtyTwoSCITCTT-Book
  • BradleyHandITCTT-Bold
  • ChalkboardSE-Bold
  • ChalkboardSE-Light
  • ChalkboardSE-Regular
  • Chalkduster
  • Chalkduster
  • Cochin
  • Cochin-Bold
  • Cochin-BoldItalic
  • Cochin-Italic
  • Copperplate
  • Copperplate-Bold
  • Copperplate-Light
  • Courier
  • Courier-Bold
  • Courier-BoldOblique
  • Courier-Oblique
  • CourierNewPS-BoldItalicMT
  • CourierNewPS-BoldMT
  • CourierNewPS-ItalicMTCourierNewPSMT
  • DBLCDTempBlack
  • DINAlternate-Bold
  • DINCondensed-Bold
  • DamascusBold
  • DamascusLight
  • DamascusMedium
  • DamascusSemiBold
  • DevanagariSangamMN
  • DevanagariSangamMN-Bold
  • Didot
  • Didot-Bold
  • Didot-Italic
  • DiwanMishafi
  • EuphemiaUCAS
  • EuphemiaUCAS-Bold
  • EuphemiaUCAS-Italic
  • Farah
  • Futura-CondensedExtraBold
  • Futura-CondensedMedium
  • Futura-Medium
  • Futura-MediumItalic
  • GeezaPro
  • GeezaPro-Bold
  • Georgia
  • Georgia-Bold
  • Georgia-BoldItalic
  • Georgia-Italic
  • GillSans
  • GillSans-Bold
  • GillSans-BoldItalic
  • GillSans-Italic
  • GillSans-Light
  • GillSans-LightItalic
  • GujaratiSangamMN
  • GujaratiSangamMN-Bold
  • GurmukhiMN
  • GurmukhiMN-Bold
  • STHeitiSC-Light
  • STHeitiSC-Medium
  • STHeitiTC-Light
  • STHeitiTC-Medium
  • Helvetica
  • Helvetica-Bold
  • Helvetica-BoldOblique
  • Helvetica-Light
  • Helvetica-LightOblique
  • Helvetica-Oblique
  • HelveticaNeue
  • HelveticaNeue-Bold
  • HelveticaNeue-BoldItalic
  • HelveticaNeue-CondensedBlack
  • HelveticaNeue-CondensedBold
  • HelveticaNeue-Italic
  • HelveticaNeue-Light
  • HelveticaNeue-LightItalic
  • HelveticaNeue-Medium
  • HelveticaNeue-MediumItalic
  • HelveticaNeue-UltraLight
  • HelveticaNeue-UltraLightItalic
  • HelveticaNeue-Thin
  • HelveticaNeue-ThinItalic
  • HoeflerText-Black
  • HoeflerText-BlackItalic
  • HoeflerText-Italic
  • HoeflerText-Regular
  • IowanOldStyle-Bold
  • IowanOldStyle-BoldItalic
  • IowanOldStyle-Italic
  • IowanOldStyle-RomanKailasa
  • Kailasa-Bold
  • KannadaSangamMN
  • annadaSangamMN-Bold
  • KhmerSangamMN
  • KohinoorDevanagari
  • KohinoorDevanagari-Book
  • KohinoorDevanagari-Light
  • KohinoorDevanagari-Medium
  • LaoSangamMN
  • MalayalamSangamMN
  • MalayalamSangamMN-Bold
  • Marion
  • Marion-Bold
  • Marion-Italic
  • Marion-Regular
  • Menlo
  • Menlo-BoldItalic
  • Menlo-Regular
  • Menlo-Bold
  • Menlo-Italic
  • MarkerFelt-Thin
  • MarkerFelt-Wide
  • Noteworthy
  • Noteworthy-Bold
  • Noteworthy-Light
  • Optima
  • Optima-Bold
  • Optima-BoldItalic
  • Optima-ExtraBlack
  • Optima-Italic
  • Optima-Regular
  • OriyaSangamMN
  • OriyaSangamMN-Bold
  • Palatino
  • Palatino-Bold
  • Palatino-BoldItalic
  • Palatino-Italic
  • Palatino-Roman
  • Papyrus
  • Papyrus-Condensed
  • PartyLetPlain
  • SavoyeLetPlain
  • SinhalaSangamMN
  • SinhalaSangamMN-Bod
  • SnellRoundhand
  • SnellRoundhand-Black
  • SnellRoundhand-Bold
  • Superclarendon
  • Superclarendon-Regular
  • Superclarendon-BoldItalic
  • Superclarendon-Light
  • Superclarendon-BlackItalic
  • Superclarendon-Italic
  • Superclarendon-LightItalic
  • Superclarendon-Bold
  • Superclarendon-Black
  • Symbol
  • TamilSangamMN
  • TamilSangamMN
  • TamilSangamMN-Bold
  • TeluguSangamMN
  • TeluguSangamMN
  • TeluguSangamMN-Bold
  • Thonburi
  • Thonburi-Bold
  • Thonburi-Light
  • TimesNewRomanPS-BoldItalicMT
  • TimesNewRomanPS-BoldMT
  • TimesNewRomanPS-ItalicMT
  • TimesNewRomanPSMT
  • Trebuchet-BoldItalic
  • TrebuchetMS
  • TrebuchetMS-Bold
  • TrebuchetMS-Italic
  • Verdana
  • Verdana-Bold
  • Verdana-BoldItalic
  • Verdana-Italic
  • ZapfDingbats
  • ZapfDingbatsITC
  • Zapfino

Xamarin.Forms Fonts for Android

Now for Android, our selection is somewhat limited. Could this be all the fonts available on Android? I hope not. It’s all that I could find. If you know of more, please tell me and I will update this list.

  • sans-serif
  • sans-serif bold
  • sans-serif italic
  • sans-serif bold italic
  • sans-serif-light
  • sans-serif-light italic
  • sans-serif-thin
  • sans-serif-thin italic
  • sans-serif-condensed
  • sans-serif-condensed bold
  • sans-serif-condensed italic
  • sans-serif-condensed bold italic
  • sans-serif-medium
  • sans-serif-medium italic
  • sans-serif-black
  • sans-serif-black italic
This is what the fonts will look like on an updated Android device.Xamarin.Forms Fonts for Android

Hopefully this post will serve as a reference to all those Xamarin.Forms developers looking for fonts. Please download the code and give it a try the next time you’re looking for a font with Xamarin.Forms, Xamarin.iOS or Xamarin.Android.

Download the Xamarin.Forms Fonts App Sample

There’s more where that came from

Stay in the loop with the Syntax Newsletter packed with tips and tricks and the freshest updates - straight to your inbox.

Newsletter subscribers get access to my free training courses first and receive discounts to paid training courses during the opening week.

Sign Up for the Syntax Newsletter

The post Xamarin.Forms Fonts for iOS and Android appeared first on Syntax is my UI.

March 24, 2015 12:00 GMT

Xamarin.Forms Slider View Recipe

I’ve been developing in Xamarin.Forms for months and yesterday was the first time I used a Xamarin.Forms Slider. On occasion, I try to reproduce popular apps or designs in Xamarin.Forms. This time I was trying to recreate an iOS app design from Dribbble.

iOS AppSettings
Android AppSettings

Recreating well known apps or designs in your framework is a great way to learn and explore. The designs will force you to use controls and techniques you would never have used otherwise.

Xamarin.Forms Slider

The Xamarin.Forms Slider View is a simple control. It may be one of the simplest. It has Minimum, Maximum, and Value properties as well as a ValueChanged event. Take a look at this example.

Xamarin.Forms Slider

The Codez

var page = new ContentPage ();

var header = new Label {
	Text = "Slider",
	FontAttributes = FontAttributes.Bold,
	FontSize = 50,
	HorizontalOptions = LayoutOptions.Center

var slider = new Slider {
	Minimum = 0,
	Maximum = 100,
	VerticalOptions = LayoutOptions.CenterAndExpand;
slider.ValueChanged += 
	(sender, e) => {String.Format ("Slider value is {0:F1}", e.NewValue);};

label = new Label {
	Text = "Slider value is 0",
	FontSize = 25,
	HorizontalOptions = LayoutOptions.Center,
	VerticalOptions = LayoutOptions.CenterAndExpand

page.Padding = new Thickness (10, Device.OnPlatform (20, 0, 0), 10, 5);

page.Content = new StackLayout {
	Children = {

Xamarin.Forms Slider ValueChanged Event

All the magic happens in the ValueChanged event of the slider. As you move the slider, this event is fired. Subscribers will get a ValueChangedEventArgs with the old and new slider values. In our sample app, we set a label to the new value.

Xamarin.Forms Slider Steps

From the screenshot of the app you can see the slider needs to set between the predefined Sync times of 1, 5, 30 and 60 minutes. The Xamarin.Forms Slider does not have step functionality and it needs it. Most UI frameworks like jQuery have sliders with steps.


Determines the size or amount of each interval or step the slider takes between the min and max. The full specified value range of the slider (max – min) should be evenly divisible by the step.

jQuery Slider

Adding the missing step functionality to the Xamarin.Forms Slider was easy. The magic happens in the ValueChanged subscriber.

private void HandleSliderChangedEvent (object sender, ValueChangedEventArgs e)
	syncSlider.Value = ((int)Math.Round(e.NewValue / 25.0)) * 25;

	if (SyncValueChanged != null) {
		var changes = new ValueChangedEventArgs (e.OldValue, syncSlider.Value);
		SyncValueChanged.Invoke (this, changes);

The math is pretty simple and setting the value to the closest step in the event was easy. Getting the correct step and min / max values will take you a few minutes. Adding stepping to the Xamarin.Forms Slider was no big deal. Is that why it’s not built in? Maybe!

The Xamarin.Forms Cookbook Series

Still hungry for more Xamarin.Forms? Try these other recipes from the Xamarin.Forms Cookbook Series.

There’s more where that came from

Stay in the loop with the Syntax Newsletter packed with tips and tricks and the freshest updates - straight to your inbox.

Newsletter subscribers get access to my free training courses first and receive discounts to paid training courses during the opening week.

Sign Up for the Syntax Newsletter

The post Xamarin.Forms Slider View Recipe appeared first on Syntax is my UI.

March 23, 2015 5:27 GMT

Android Tips: Immersive Panoramic Google Maps

Displaying a map in your app can add a lot of context for a specific location. You can also take things a step further, though, and create a fully immersive experience to help your users get where they need to be.Panorama View Control Android This can be accomplished in just a few lines of code with the Street View Panorama View control.

Previously, I covered how to use Google Maps Lite in your Xamarin.Android apps for displaying non-interactive, light-weight maps. For the Panorama View, you will go through the same setup process of adding Google Play Services to your project and settings up your Google Maps API Key. In this example, we will add more context our Coffee Filter app by adding a button to navigate to the Street View page.

Add a StreetViewPanoramaView

The first step is to add a new layout. We are going to simply fill the entire page with a StreetViewPanoramaView as we want to fully immerse our users in the street view. You can of course embed the control into an existing page and make it any size you wish.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_gravity="center" />

Setting up the Activity

Similar to using Google Maps, we will need to implement a callback, IOnStreetViewPanoramaReadyCallback, in our Activity and initialize our StreetViewPanorama.

public class PanoramaActivity : ActionBarActivity, IOnStreetViewPanoramaReadyCallback
  StreetViewPanoramaView streetViewPanoramaView;
  StreetViewPanorama streetPanorama;
  LatLng latlng;
  protected override void OnCreate (Bundle bundle)
    base.OnCreate (bundle);
    SetContentView (Resource.Layout.panorama);
    //pass in lat/lng from parent activity
    var lat = Intent.GetDoubleExtra ("lat", 37.7977);
    var lng = Intent.GetDoubleExtra ("lng", -122.40);
    //create LatLng to display
    latlng = new LatLng (lat, lng);
    //find our panorama view and create async.
    streetViewPanoramaView = FindViewById<StreetViewPanoramaView> (Resource.Id.panorama);
    streetViewPanoramaView.OnCreate (bundle);
    streetViewPanoramaView.GetStreetViewPanoramaAsync (this);

The IOnStreetViewPanoramaReadyCallback interface has one method to implement OnStreetViewPanoramaReady. This will pass your StreetViewPanorama that you use to set certain properties and set the position to display. We will turn on just about every feature, and set the position to the position that was passed in from the parent activity.

public void OnStreetViewPanoramaReady (StreetViewPanorama panorama)
  this.streetPanorama = panorama;
  streetPanorama.UserNavigationEnabled = true;
  streetPanorama.StreetNamesEnabled = true;
  streetPanorama.PanningGesturesEnabled = true;
  streetPanorama.ZoomGesturesEnabled = true;
  streetPanorama.SetPosition (latlng);

In addition to this, it’s best practice to override OnResume, OnPause, OnDestroy, OnLowMemory, and OnSaveInstanceState in your Activity and call the matching methods on your StreetViewPanoramaView control. If you don’t want to wire the lifecycle events yourself, there’s also a Fragment & SupportFragment version of the StreetViewPanorama that will handle this for you automatically.

Full Immersion

In Android KitKat, Google introduced a new API called Immersive Full-Screen mode for an Activity. This enables your app to extend all the way into the status and navigation bars on the device. To take advantage of this, you simply need to add a few lines of code in your Activity, setting the SystemUiVisibility of the DecorView.

public override void OnWindowFocusChanged (bool hasFocus)
  base.OnWindowFocusChanged (hasFocus);
  if (hasFocus && (int)Build.VERSION.SdkInt >= 19) {
    Window.DecorView.SystemUiVisibility =
        | SystemUiFlags.HideNavigation
        | SystemUiFlags.LayoutFullscreen
        | SystemUiFlags.Fullscreen
        | SystemUiFlags.ImmersiveSticky);

We now have a fully immersive, beautiful Street View Panorama View in our app!

In Motion Panorama

Learn More

To get started, be sure to download the Google Play Service component from the Component Store for your Android apps. Read through the entire Street View documentation from Google for advanced options. We also have a full sample of adding Immersive mode to your Xamarin.Android apps. You can find the full source code for this sample and Coffee Filter on my GitHub.

The post Android Tips: Immersive Panoramic Google Maps appeared first on Xamarin Blog.

March 22, 2015 1:30 GMT

Episode 24: Cross-Platform Performance Comparisons with Kevin Ford

Ever wanted to know how different app frameworks and approaches compare with each other when it comes to performance? In this episode we spoke to Kevin Ford to dig into exactly that. Join us for a look at how the native SDKs, Xamarin, and Cordova compare for various performance measurements.

Hosts: Greg Shackles

Guest: Kevin Ford


Thanks to our Sponsors!


Raygun.io – Exceptional Error Tracking Raygun.io is the fastest and easiest way to track your application’s errors and get the level of detail you need to fix crashes quickly. Notifications are delivered right to your inbox and presented on a beautiful dashboard.

March 22, 2015 6:45 GMT

Navigation from a ListView

The problem to be solved

One drawback with the vanilla ListView that comes with Xamarin.Forms is that once an item is selected it can't be selected again until you select something else and reselect it. Usually this is fine, unless you use the ListView to navigate away to a new page. When you return you cannot re-navigate to the same page again.

The solution

The solution to this is simple, just hook up to the ItemSelected event for the ListView and set the SelectedItem property to null.

So the short version of you quick-googlers would be the following line of code. (in the View)

  // Reset the selected item to make it selectable again
  duckListView.ItemSelected += (s, e) => {
    duckListView.SelectedItem = null; 

And the navigation should be done in the ViewModel

        public Duck SelectedDuck
                if (value != null)
                    // IoC omitted, we should really get someone else to 
                    // create these objects for us.
                    var viewModel = new DuckViewModel() { Duck = value };
                    var page = new DuckView(viewModel);

The more verbose version

You could also navigate directly from this event handler, but you should feel it deep in your heart that that is just wrong. Instead we handle navigation in the ViewModel. I've created a sample project to do this. Also, I'm doing this without any additional framework that would handle navigation for you so that's why I need to provide my ViewModel with a navigation interface.

I'll present each file to you below or just download the sample solution from here.

The Model

Our model is simple. It's just a duck with a name... As you might recall, a model could be anything really. In this case it's a simple class.
    public class Duck
        public string Name

The ViewModel (s)

We've got two ViewModels, but it's really only the MainViewModel that's interesting. It initializes it's own data, which usually should be done async from another source. It doesn't implement INotifyPropertyChanged either, as is should but for this sample it's good enough.

What to focus on is the SelectedDuck property that handles the navigation. We only implement a setter for this since we reset the selected item anyhow in the view itself and on top of that navigate away from the page.

    /// <summary>
    /// The sample ViewModel. Should implement INotifyPropertyChanged
    /// </summary>
    public class MainViewModel
        private INavigation _navigation;

        public MainViewModel(INavigation navigation)
            _navigation = navigation;

            Ducks = new List<Duck>()
                new Duck() { Name = "George" },
                new Duck() { Name = "Bob" },
                new Duck() { Name = "Sarah" },
                new Duck() { Name = "Clint" },

        /// <summary>
        /// A list of ducks
        /// </summary>
        /// <value>The ducks.</value>
        public List<Duck> Ducks

        public Duck SelectedDuck
                if (value != null)
                    // IoC omitted, we should really get someone else to 
                    // create these objects for us.
                    var viewModel = new DuckViewModel() { Duck = value };
                    var page = new DuckView(viewModel);

The other ViewModel (DuckViewModel) simply references the selected duck on the page we navigate to.

   public class DuckViewModel
        public DuckViewModel()

        public Duck Duck

The View

That leaves us with the view that consists of two parts; XAML and the code behind. Usually you don't want any code expect the ViewModel-binding in the code-behind since it's very platform coupled, but in this case we need to do an exception. We need to reset the SelectedItem property of the ListView.

    public partial class MainView : ContentPage
        public MainView()
            BindingContext = new MainViewModel(this.Navigation); // Should be injected

            // Reset the selected item to make it selectable again
            duckListView.ItemSelected += (s, e) => {
                duckListView.SelectedItem = null; 

The XAML parts look like this.

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="ListViewNavigation.MainView">

      <ListView x:Name="duckListView"
             ItemsSource="{Binding Ducks}"
             SelectedItem="{Binding SelectedDuck}">
            <Label Font="Large" Text="{Binding Name}" />



There is a lot missing in forms of Ioc and base frameworks for MVVM (like MvvmLight och MvvmCross). Is there an alternative for the extreme mvvm-purists? Yes, you could hook up a GestureRecognizer on each item in the ListView but some platform specific animations will be lost if you do so.

Please give feedback what ever you feel like! And if there's a better way, I would love for you to enlighten me! :D

March 22, 2015 3:10 GMT

Authenticating with Touch ID and the iPhone pin

One thing I really love about the new iOS devices - iPhone 5S, 6, 6+ and the iPad Air 2 - is the Touch ID sensor. I’ve always had a PIN on my devices - there is too much important information on my phone to not have one - and TouchI ID takes the pain out of it1. It's also core to the iOS experience: Apple Pay relies on it, and it's used by iTunes and a lot of other Apple apps.

Touch ID promo shot

But one thing I want is a nice, easy way to use the Touch ID sensor in my own apps. iOS8 introduced the Local Authentication APIs. This makes it easy - trivial - to request a Touch ID authentication.

var context = new LAContext ();
context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, "Do Secret Stuff", (bool success, NSError error) => {
    if (success) {
    } else {
        switch (error.Code) {
        case LAStatus.AuthenticationFailed:
        case LAStatus.UserCancel:

This is all good and easy, but it gives the user an option I don't like: they can use Touch ID, or they can enter a password (or cancel). And if there is no Touch ID, it'll just not work - it's finger prints or nothing. Worse, there is no way to turn off the password option (or change the text).

Touch ID shot using LAContext

One thing I didn't know about until recently is that you can get the same - or similar - prompt, but allow it to fall back to the devices PIN, without a password option. This means it works on any iOS8 device.

For most of my uses - validate that the person on the phone is the owner or someone the owner has trusted - this is the best option.

It's just not that obvious how to do it.

The general idea for this - and I'm assuming it's a bit of a hack workaround - is to put a new item into the Keychain, but set it's ACLs to require the user to authenticate in order to get it back. The magic ACLs are

new SecAccessControl (SecAccessible.WhenPasscodeSetThisDeviceOnly, SecAccessControlCreateFlags.UserPresence)

In Objective-C land, this is kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly and kSecAccessControlUserPresence. For the life of me, I can't find reference to it in Apple's docs, but they do have a sample and also slides from a WWDC session on this. Maybe we get the docs in iOS9.

The full call to create the Keychain item is this:

var secret = NSData.FromString (UIDevice.CurrentDevice.IdentifierForVendor.ToString(), NSStringEncoding.Unicode);

var record = new SecRecord (SecKind.GenericPassword) {
    Service = NSBundle.MainBundle.BundleIdentifier,
    Account = "SecurityViewAccount",
    AccessControl = new SecAccessControl (SecAccessible.WhenPasscodeSetThisDeviceOnly, SecAccessControlCreateFlags.UserPresence),
    UseNoAuthenticationUI = true,
    ValueData = secret

var res = SecKeyChain.Add (record);

return (res == SecStatusCode.Success);

You can update it in a similar manner if needed, as the add will fail if the item already exists. To do the actual authentication:

var query = new SecRecord (SecKind.GenericPassword) {
    Service = NSBundle.MainBundle.BundleIdentifier,
    Account = "SecurityViewAccount",
    AccessControl = new SecAccessControl (SecAccessible.WhenPasscodeSetThisDeviceOnly, SecAccessControlCreateFlags.UserPresence),
    UseOperationPrompt = "Your message goes here", 
SecStatusCode status;

var res = SecKeyChain.QueryAsData (query, false, out status);
if (res != null) {
    return NSString.FromData(res, NSStringEncoding.Unicode).ToString ();

return null;

A non-null result means they authenticated - if you need it, the result is the secret that you stored when you created the item. This shows a subtley different UI to the user:

Touch ID UI with PIN

And better yet, on iOS8 devices without Touch ID, the user is prompted for the PIN if they press "Enter Passcode".

There is still no customisation of the dialog. No option to ONLY use Touch ID (no PIN), which would be nice. And no fallback for devices which have no PIN set at all - you'd need to make your own PIN screen for that.

I've put together a very basic project which shows how it works. It's iOS8 only, tho it works on iOS7 - it just will not let you in! When I get around to rewriting Trip Wallet, I think I'll use this as the main authentication method.

  1. The only thing I don't like is, sometimes, when I want to hit the media controls, the phone has already logged me in. First world problem, I know.

March 21, 2015 12:00 GMT

NuGet Support in Xamarin Studio 5.8

Xamarin Studio 5.8 added support for Apple’s Watch Kit and it also includes some NuGet bug fixes.

Bug Fixes

  • Allow ASP.NET project templates to work offline.
  • Build error after updating Xamarin.Forms in a project created by Visual Studio
  • Custom MSBuild task not updated after updating Xamarin.Forms
  • Update information in the Solution window incorrect after updating packages
  • Check for package updates continues after closing a solution
  • Check for package updates prevents packages from being removed
  • Incorrect error message displayed when checking for package updates
  • Exception when checking for package updates after changing target framework of a project

More information on all the new features and changes in Xamarin Studio 5.8 can be found in the release notes.

Allow ASP.NET project templates to work offline

Previously it was not possible to create an ASP.NET project without an internet connection even if all the NuGet packages were available in the local machine’s NuGet packages cache.

Now the local machine’s NuGet cache is used as the primary source of packages for project templates so it is possible to create an ASP.NET project without an internet connection if the NuGet packages are already in this cache.

This problem did not affect project templates, such as Xamarin.Forms, which include the NuGet packages with their project templates.

Build error after updating Xamarin.Forms in a project created by Visual Studio

When a NuGet package that uses custom MSBuild targets file, such as Xamarin.Forms, is added to a project by Visual Studio the project file has an extra Target added, as shown below.

<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <ErrorText>This project references NuGet package(s) that are missing on this computer.
Enable NuGet Package Restore to download them.  For more information, see
http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
  <Error Condition="!Exists('packages\Xamarin.Forms.\build\portable-win+net45+wp80+MonoAndroid10+MonoTouch10\Xamarin.Forms.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\Xamarin.Forms.\build\portable-win+net45+wp80+MonoAndroid10+MonoTouch10\Xamarin.Forms.targets'))" />

When the project was opened in a previous version of Xamarin Studio, and the NuGet package is updated or removed, the Error task was not updated. The project would then fail to compile with an error being reported that the old .targets file could not be found.

Now when updating or removing a NuGet package the EnsureNuGetPackageBuildImports target is checked and the matching Error task will be removed. If there are no remaining Error tasks then the EnsureNuGetPackageBuildImports target is also removed. This prevents build errors after updating or uninstalling the old NuGet package from the project.

Note that Xamarin Studio will not add an EnsureNuGetPackageBuildImports target and will not add Error tasks to a project when a NuGet package is added or updated.

Custom MSBuild task not updated after updating Xamarin.Forms

If a project that had a reference to Xamarin.Forms was compiled once, then the NuGet package was updated, the old MSBuild task was still being used when compiling.

For Xamarin.Forms this could cause a “XamlG Task failed unexpectedly” build error to be reported. Also the Package Console would report not being able to access the Xamarin.Forms.Build.Tasks.dll when updating or removing the NuGet package.

The problem was that MonoDevelop.Projects.Formats.MSBuild.exe that compiles the project would lock the MSBuild task assembly.

Now when an MSBuild import is removed on updating a NuGet package Xamarin Studio will dispose the current project builder which will shutdown the MonoDevelop.Projects.Formats.MSBuild.exe process. This unlocks any custom MSBuild task assemblies loaded by this process, allowing the old NuGet package to be removed without any access denied errors, and when the project is recompiled again it will use the correct MSBuild task assembly.

Update information in the Solution window incorrect after updating packages

With check for updates enabled in Preferences, when an ASP.NET project is created, updates are shown as available for several packages. When the packages are updated the Solution window would still show updates as being available even though the packages had been updated.

The problem was that a change was made in Xamarin Studio 5.7 to update package dependencies at the same time as the package was updated. This meant that an update event was not fired for each package being updated which would result in some package updates being shown as available in the Solution window even when they had been updated.

Now Xamarin Studio will check all package references when a package is updated so if any package dependencies are updated the Solution window will show the correct status of the packages.

Check for package updates continues after closing a solution

Xamarin Studio will now stop checking for package updates when the current solution is closed. Previously this would continue until the check was completed.

Check for updates prevents packages from being removed

Previously when Xamarin Studio was checking for package updates all other NuGet actions, such as updating, adding or removing packages, would not be run until the check for updates had completed. Now the check for NuGet package updates is done on a separate thread so other NuGet actions can be run at the same time.

Incorrect error message displayed when checking for package updates

The Package Console would sometimes show the error message “An exception was thrown while dispatching a method call in the UI thread.” instead of the underlying error making it difficult to determine the cause of the problem. For example if there was a zero byte sized .nupkg file in the solution’s package directory, and check for updates is enabled, then the wrong error was displayed in the Package Console.

Exception when checking for package updates after changing target framework of a project

Previously a null reference exception would be reported in the Package console window when doing the following:

  1. Create a project with one NuGet package added.
  2. Create two NuGet package sources in Preferences. Disable all other package sources.
  3. Open the Add Packages dialog and select All Sources.
  4. Go back to Preferences and uncheck both of the package sources.
  5. Change the target framework of the project in the project options.
March 20, 2015 6:16 GMT

Functional GUI Apps with F# at FRINGE

I’m speaking at FRINGE!

My topic is “Functional GUI Apps” in which I will try to convince you that GUIs don’t have to be tangles of state transforming events.

When I first started using F#, I immediately recognized it as a wonderful data modeling and transformation language. But I wasn’t quite sure how to write GUI apps with it.

Sure, F# supports writing object oriented code so you can build UIs just as you would in C#. But I wanted more - I wanted my UI layer to have the same elegance as my model layer.

After a few false starts, I not only found that it’s possible to do GUIs in a functional style, but that there are a lot of advantages to doing it that way. I will be presenting my findings and also the work of others that have played in this fun world.

Mea Culpa: Dedicated readers will note that I whined a lot about not getting to speak at FRINGE just a couple days ago. Why this change of news? One simple answer: I’m terrible at email. Yes, my talk got accepted and, through my own cleverness, I never saw the acceptance letter. Some days… some days…

March 20, 2015 1:37 GMT

Code Review: Microsoft's System.Net.Mail Implementation

For those reading my blog for the first time and don't know who I am, allow myself to introduce... myself.

I'm a self-proclaimed expert on the topic of email, specifically MIME, IMAP, SMTP, and POP3. I don't proclaim myself to be an expert on much, but email is something that maybe 1 or 2 dozen people in the world could probably get away with saying they know more than I do and actually back it up. I've got a lot of experience writing email software over the past 15 years and rarely do I come across mail software that does things better than I've done them. I'm also a critic of mail software design and implementation.

My latest endeavors in the email space are MimeKit and MailKit, both of which are open source and available on GitHub for your perusal should you doubt my expertise.

My point is: I think my review carries some weight, or I wouldn't be writing this.

Is that egotistical of me? Maybe a little.

I was actually just fixing a bug in MimeKit earlier and when I went to go examine Mono's System.Net.Mail.MailMessage implementation in order to figure out what the problem was with my System.Net.Mail.MailMessage to MimeKit.MimeMessage conversion, I thought, "hey, wait a minute... didn't Microsoft just recently release their BCL source code?" So I ended up taking a look and pretty quickly confirmed my suspicions and was able to fix the bug.

When I begin looking at the source code for another mail library, I can't help but critique what I find.

MailAddress and MailAddressCollection

Parsing email addresses is probably the hardest thing to get right. It's what I would say makes or breaks a library (literally). To a casual onlooker, parsing email addresses probably seems like a trivial problem. "Just String.Split() on comma and then look for those angle bracket thingies and you're done, right?" Oh God, oh God, make the hurting stop. I need to stop here before I go into a long rant about this...

Okay, I'm back. Blood pressure has subsided.

Looking at MailAddressParser.cs (the internal parser used by MailAddressCollection), I'm actually pleasantly surprised. It actually looks pretty decent and I can tell that a lot of thought and care went into it. They actually use a tokenizer approach. Interestingly, they parse the string in reverse which is a pretty good idea, I must say. This approach probably helps simplify the parser logic a bit because parsing forward makes it difficult to know what the tokens belong to (is it the name token? or is it the local-part of an addr-spec? hard to know until I consume a few more tokens...).

For example, consider the following BNF grammar:

address         =       mailbox / group
mailbox         =       name-addr / addr-spec
name-addr       =       [display-name] angle-addr
angle-addr      =       [CFWS] "<" addr-spec ">" [CFWS] / obs-angle-addr
group           =       display-name ":" [mailbox-list / CFWS] ";"
display-name    =       phrase
word            =       atom / quoted-string
phrase          =       1*word / obs-phrase
addr-spec       =       local-part "@" domain
local-part      =       dot-atom / quoted-string / obs-local-part
domain          =       dot-atom / domain-literal / obs-domain
obs-local-part  =       word *("." word)

Now consider the following email address: "Joe Example" <joe@example.com>

The first token you read will be "Joe Example" and you might think that that token indicates that it is the display name, but it doesn't. All you know is that you've got a 'quoted-string' token. A 'quoted-string' can be part of a 'phrase' or it can be (a part of) the 'local-part' of the address itself. You must read at least 1 more token before you'll be able to figure out what it actually is ('obs-local-part' makes things slightly more difficult). In this case, you'll get a '<' which indicates the start of an 'angle-addr', allowing you to assume that the 'quoted-string' you just got is indeed the 'display-name'.

If, however, you parse the address in reverse, things become a little simpler because you know immediately what to expect the next token to be a part of.

That's pretty cool. Kudos to the Microsoft engineers for thinking up this strategy.

Unfortunately, the parser does not handle the 'group' address type. I'll let this slide, however, partly because I'm still impressed by the approach the address parser took and also because I realize that System.Net.Mail is meant for creating and sending new messages, not parsing existing messages from the wild.

Okay, so how well does it serialize MailAddress?

Ugh. You know that face you make when you just see a guy get kicked in the nuts? Yea, that's the face I made when I saw line #227:

encodedAddress = String.Format(CultureInfo.InvariantCulture, "\"{0}\"", this.displayName);

The problem with the above code (and I'll soon be submitting a bug report about this) is that the displayName string might have embedded double quotes in it. You can't just surround it with quotes and expect it to work. This is the same mistake all those programmers make that allow SQL-injection attacks.

For an example of how this should be done, see MimeKit's MimeUtils.Quote() method.

I had such high hopes... at least this is a fairly simple bug to fix. I'll probably just offer them a patch.

ContentType and ContentDisposition

Their parser is decent but it doesn't handle rfc2231 encoded parameter values, so I'm not overly impressed. It'll get the job done for simple name="value" parameter syntax, though, and it will decode the values encoded with the rfc2047 encoding scheme (which is not the right way to encode values, but it is common enough that any serious parser should handle it). The code is also pretty clean and uses a tokenizer approach, so that's a plus. I guess since this isn't really meant as a full-blown MIME parser, they can get away with this and not have it be a big deal. Fair enough.

Serialization, unsurprisingly, leaves a lot to be desired. Parameter values are, as I expected, encoded using rfc2047 syntax rather than the IETF standard rfc2231 syntax. I suppose that you could argue that this is for compatibility, but really it's just perpetuating bad practices. It also means that it can't properly fold long parameter values because the encoded value just becomes one big long encoded-word token. Yuck.


Amusingly, Microsoft does not use their Convert.FromBase64() decoder to decode base64 in their System.Net.Mail implementation. I point this out mostly because it is the single most common problem users have with every one of the Open Source .NET mail libraries out there (other than MimeKit, of course) because Convert.FromBase64() relies on the data not having any line breaks, white space, etc in the input stream.

This should serve as a big hint to you guys writing your own .NET email libraries not to use Convert.FromBase64() ;-)

They use unsafe pointers, just like I do in MimeKit, but I'm not sure how their performance compares to MimeKit's yet. They do use a state machine, though, so rock on.

I approve this base64 encoder/decoder implementation.


One thing they do which is pretty cool is connection pooling. This is probably a pretty decent win for the types of things developers usually use System.Net.Mail's SmtpClient for (spam, anyone?).

The SASL AUTH mechanisms that they seem to support are NTLM, GSSAPI, LOGIN and WDIGEST (which apparently is some sort of IIS-specific authentication mechanism that I had never heard of until now). For those that were curious which SASL mechanisms SmtpClient supported, well, now you know.

The code is a bit hard to follow for someone not familiar with the codebase (not nearly as easy reading as the address or content-type parsers, I'm afraid), but it seems fairly well designed.

It does not appear to support PIPELINING or BINARYMIME like MailKit does, though. So, yay! Win for MailKit ;-)

They do support SMTPUTF8, so that's good.

It seems that if you set client.EnableSsl to true, it will also try STARTTLS if it isn't able to connect on the SSL port. I wasn't sure if it did that or not before, so this was something I was personally interested in knowing.

Hopefully my SmtpClient implementation review isn't too disappointing. I just don't know what to say about it, really. It's a pretty straight-forward send-command-wait-for-reply implementation and SMTP is pretty dead simple.


Overall the bits I was interested in were better than I expected they'd be. The parsers were pretty good (although incomplete) and the serializers were "good enough" for normal use.

Of course, it's not as good as MimeKit, but let's be honest, MimeKit sets the bar pretty high ;-)

March 19, 2015 4:05 GMT

Exciting Xamarin Announcements from dotnetConf

Miguel and I just had the honor of helping kick off day two of dotnetConf, along with our good friend Scott Hanselman. dotnetconf logo
dotnetConf is a two-day virtual event, dedicated to all things .NET and to highlighting our vibrant developer community. We had a few exciting announcements to share with everyone, which you can watch for yourself in the recording below, or read about in the summary that follows.

Xamarin.Forms for Windows Preview

Xamarin.Forms for Windows Store

We launched Xamarin.Forms a year ago, enabling developers to rapidly create native applications for iOS, Android, and Windows Phone from a single shared C# code base. One of our most popular samples from that launch is an app dedicated to all things Scott Hanselman – aptly named Hanselman.Forms.

For today’s intro with Scott, I couldn’t resist taking the opportunity to re-launch Hanselman.Forms with podcast streaming and a few new bells and whistles showing off the latest features available in Xamarin.Forms, such as pull-to-refresh. But the fun didn’t stop there, as we capped off the demo with the exciting announcement of our preview support for building for Windows Store and Phone RT when developing with Xamarin.Forms.

Hanselman.Forms on All Devices

Xamarin.Forms for Windows Preview is available now on NuGet as a pre-release package. This is a very early preview that we’re making publicly available to get as much feedback as possible from the community as we stabilize our Windows support over the next few months. To get started, simply add a new Windows Store app to your existing solution and with a few lines of initialization code and you are on your way. We have full documentation for this preview available on our developer portal, and you can download and run the source for Hanselman.Forms straight from GitHub.

Xamarin Everywhere

The theme of today’s talk was “.NET deserves to be everywhere”, so in addition to extending the Hanselman app to Windows Store, I also took the opportunity to update it with support for wearable platforms, because I know that everyone wants mission-critical Hanselman updates on their wrist. Now, you will find a brand new Android Wear and Apple Watch app as part of the Hanselman.Forms project with plenty of awesome shared C# code, and you can start building your own wearable apps today with WatchKit in Xamarin.iOS, or by referencing the Android Wear Component or NuGet in your Xamarin.Android projects.


Xamarin Subscriptions for OSS Contributors

We love the .NET community and are dedicated to supporting the huge community of .NET developers working on powerful NuGets like PCLStorage, SQLiteNet and other plugins for Xamarin and Windows.

Xamarin Heart OSS

To ensure that all open source projects have everything they need to succeed, today we also announced the expansion of our our support for OSS developers to include free Xamarin subscriptions with support for Visual Studio. Any open source developers with app store compatible licenses receive non-commercial Xamarin subscriptions for the purpose of developing, testing and maintaining compatibility with the Xamarin platform. Active developers on established open source projects can apply now.

The post Exciting Xamarin Announcements from dotnetConf appeared first on Xamarin Blog.

March 19, 2015 4:25 GMT

Microsoft Band SDK + Xamarin

Band-fans were happy to see Microsoft release their Java Android SDK for Microsoft Band a few weeks ago, and their Objective-C iOS SDK this week. Xamarin was then able to almost immediately release the Microsoft Band SDK component for iOS and Android, giving you the same functionality but entirely in C# for all three mobile platforms...

I decided to give it a try, converting my "magic eight ball" apps for Xamarin.Forms and Apple Watch to the Band. The idea is: you shake your wrist and the "prediction" appears on the Band!

It works because there is an Android app running on the paired phone, using the Band SDK. The app is tracking the Band's accelerometer, and using the readings to decide when you've shaken your wrist a couple of times.

When the shake-detection is triggered, the app picks a random number, pushes a new Tile onto the Band (if it doesn't already exist), and then sends a message for the tile with a random "prediction".

The Android app is simple, it contains only a Connect button to connect to the Band, and a Vibrate button to test the connection (plus a label that displays the "prediction" text that is sent to the Band).

The code for this Android sample is available on github, hopefully I'll get the iOS version running soon.

If you want to get more info about developing for the Band, check out Matt's detailed blogpost with code.

Finally, Microsoft built a quite detailed Android app that demonstrates all aspects of their SDK, and Matt did an amazing job of porting it to Xamarin - check that out too!

March 18, 2015 9:36 GMT

Xamarin.Forms: Segmented Control

iOS has a very useful segmented control.   It is, essentially, a set of radio buttons that look more like an array of normal buttons…



It would be great to have this on iOS and Android, and by the way I’d like it to work in Xamarin.Forms.  So I set out to write it, and I did so the way I do, which is to first see if someone else has already done it(!)  Sure enough, my buddy Venkata pointed me at Chris Pellett’s project on GitHub.  It does, at least to a first approximation, exactly what I want.


Read more

March 18, 2015 5:27 GMT

Android Parallax Made Easy

You may have seen some of my tweets recently about the upcoming release of Coffee Filter 2.0 with some awesome new features. Before I release any Android app I always send it off to my good friend Jérémie Laval to do a full UI review. We both love Android and Material Design and he always gives me the best pointers on how to improve my apps. On my details page I setup a complex view with an image on the background that sits behind a ScrollView for the content. I had put a gradient on the background and just let the ScrollView overlap on top of the ImageView. I thought this was pretty nice, however Jérémie immediately could see that it needed a little Parallax. I thought it was going to take me forever to figure out, but it is actually extremely easy to implement, let’s take a look.

Custom ScrollView

Unfortunately, the Android ScrollView does not expose an event to subscribe to whenever it is being scrolled. However, if we create our own custom ScrollView we have access to override the OnScrollChanged event and bubble up our own event to anyone that needs to subscribe (let’s say our Activity).

Update the AXML

Now we just need to update our AXML with the new ScrollView. In this instance I have a FrameLayout with an ImageView in the background, then the ScrollView’s LinearLayout child has the same paddingTop of the height of the Image. This will show the image under it like you see above, but the ScrollView can extend over the image, which is very cool.

Parallax the ImageView

The last step is to subscribe to this new event in your Activity (or Fragment in this case). Then whenever you receive a scroll event you will simply use the ImageView’s TranslateY property to adjust it based on the Y of the ScrollView. In this instance I am using 2.5F as the speed of the parallax and I am setting it to a negative number as we are translating. You can apply this magic number to any view though, such as a ScrollView and scroll it to the positive Y adjustment for a nice parallax as well. 

Here is what it looks like!

March 17, 2015 4:25 GMT

Excited for FRINGE

It’s been too long since we’ve had an open source .NET conference. Since monospace/monkeyspace imploded, we’ve been left with just Xamarin’s Evolve. And while I love Xamarin, and Evolve is glorious, it’s just not the same thing as the free-wheeling brain fest of an OS conference. Only at an open source conference do I get to see free thinkers unabashedly demo’ing their latest library or idea without having to bend it to a corporate initiative. It’s liberating and exciting!

Thankfully, FRINGE is bringing back open source .NET conferences - and it’s doing a hell of a job of it. I love everything about it. I love their web site and the use of pink. I love writing it in all caps.  I love the people organizing it. I love the people who are going. I love the city it’s being held in. I want to retire and just attend FRINGE professionally for the rest of my life.

So go get a ticket and get your bum over to Portland - and bring your best ideas.

Sad about FRINGE Even More Excited for FRINGE

On a personal note, I’m a bit sad that I won’t get to speak at FRINGE. I will be speaking! Since deciding to become an active member of the .NET community (introverts such as myself make such decisions solemnly) I have gotten to speak at the mono and monkeyspaces every year.

It’s a tiring thing being a speaker. You have to do an enormous amount of preparation at home, then, at the conference, you can’t relax until your presentation is over. All that stress, and then your work disappears into the ether 45 mins after you begin (you pray, gods willing, that someone, somehow, remembers a word of what you said - that all that effort was not for nought).

But I love to present. I love to lecture. My friends will often yell, “stop lecturing me!” Little do they know that I’m just practicing for conferences - that I’m annoying them for the greater good of the .NET community.

Part of this comes from my philosophy of knowledge: You haven’t learned something until you can code it (explain it to a computer), and you don’t understand it until you can teach it (explain it to a human). Presenting gives me an excuse to intensely study - to interrogate and hopefully verify - my own knowledge and then communicate the findings. It’s like crack for someone like me.

Withdrawing from an addiction is a painful process.

Personal reflection is in order I suppose. I suppose the topic I proposed “using functional programming to create user interfaces” - while an incredibly timely and sexy topic (note libraries like React, note how kahn academy is writing their apps) in my mind, just didn’t resonate with the organizers. Perhaps my description sucked. Perhaps the other talks are more timely and more thought provoking. Or it could simply be I’m overthinking things and I should get back to work. Probably that last one. I’m an idiot.

See you at FRINGE!

March 17, 2015 11:00 GMT

Xamarin.Forms in Anger

Are you a skeptic of the promise of Xamarin.Forms? Do you believe that with Xamarin.Forms you can build native cross-platform UI’s with a single C# codebase? Early on I struggled with the choice of whether to use Xamarin.Forms or a combination of Xamarin.iOS and Xamarin.Android.

On the Xamarin.Forms Fence

To be completely honest, I am no longer a Xamarin.Forms skeptic, but, I do have some reservations about its ability to make good looking cross-platform UI’s. I know that Xamarin.Forms can make developer level UI’s. You know what I mean; it works — but its ugly!

What can a design conscious developer do when faced with the possibility of a bad UI? Scream? Run away? Move to HTML5? No, that won’t do. It’s time to get angry and swing Xamarin.Forms with all our might.

Death to the Developers UI

Each “In Anger” blog post will tackle a single page of a beautifully designed iOS or Android application. My job will be to reproduce the design in Xamarin.Forms as faithfully as possible. To make things a bit harder I will try not to use custom renderers unless absolutely necessary. I will also make the iOS design fit in the Android Design Guidelines and vice versa for Android to iOS.

You might be asking yourself where am I going to get these designs? We’ll cheat and steal them form any available source. Sources like Dribbble, Behance, Pinterest boards, and popular applications will be our initial fishing grounds. If you have a suggestion for an “In Anger” post, please leave them in the comments.

Our First Contestant

I must admit, I do not know where this screenshot came from. It was probably from Dribbble. The screen to the left will be our focus for this first Xamarin.Forms “In Anger” post.


In the Android version, I used the default Dark theme and styled the app to match. Our goal for this series is to produce cross-platform UI’s that look native on the device; not to make an Android App look like it came from Apple.

The iOS version of the Vet app looks almost identical to the design sample. Special thanks goes to James Montemagno for his Circle Image Plugin. Without it, I would have had to cheat and crop square images to make circles.

iOS Vet

Did Xamarin.Forms keep its promise? For the Vet app, I think it did splendidly. What do you think? Till next time, have fun and don’t be afraid to swing Xamarin.Forms in Anger.

The couple of you that noticed or cared about the missing Windows Phones are out of luck. I will not be focusing on Windows until it gains more market share. Hey, I am entitled, I got burned by Silverlight!

There’s more where that came from

Stay in the loop with the Syntax Newsletter packed with tips and tricks and the freshest updates - straight to your inbox.

Newsletter subscribers get access to my free training courses first and receive discounts to paid training courses during the opening week.

Sign Up for the Syntax Newsletter

Related Post

The post Xamarin.Forms in Anger appeared first on Syntax is my UI.

March 17, 2015 12:32 GMT

NGraphics in a Xamarin Sketch

Frank Krueger published a new open source graphics library called NGraphics today. As with everything Frank does it looks pretty awesome. It even has its own editor where you can type in code and live preview the output. So you probably won’t need what I’m about to show you, but I was curious if it would work with Xamarin Sketches (just for kicks).

Sure enough, all I had to do was add LoadAssembly calls to reference NGraphics assemblies in the sketch and add the assemblies to the sketchname.sketchcs.Resources folder alongside the sketchcs file. Then, since Frank includes methods to return native image types, such as NSImage on Mac, I can leverage the sketch visualizers in Xamarin Studio to get a live preview.

Here’s Frank’s sample code to draw a house in a sketch:


March 16, 2015 9:14 GMT

Introducing NGraphics

Many moons ago I created a cross platform library for rendering vector graphics called CrossGraphics. It was good. It supported lots of platforms and was fast. Very fast in fact because it was designed for my app iCircuit which was already a CPU hog and had to run on 2010 era mobile hardware. To be fast, I played loosey goosey with cross platform accuracy (they mostly rendered the same) and features (who needs gradients?).

But the times, they are a changin’. My phone’s CPU is 64-bits and massive. Apple now supports GPU based rendering (finally that G stands for something other than Triangle). And, the fact is, though flat is in style, you really do need gradients.


Today, I would like to announce NGraphics. A cross platform PCL to satisfy your 2D vector drawing needs. It’s available on nuget now!

NGraphics is a big improvement over CrossGraphics. Here’s why I’m excited:

Platforms! NGraphics comes out of the box supporting iOS, OS X, Android, and Windows.

Gradients! It supports both the linear and radial variety with any number of color stops.

Paths! Crazy paths with arcs can now be used and abused.

Images! Images can be loaded from streams, created by rendering onto a canvas, or built up pixel by pixel.

SVG Reading and Writing! CrossGraphics was able to output SVG, but NGraphics can read ‘em too.

Retained Mode and Immediate Mode! NGraphics supports both immediate mode rendering with canvases (DrawLine, FillPath, etc.) along with a retained mode graphics model (Path, Rectangle, Ellipse, …). This makes caching and serialization easy.

Unit Tests! It turns out that getting all the platforms to behave themselves requires more than blind faith. NGraphics has a unit test suite that runs on all the platforms (4) and generates images to easily spot consistency errors.

Editor! I love to use code to draw things, but I hate waiting for the compiler (or worse, the IDE). So I wrote a little editor that lets you type C# code and get a live preview of the graphic you are creating. I love this thing…


I hope you’ll check out NGraphics! It’s as simple as going to NuGet and searching for “NGraphics”. If you have the time, I would love bug reports, feature requests, and especially pull requests over at the NGraphics project.

March 16, 2015 3:15 GMT

Revisiting the code snack concept

At the end of 2008 I had a clear mission for what I wanted to host on this domain. The idea of a "code snack" was born out of an observation that there needed to be a resource that provided small easily digestible pieces of information about software development. The definition of code snack is clear and concise:

code snack - [kohd snak] - n. - an easily digestible morsel of programming related information

However, despite having a clear vision and a solid definition, this site has only produced two snacks related to Windows 8 design:

  1. Metro Snack #1: Choosing XAML or HTML5 for Windows Developer Preview apps
  2. Metro Snack #2: What is WinRT?

These were written in January 2012. We're a third of the way into 2015 and as someone I respect a ton says frequently: "It's later than you think."

This blog got me started on a path that has certainly led me to where I am today but I can't say that it has lived up to its potential as the resource I defined right before the start of 2009. A very important person in my life recently rekindled this idea and I want to make sure I follow through this time.

Over the next few weeks I'm going to be brainstorming some topics that would make for good snacks but while I work on that I could use your help. What kind of topics would you like to see explained in short easily digestible chunks? Hit me up on Twitter @brentschooley or use my contact form if you have any ideas.

Here's to many snacks in the future.

March 16, 2015 12:26 GMT

URLEncode in Xamarin Forms PCL

The shortest blog post ever. If you want to URLEncode (or decode) in a Xamarin Forms PCL, simply use:

var encoded = System.Net.WebUtility.UrlEncode(veryUnEncoded);

There is also methods for HTML encoding and decoding in there and url encoding/decoding to bytes. I always have to look this up for some reason, that's why I'm putting it on my blog so that I can find it easily.

Thank you, that is all...
March 16, 2015 11:00 GMT

Xamarin.Forms ListView Custom ViewCell Recipe

The easiest way to add some punch and polish to your mobile app is with a customize ListView. Customizing a Xamarin.Forms ListView is pretty easy. It all starts with creating our very own ViewCell.

Our custom ViewCell will be used repeatedly in the ListView for each row of data visible on the screen. Take a look at my “Choose a Vet” sample. The names have been changed to protect the Xamarin. ;)

Xamarin.Forms ListView

 Don’t you just love circle images? I do. Quick shout out to  for making a great plugin for the Xamarin community. You can find the plugin here.

Customizing the Xamarin.Forms ListView

You can customize the Xamarin.Forms ListView in a couple of ways. I like to create a class that inherits from ViewCell and put all of my customizations and bindings in it. The Vet ViewCell layout is complicated. Separating it from the ListView keeps the complexity of the ViewCell from overwhelming the ListView.

public class VetCell:ViewCell
	public VetCell ()
		var vetProfileImage = new CircleImage {
			BorderColor = App.BrandColor,
			BorderThickness = 2,
			HeightRequest = 50,
			WidthRequest = 50,
			Aspect = Aspect.AspectFill,
			HorizontalOptions = LayoutOptions.Center,
			VerticalOptions = LayoutOptions.Center,
		vetProfileImage.SetBinding (Image.SourceProperty, "ImageSource");

		var nameLabel = new Label () {
			FontFamily = "HelveticaNeue-Medium",
			FontSize = 18,
			TextColor = Color.Black
		nameLabel.SetBinding (Label.TextProperty, "Name");

		var distanceLabel = new Label () {
			FontAttributes = FontAttributes.Bold,
			FontSize = 12,
			TextColor = Color.FromHex ("#666")
		distanceLabel.SetBinding (
                        Label.TextProperty, new Binding (
                                stringFormat: "{0} Miles Away")

		// Online image and label
		var onlineImage = new Image () {
			Source = "online.png",
			HeightRequest = 8,
			WidthRequest = 8
		onlineImage.SetBinding (Image.IsVisibleProperty, "ShouldShowAsOnline");
		var onLineLabel = new Label () { 
			Text = "Online", 
			TextColor = App.BrandColor,
			FontSize = 12,
		onLineLabel.SetBinding (Label.IsVisibleProperty, "ShouldShowAsOnline");

		// Offline image and label
		var offlineImage = new Image () {
			Source = "offline.png",
			HeightRequest = 8,
			WidthRequest = 8
		offlineImage.SetBinding (Image.IsVisibleProperty, "ShouldShowAsOffline");
		var offLineLabel = new Label () { 
			Text = "5 hours ago", 
			TextColor = Color.FromHex ("#ddd"),
			FontSize = 12,
		offLineLabel.SetBinding (Label.IsVisibleProperty, "ShouldShowAsOffline");

		// Vet rating label and star image
		var starLabel = new Label () { 
			FontSize = 12,
			TextColor = Color.Gray
		starLabel.SetBinding (Label.TextProperty, "Stars");

		var starImage = new Image () {
			Source = "star.png",
			HeightRequest = 12,
			WidthRequest = 12

		var ratingStack = new StackLayout () {
			Spacing = 3,
			Orientation = StackOrientation.Horizontal,
			Children = { starImage, starLabel }

		var statusLayout = new StackLayout {
			Orientation = StackOrientation.Horizontal,
			Children = { 

		var vetDetailsLayout = new StackLayout {
			Padding = new Thickness (10, 0, 0, 0),
			Spacing = 0,
			HorizontalOptions = LayoutOptions.FillAndExpand,
			Children = { nameLabel, statusLayout, ratingStack }

		var tapImage = new Image () {
			Source = "tap.png",
			HorizontalOptions = LayoutOptions.End,
			HeightRequest = 12,

		var cellLayout = new StackLayout {
			Spacing = 0,
			Padding = new Thickness (10, 5, 10, 5),
			Orientation = StackOrientation.Horizontal,
			HorizontalOptions = LayoutOptions.FillAndExpand,
			Children = { vetProfileImage, vetDetailsLayout, tapImage }

		this.View = cellLayout;

I know what you’re thinking, “Holy cow that’s a lot of code.” Yes, it’s a lot of code. After reading through it, you will see, it’s a lot of nested StackPanels. Here is what it would look like if we could turn on “Borders” for the StackPanels.

Xamarin.Forms ViewCell Vet

 Maybe I should put in a feature request to the Xamarin.Forms team! Yeah. Give me borders!

Marry the Xamarin.Forms ListView to a ViewCell

Getting your custom ViewCell into the ListView is pretty easy. All we have to do is set the ListView’s Item Template to be our ViewCell Type. This is the same way you use the built in ViewCells.

var vetlist = new ListView {
	HasUnevenRows = true,
	ItemTemplate = new DataTemplate (typeof(VetCell)),
	ItemsSource = VetData.GetData (),
	SeparatorColor = Color.FromHex ("#ddd"),

Customizing your Xamarin.Forms ListView will go a long way to making your app design unique. There’s nothing wrong with using the built in ViewCells. Especially if they fit the design and the needs of your app.

Download the Xamarin.Forms ListView Recipe Project

The Xamarin.Forms Cookbook Series

Still hungry for more Xamarin.Forms? Try these other recipes from the Xamarin.Forms Cookbook Series.

There’s more where that came from

Stay in the loop with the Syntax Newsletter packed with tips and tricks and the freshest updates - straight to your inbox.

Newsletter subscribers get access to my free training courses first and receive discounts to paid training courses during the opening week.

Sign Up for the Syntax Newsletter

The post Xamarin.Forms ListView Custom ViewCell Recipe appeared first on Syntax is my UI.

March 15, 2015 10:25 GMT

Debugging Xamarin app network calls on OSX with iOS Simulator

This blog is a quick tip for people trying to debug network calls in their Xamarin/Xamarin.Forms app while on OSX.

While we take it for granted to debug network calls in our web browsers these days, when it comes to a native app it’s not so apparent, especially if you’re on OSX. Note*, this post is for OSX if your using Windows this forum post might help.

In my research I couldn’t find a free debugging proxy but the old faithful Charles Debugging proxy works well.

While you think it might be as simple as opening up Charles there’s actually a few quirks.

Using Charles with iOS Simulator

Thankfully the latest version of Charles proxy can automatically register the certificate on your simulator devices. To do this open Charles and from the Help menu option select ‘Install Charles CA SSL Certificate in iOS Simulators’.

Screen Shot 2015-03-15 at 8.53.09 pm

… run the app in the iOS simulator and that should work right? wrong!

If you’re using Xamarin/Xamarin.Forms and the standard System.Net.HttpClient then this code is fully managed code and will not communicate with the local OS to discover the proxy settings. Luckily we have a little saving grace in that the HttpClient allows for different underlying network implementations, in iOS the native network library is called CFNetwork library. Miguel has previously blogged about this.

Now that’s great but how do I get it working in my Xamarin.Forms app? Well considering the CFNetwork is a Native iOS binding we can’t actually reference it from our Forms PCL, we need to create a dependancy that’s sets it up for us.

It’s the standard way to create a dependancy.

1. Define a interface in our PCL

public interface IHttpClientHandlerFactory
    HttpClientHandler GetHttpClientHandler();

2. Create the Native implementation of the interface

[assembly: Xamarin.Forms.Dependency(typeof(HttpClientHandlerFactory))]
namespace App.iOS
    public class HttpClientHandlerFactory : IHttpClientHandlerFactory
        public HttpClientHandler GetHttpClientHandler()
            return new System.Net.Http.HttpClientHandler {
                Proxy = CoreFoundation.CFNetwork.GetDefaultProxy(),
                UseProxy = true

3. Use the Native implementation

Note* as I’ve only implemented this in my iOS app I’ve got logic which only uses the custom HttpClientHandler when the factory exists.

var handlerFactory = Xamarin.Forms.DependencyService.Get<IHttpClientHandlerFactory> ();
if (handlerFactory == null) 
    client = new HttpClient() {
        BaseAddress = new Uri (ServiceUrl),
    var handler = handlerFactory.GetHttpClientHandler ();
    client = new HttpClient(handler) {
        BaseAddress = new Uri (ServiceUrl),

Once you’v done that, first run Charles and then debug your app in the simulator and you should see the network calls come in.

Happy Debugging…

The post Debugging Xamarin app network calls on OSX with iOS Simulator appeared first on Michael Ridland.

March 12, 2015 6:08 GMT

MonoDevelop.AddinMaker 1.2

I've finally released MonoDevelop.AddinMaker 1.2, making it easier than ever before to customize and add features to Xamarin Studio and MonoDevelop. This release has been stalled for a while due to factors beyond my control, and I'm very happy to be able to make it available at last. Thanks to Lluis for getting rid of the roadblocks!

This release improves the basic user experience by introducing the concept of "Addin References". Instead of referencing an addin's assemblies and explicitly adding a dependency on that addin, you can add an addin reference, which will automatically take care of both of these things for you.

However, the most important changes are below the surface. Switching to the MSBuild engine allows you to use custom MSBuild syntax to customize your build process, and enables command-line builds via MSBuild/xbuild. More importantly, it provides a solid foundation on which to build future improvements.

Happy extending!

March 10, 2015 8:54 GMT

Official Pull To Refresh in Xamarin.Forms 1.4.0!

I can not lie when I say I LOVE pull to refresh in apps. Just search my blog and you will see tons of posts on how to implement it in Android, iOS, MVVMCross, and of course my crazy custom implementations for Xamarin.Forms. While those were nice custom renderers that provided a simple API, we finally have something official from Jason and the Xamarin.Forms team in 1.4.0, which released this week. The API looks strikingly familiar:

I couldn’t explain how it works better than the official release notes: 

When the user triggers a PullToRefresh the Command will be invoked and the Refreshed event emitted. IsRefreshing will be set to true. The ICommand.CanExecute property is respected. The user must either call EndRefresh or assign IsRefreshing to false in order to end the refresh state.

So, how would you implement this in your ViewModel? Well I start all things off with a bool called IsBusy that tracks if we are loading data on the page:

We can use this to bind to our IsRefreshing and use it as a CanExecute flag for our ICommand. Next is to setup some sort of ICommand and method that will be refreshing our data. In this example I am updating my Hanselman.Forms app's tweets page to have pull to refresh, so here is the code that refreshes tweets:

Notice I am using my IsBusy as a control for CanExecute, and also after I change it I call the Command’s ChangeCanExecute method to ensure anyone listening knows to update their status. You can make this a bit more clever if you desire in the properties getter/setter.

Finally is the DataBinding part and you will need to setup and bind up 3 properties: IsPullToRefreshEnabled, RefreshCommand, and IsRefreshing.

Notice I am only Binding OneWay on IsRefreshing. This means that my ViewModel can notify and change the IsRefreshing, but the Refresh view is not in control of my IsBusy. This is only important because I always check IsBusy ahead of time when I run my refresh logic. I am also using IsBusy to modify the CanExecute so I don’t want any outside forces modifying it.

And there you have it, let’s see it in action:

March 09, 2015 9:03 GMT

Essential Xamarin.Android Templates for Visual Studio

During my Effective Navigation in Android talk at last years Xamarin Evolve I had the opportunity of showcasing my Xamarin.Android Templates Pack for Visual Studio, which you can get from the Visual Studio Gallery under “Tools->Extensions and Updates”. I like the templates that come installed with Xamarin, however the flexibility of Visual Studio to easily create project and item templates led me to creating this pack which included:


  1. Navigation Drawer


  1. Single Menu Item
  2. Search Menu Item
  3. Share Menu Item

While these were great at the time the entire Android ecosystem has shifted towards AppCompat for Material Design in apps. So I worked all day and night Sunday to update my Templates pack to bundle in a bunch of AppCompat project templates, and also extended the item templates to include AppCompat versions. 

Android Blank App AppCompat 

The first template creates a standard blank app, but adds all resource files for you automatically for theming as well as some simple navigation. It also uses the new Toolbar.

Android Navigation Drawer AppCompat 

Probably the most requested template and most used is a nice Navigation Drawer sample with everything you need including images in your navigation drawer and proper selector colors for older API levels.

All The Menu Templates!

I have also update all of the Menu Item xmls to include a standard and AppCompat version. I also have the code that you need to copy into your Activity so you don’t need to go look it up!

One More Thing

I also decided to include a nice Adapter item template with my recommend method of proper view reuse, which you can read more about at http://blog.xamarin.com/creating-highly-performant-smooth-scrolling-android-listviews/. This way you don’t have to remember all that nasty ViewHolder logic. I do plan on introducing a RecyclerView Adapter in the future as well. 

Requests Welcome

All of my project and item templates can be found on GitHub: https://github.com/jamesmontemagno/xamarin-templates and you are free to open up an Issue with a request for Android project or item templates that you might like to see.


I also decided to do a walkthrough of the templates:

March 09, 2015 1:30 GMT

Plugin 05: Accelerometer

In our series on plugins, today we’re going to cover plugin which can help us to work with Accelerometer sensor. This sensor is responsible to detect X, Y, Z co-ordinates of the devices. Using data received from this sensor, you can build games like TempleRun, where users can collect the coins by tilting the device.

There are different APIs for different platform and their usage is different too. First, lets see how we can use this sensor in different platform and then we’ll use plugin in Xamarin.Forms application.

Being Windows Runtime API, the API and its usage is same in Windows and Windows Phone. Here, you create object of the sensor and register for ‘ReadingChanged’ event. Whenever device position is changed, it is reported through that event and UI can be updated using Dispatcher.

In case of Android, it is again similar to Windows platform. Create object of SensorManager and register for SensorChanged event.

iOS is not any different. You create object of CMMotionManager and then listen to sensor for changes.

As you can see, for three different platforms the APIs are totally different. But with Plugins for Xamarin.Forms it becomes easy. You can use DeviceMotion plugin which can work across all these platforms. And the code for same looks like:

In this series on plugin we’ve seen how particular concept can be implemented in all the three platforms and how we can use plugin to make life easier. This will be be last post in this series, but there are many plugins available which you can explore and use in your projects. Do let me know if you want to cover any specific plugin. We’ll start with a new series in couple of weeks. Till then… happy coding :)

Mayur Tendulkar

March 08, 2015 7:38 GMT

Attend: Microsoft Azure Conference 2015

Microsoft Azure Conference 2015

This time, Microsoft India is hosting its ‘Microsoft Azure Conference 2015′ in Pune. This is going to be a huge event for any cloud enthusiast with 2 days and more than 70 sessions. More details about this event is available here: http://www.microsoftazureconference.in/

In this event, I’m going to conduct a hands-on-lab on ‘Put Office 365 in Your Xamarin Mobile Apps’. In this lab, attendees will learn how to integrate Office 365 services in their mobile applications (Android, iOS and Windows)

As a homework, I’ll recommend to go through following links:

This will help you to understand the topic and be prepared for lab.

Mayur Tendulkar


March 08, 2015 3:21 GMT

Android's ActionBarActivity and the Hardware Back Button

In my last post I talked about one of the roadblocks I hit when upgrading to Android's new ActionBarActivity. That was definitely a major pain, but there's one other issue I've run into so far that I wanted to call attention to as well. This one didn't cost us nearly as much time as that last one did, but it was certainly unexpected.

Our apps make use of a single activity and fragments for each separate screen within the app. After updating this activity to extend from ActionBarActivity we noticed that suddenly the hardware back button was causing the host activity to finish, even when there were multiple fragments in the backstack. Prior to this change we could rely on the hardware back button to pop fragments off the stack first, and only finish the activity if there was nothing left in the stack.

I figured this was just a documented change, but a look at Android's documentation for onBackPressed() says:

Take care of popping the fragment back stack or finishing the activity as appropriate.

This description lines up with the behavior I would have expected, but unfortunately the observed behavior is not the same.

The fix for this in the host activity is simple enough:

public override void OnBackPressed()  
    if (FragmentManager.BackStackEntryCount > 0)

All in all it's certainly not the end of the world to add this small amount of code to work around the issue here. I was just surprised by the change in behavior, and wanted to call attention to it in case it helps one of you solve the issue in your apps before they make it out to the Play store.

March 07, 2015 7:26 GMT

XHackNight by XHackers : and the winner of blogtowin contest is

On Feb 7th and 8th, we had an awesome hackathon called XHacknight. Before jumping into the actual, let us once again thank each and every one of you (participants and hackers) for your time, support and enthusiasm.This gives us a boost to come up with more and more events on Xamarin and CocosSharp.

As you know, We asked you folks to come up with a blog post expressing your experience, opinion and feedback on the event. We received 4 blog post entries and everyone of you is a winner for writing up your love for XHackers. Thank You!!

After a thorough walkthrough of your blogs and voting by XHackers panel, The winner is

Mr. Sreekanth - "My experience at my first Hackathon" . Not for his memes, but for a complete rewind of the event.

Smiley face

Congratulations Sreekanth !!!

we will reach out to you soon and you will receive creating mobile apps with xamarin.forms hardcopy from XHackers. Keep blogging about Xamarin and see you all soon !!!

Xhackers Core Team

March 06, 2015 2:31 GMT

Xamarin: Sliding Windows

Sliding Windows

Call it a sliding window, a drawer, a hamburger; it is the latest craze in navigation.  You click on the ubiquitous icon of three lines and the page slides over to reveal… Well whatever you want.  Often it reveals navigation choices.

So the question arises: how do you do this in Xamarin.Forms?  I have looked at a number of sources and samples and have synthesized them into an approach I like.

Start with a Xamarin.Forms Application

The technique I’m going to describe is designed to work with Xamarin.Forms. All of the work is done in the PCL.  Begin by creating a BaseContentPage which derives from ContentPage and adds a NavigationPageName.  This will let pages identify themselves,

Continued here.

March 06, 2015 2:39 GMT

I Get XAML, You Get XAML, Everyone Gets XAML with Xamarin.Forms

Many of you in the Microsoft .NET Framework world are familiar with XAML. XAML is an XML-based language for working with objects. It has been used extensively in developing UIs in Silverlight, Windows Presentation Foundation and is used in the Windows Runtime. Unfortunately, XAML support isn't a feature that's built into iOS or Android. With the release of the Xamarin cross-platform toolkit, Xamarin.Forms, XAML can now be used with those platforms, as well as Windows Phone.

Url: http://visualstudiomagazine.com/articles/2015/03/01/everyone-gets-xaml-with-xamarinforms.aspx

March 05, 2015 5:45 GMT

Coffee Filter: A C# Powered Android App in 2 Days

I love coffee. You will normally find me riding my bike around Seattle stopping from coffee shop to coffee shop indulging in a 8oz quad lattes, strong black coffee, or probably a shot in the dark. So when I set out to blog about the new Google Maps Lite API it was pretty obvious what I needed to do… create an app showing me the closest coffee shops around me. In that moment Coffee Filter was born! What was interesting to me and hopefully to you was how I was able to think up Coffee Filter, design, implement, test, and ship to Google Play in under 48 hours. More than half of those hours I was either asleep or on a plane! Let’s take a look at how it was created.

Material Design First

I immediately knew I wanted to use AppCompat and leverage material design as much as I could. I followed my own blog post on how to integrate Support v7 into my app and re-used all of the styles and colors xml. This was pretty tedious to setup and made me question why there aren’t project templates for these…. aka I know what I am doing this weekend :) 

Next was choosing my material palette and integrating different assets. I immediately went to http://www.materialpalette.com/, which is an amazing resource to help you put some colors together for your app. Then I headed over to the Android Asset Studio, every Android developers #1 bookmark, to generate a few icons for the app. If you are looking for some inspiration be sure to check out http://www.materialup.com for awesome material designs.

Tight Code Challenge

Monday night couldn’t have ended better. I got to sit down at my favorite restaurant, Thai Tom, to indulge in a Pad Thai Chicken with one my best friends Frank Krueger. I told Frank about Coffee Filter and my current UI design with Google Maps Lite and I could tell ideas were igniting in his brilliant mind. He enhanced my currenty UI idea with a new enhancement of flipping through coffee locations with a map hiding behind them. The UI would mostly be informational with nice large fonts telling me where to go get coffee. However, what Frank said next was very interesting, which was that he challenging me to write Coffee Filter in as little lines of code as possible. That meant no big MVVM framework, not over architected, just go go go. 

I took this challenge mostly to heart and didn’t introduce any data binding or IPropertyChanged notifications. I still separated out my Models and View Models into a nice re-usable section, but just didn’t add any framework into the mix. The entire app is actually around 650 lines of code including using statements and comments, which to me is very impressive.

Plugins for Xamarin

The reason for nice tight code was actually because of plugins. Plugins abstract away a bunch of cross platform functionality, which is where most of the code actually lives, so I didn’t have to write it. When I started writing plugins for Xamarin a while back I didn’t know how often I would actually use my own, but I found immediate use of three:

Get the App & the Code

My favorite part of Android development is being able to package up an app and have it on Google Play within two hours. This means that yes, Coffee Filter is available right now: https://play.google.com/store/apps/details?id=com.refractored.coffeefilter. Of course you know I love open source, so you can grab the code for Coffee Filter on GitHub: https://github.com/jamesmontemagno/Coffee-Filter. It even includes some brand new Xamarin.UITests that can be run on a simulator or Test Cloud, which is pretty awesome. I am not done yet with Coffee Filter though as I will be adding more details to each coffee shop, refactoring, taking feedback, fixing bugs, and of course leveraging my shared code with iOS.

March 05, 2015 5:23 GMT

Nearest Bus Post Mortem Part 4: Today Extension

This is a multipart post-mortem-style post series on the design and development of Nearest Bus. I'm planning on covering the architecture, design, code, widget (this post) and possibly some on adding a watchkit app, once I finish that off.

My wife has long joked that Nearest Bus should be called "Run or walk", as I'd usually check it when we were around the corner from the bus stop - should we be running to the stop, or did we have time to keep walking?

However, unlocking my phone, finding and loading the app, waiting for it to find the stop and load it, it all takes time.

In iOS8, Apple added Extensions, which allow you to build your own keyboards, sharing extensions, and Today Extensions, which sit in the "Today" notification area than you can pull down from the top of the screen. It's an area which is designed for glanceable data - fast to load, specific to the user or the users current situation, and usually small.

Today Extension

Pretty much perfect for showing when the bus is coming!

Xamarin have added support for Extensions (I prefer Widget, but that's the proper name I think), so it was fairly easy to fire up a new Extension and reuse the common library. The focus of the extension is to show the nearest 4 favourite bus stops, and only show the route and times.

At it's core, a widget is a seperate app, which is contained within your existing app, but only for packaging purposes. It has it's own assets, it's own binary, everything. The only thing they can share with the host app bundle is code, by using a shared library, but the Xamarin model doesn't yet support iOS shared libraries (which is also only supported on iOS8), so you have to duplicate your code in 2 binaries.

From a .NET point of view, tho, this is easy! Just make a new assembly, and import it into both the app and the extension. Easy. Well, almost: more on that in a moment.

Preferences (NSUserDefaults) can be shared by an App Group, and the Keychain is also available. You can also setup a shared folder to move data between your app and the extension, tho I dont use that in this app.

//this has to be setup in the mobileprofile
const string groupId = "group.com.bigtedltd.NearestBus";  
NSUserDefaults GroupedDefaults {  
    get {
        return new NSUserDefaults (groupId, NSUserDefaultsType.SuiteName);

void LoadFavourites () {  
    using (var defaults = GroupedDefaults) {
        string defaultsJson = defaults.StringForKey ("favourites");

Every time the user pulls down the today notification area, your main UIViewController is recreated and restarted, so make sure any state is kept out of this main ViewController, and can be recreated if the app is killed outright. After it's create, the WidgetCallback is called.

[Export ("widgetPerformUpdateWithCompletionHandler:")]
public void WidgetPerformUpdate (Action<NCUpdateResult> completionHandler)  
    //Do stuff that we have to to each time the app is loaded
    if (TodayViewModel.SharedInstance.Location.LastFoundLocation != null) {
        LoadFromLocation(//last lat and lon);
    } else {
        ReloadCollectionView ();
    //Tell the OS we have something to show. Or nothing. Or an error.
    // ONLY call this once.
    completionHandler (NCUpdateResult.NewData);

This is the "main method" for the widget, in which you can start updates, and eventually tell the OS that you have something - or nothing - to display. The general process is:

  • OS shows the last state of your wiget as a static image
  • Create
  • WidgetCallback is called
  • You work out if you have something to update (something, nothing, error). The screen is updated as needed

You can keep changing the screen after you tell the OS that you have new data - eg animations, or moving things around and updating labels - but if you say "no new data", then the previous image is left there.

Be sure to only call the callback once, and if possible, AFTER you have finished updating the UI. Things get a bit weird if you don't.

Designing a widget is pretty simple. You have a base storyboard, on which you can put anything which doesn't scroll vertically (and Apple recommends not scrolling horizontally either), and then .... go nuts!

Widget Storyboard

I've used a UICollectionView, which is the same class I use in the main app. UICollectionView is pretty much UITableView 2.0, with a lot of the crappy bits removed and fixed.

As your widget can't scroll vertically itself, you can resize the collection view to wrap it's content easily:

public void ReloadCollectionView ()  
    //Do other stuff, then set the PreferredContentSize
    //StopList is my UICollectionView
    PreferredContentSize = StopList.ContentSize;


[Export ("widgetMarginInsetsForProposedMarginInsets:")]
public UIEdgeInsets GetWidgetMarginInsets (UIEdgeInsets defaultMarginInsets)  
    //remove the border. Go full width.
    return new UIEdgeInsets (0, 10, 0, 0);

Working within a widget container has a few constraints, however. The main one is that you are limited to 16MB of memory use. This is a hard limit - a VERY hard limit. If you go over, you are immediately killed. This can be quite difficult to keep within, so keep you images small (prescale them), make good use of text data rather than image data, and architect your app in such a way that anything which isn't needed isn't included.

This last point is especially important for me. I was pulling in Sqlite for the AT data, but I didn't actually use it in the Widget - the data all comes from the favourites, which is just a JSON serialsed blob, so I'm not looking anything up in Sqlite.

So I moved the sqlite-using ATStopProvider into a seperate shared library, which is only used by the app, and removed the dependancy on sqlite from the core shared library. Only one is registered with the IOC container on startup. That stopped me getting killed quite as much, tho I think I'm very close to the limit as it is.

One of the other advantages of creating a widget at this point is that it should be fairly easy to create a WatchKit app down the road a little - and having the bus info as a glanceable screen on the watch would be ideal!

A WatchKit app is just another extension - they work exactly the same as a Today Extension, and the code runs on the phone, with the display "remoting" to the watch. I'll post more once I have the watch app working, as Xamarin now have (Alpha) support for WatchKit and iOS 8.2 apps.

I need to get my head around WatchKit UI design, too, before I start on this. It might have to wait until after the watch is released.

March 04, 2015 5:28 GMT

Nearest Bus Post Mortem Part 3: Code

This is a multipart post-mortem-style post series on the design and development of Nearest Bus. I'm planning on covering the architecture, design, code (this post), widget and possibly some on adding a watchkit app, once I finish that off.

Ah yes. The code part. I've not really covered it, but, from reading almost anything I've written in the past, you'd know I use and love the Xamarin set of tools - Xamarin.iOS in this case. This app is no exception - C# is still my native language, even tho I spend 8+ hours a day writing either Java or Objective C.

As I started this rewrite from scratch, I could have used this as a Swift learning exercise, however I'm not overly enamoured with Swift yet. I think it'll be big - it will replace Objective-C on iOS - but it's just not cooked enough yet. The spec keeps changing, it doesn't fit into Cocoa very well yet, and most of the "wow" features I've seen so far have been in other languages - C# mostly - for a number of years.

Yes, it's more functional than Objective-C, but adding a .map and .reduce method, and lambdas, doesn't make it a "functional language". Go look at Scala or F#.

Objective-C is growing on me, too, with a few exceptions which could be fixed by a better IDE (eg, merge .h/.m in the IDE). AppCode, which I use every day, goes a long way, but it's still not quite there.

I made a decision early on to move from code-driven UI to storyboards. They are now Apple's recommended way of doing things, and unless you are a bit careless with your merging, they are pretty easy to deal with in Git. Nearest Bus is a pretty simple app - there are only 6 scenes in the storyboard, and only one developer - so it made sense. It also gave me an easy route to support multiple screen sizes (iPhone 4S, 5(S), 6, 6+) without much extra work.


Xamarin Studio comes with it's own Storyboard designer, but I chose not to use it - this was, to some degree, an exercise in learning more about Auto Layout and how it works in Xcode (poorly, it seams), so I can apply that to the day job. I can't attest to how good the Xamarin one is - or isn't - but it looks quite complete from a small amount of experimentation. Switching between then, however didn't work for me - the generated code isn't the same. The Xcode integration works well enough, however.

I chose not to use Size Classes on this project, but I could have done easily enough. Pretty much every element is full screen - or full-parent - so aside from resizing some of the cells so that they cover the whole screen, everything else was just normal Auto Layout.

Animations, while not the full Material Design type, were a bit of a focus for this app, and ended up being fair easy to do. I wanted a way of doing a progress indicator - whats the app doing while it's loading - and having the text fly in from the right, and exit via the left, with the icons dropping into the middle then falling to the bottom is quite a good way to convey this. It works better with the London data than the Auckland, as London uses 2 distinct steps - find location, and get stops over the network. The Auckland one really only has one step - find location - which takes any time. Getting the stops is a simple SQLite query, which takes only a few 10's of ms. The stops then load asynchronously as the user is looking at them in the card view.

Animation of the loading screen

Animation using Auto Layout constraints is pretty easy - just expose the constraint you want to change from the Storyboard, as you would with any other outlet, and manipulate its constant inside an animation block. Then call LayoutIfNeeded() at the end of the animation block, and it'll animate like normal.

AnimateEverythingOut ();

UIView.Animate (0.5, () => {
}, () => {
    MessageHelper.Hub.PublishAsync (new RefreshLocationMessage (this));

nfloat IconHeight = 40;
nfloat LabelWidth = 300;

void AnimateEverythingOut() 
    FindYouLocationCenterConstraint.Constant = -(UIScreen.MainScreen.Bounds.Width + LabelWidth);
    LoadingBusInfoCenterConstraint.Constant = -(UIScreen.MainScreen.Bounds.Width + LabelWidth);

    FindYourLocationIconCenterConstraint.Constant = UIScreen.MainScreen.Bounds.Height + IconHeight;
    LoadingBusInfoIconCenterConstraint.Constant = UIScreen.MainScreen.Bounds.Height + IconHeight;

void AnimateFindYourLocationIn() 
    FindYouLocationCenterConstraint.Constant = 0;
    FindYourLocationIconCenterConstraint.Constant = 0;

void AnimateFindYourLocationOut()
    FindYouLocationCenterConstraint.Constant = UIScreen.MainScreen.Bounds.Width + LabelWidth;
    FindYourLocationIconCenterConstraint.Constant = -(UIScreen.MainScreen.Bounds.Height + IconHeight);

I'm still working out and researching how to do some of the Material Design animations, especially the action button transforming into a full screen one. If you have any ideas, please share them.

Inside the app, all communication up the stack (from the bottom to the UI) is done with message passing. TinyMessenger provides an easy way to post a message and receive it in another part of the app. I found it's Unsubscribe call to be a bit flakey (basically, it didn't unsubscribe, so I ended up getting multiple calls to a given handler), but other than that, it works. I'd like to look at what Otto is doing in the Android space, and possibly use that approach, eg:

public void DoReactToMessage(SomeMessage message) {}

public void DoSomeOtherMessage(SystemMessage message) {}

Rather than attaching a lambda. Or maybe I should just fix TinyMessenger, as it works great otherwise.

For top down (the UI pulling things up from below), I've used a fairly normal IOC resolver

var favouriteProvider = MessageHelper.Container.Resolve<IFavouriteProvider>();

This even lets me register multiple providers, and just check if they are valid before using them (eg, AT and TfL will never be active at the same time).

This has it's own problems, as I then have double the code I need in memory - especially problematic in the very restrictive memory environment of a Today Extension. I need a way to unregister a class/type, which is something I may need to add to TinyIOC, so I can register the TfL provider, and have it deregister itself if it's not valid for use. Otherwise, I may have 10 providers in memory at a time, but only 1 is valid for use. Another option would be to have the first ILocationProvider register the appropriate handlers, as the user is not likely to switch cities with the app running.

I would have liked to look at using ReactiveUI in some way, but I ended up not doing so, mostly in an effort to ship the app, rather than just play with a new technology. That might come in a later rework, as I like the idea of Reactive, and I don't grok it enough yet.

Shot of the tip jar

One of the cheeky features of the app is a Tip Jar, using In App Purchase (IAP). I was previously charging 69p (99c) for the app, but there were only a few sales every day, so I decided to find out how much interest there was without the cost - the answer being around 50x the interest! So I wanted to keep the app free to have as many people use it as possible, but still let them pay for it if they want to. Hence, the Tip Jar.

A few people have asked "Does apple allow this?". At the moment, they do, however I'm very clear in the UI that they are putting money in a tip jar, not actually buying something or unlocking some feature.

iOS provides StoreKit to do IAP, and Xamarin have a wrapper around this called Xamarin.InAppPurchase. It's an iOS-only component (which I suspect is why isn't not part of Xamarin.Mobile), and it makes doing IAP very easy, with a simple C# event model.

You basically setup your PurchaseManager, fire it some product id's to use, tell it to go get them from the store (it calls you back with the ones it got), and you call BuyProduct passing the product instance in.

The rest of the setup is normal IAP - you have to load the ID, name and price into iTunes Connect, and have it approved by Apple.

Once the user has done their thing, you get a callback saying it's done, with the receipt, or a call to the error handler to say it didn't work. It can even simulate the Appstore, as you can't use it in the iOS simulator (it has to be on a real device).

IAP has become a lot easier, too, with the use of TestFlight. If your app is being tested via TestFlight, your users can buy as many smurfberries as they like, and they will not be charged. By the same token, once the app is out of beta, they also will not get to keep things they bought. It makes the process of testing IAP really easy.

One of the things which tripped me up in the previous version of Nearest Bus was having too many event handlers attached to the singleton/static PurchaseManager. This time around, I've used methods rather than lambdas, so I can deregister the handlers when the IAP screen closes. So far, so good (but I wish .NET event handlers had an official way to say "clear all")

Some of the other components I'm using (either from NuGet or the Xamarin Component Store) are:

  • sqlite-net, which is my go-to micro-ORM. It's used for the AT stops database, which is preloaded from their Google Transit data
  • ModernHttpClient, which allows me to use HttpClient, but backend is on NSUrlSession (or OkHttp on Android)
  • TinyIOC and TinyMessenger.
  • NewtonSoft's Json.Net, which is pretty much the standard for Json these days. I need to have a look at SimpleJson, tho, and see if it's (lack of) size will give me some memory back.
  • Xamarin Insights for analytics and crashreporting. It still a "work in progress", but it's functional for what I need. If you need more - especially cross language or mobile and web, go look at RayGun.io

In the last part (for the moment) I'm going to specifically look at the Today Extension (aka Widget), as that was also a major reason for rewriting the app.

March 03, 2015 10:21 GMT

FREAKy - SSL kind of broken in iOS, Android etc

Ars Technica:

The weak 512-bit keys are a vestige of the 1990s, when the Clinton administration required weak keys to be used in any software or hardware that was exported out of the US. To satisfy the requirement, many manufacturers designed products that offered commercial-grade keys when used in the US and export-grade keys when used elsewhere. Many engineers abandoned the regimen once the exports restrictions were dropped, but somehow the ciphers have managed to live on a select but significant number of end-user devices and servers.

If there is a backdoor, it will be found. Thanks, paranoid post-cold-war American government.

This is more of a worry, tho, especially if you have a non-Google Android phone (ie, Samsung, HTC et al)

An Apple spokesman said the company plans to issue patches for iOS and OS X next week. A Google spokeswoman said an Android patch has already been distributed to partners. In the meantime, Google is calling on all websites to disable support for export certificates.

iOS: next week. Android: um, when the partners and carriers feel like it. So.... never. Or ages away. But most likely never.

More technical background on it here.

March 03, 2015 5:23 GMT

Nearest Bus Post Mortem Part 2: Design

This is a multipart post-mortem-style post series on the design and development of Nearest Bus. I'm planning on covering the architecture, design (this post), code, widget and possibly some on adding a WatchKit app, once I finish that off.

I mentioned some of the design decisions and priorities for the design of Nearest Bus in the overview. The main driving priority is

The app must be quick to use. I'm standing at a bus in the dark and it's raining, when's the bus coming?

Secondary to that is accessibility, which is an extension of the primary priority, but to people with visual impairments. Everything else follows these priorities. The look, feel, layout, and all other decisions.

For the functional and visual design, I have been quite taken by Googles Material Design language, which they have introduced recently in Android 5 / Lollipop. I like the ideas behind it, the concept of data sitting on pieces of "magic paper" and then manipulating the paper in 3D space. The use of 3D is subtle - unlike the older pre-iOS7 design style - and it makes sense to me as way to manipulate data which is sitting, otherwise flat, on a two dimensional surface.

Materials Video from Google

To be honest, I find my reaction to Material to be a bit of a surprise. On an Android phone - Nexus 4 in my case - I find Material to be a bit bland and flat. On a Nexus 5, it's just "ok". But put the same design principles on an iOS device - Google Maps and Hangouts especially - and it's lovely. I wonder if it's something to do with the screens, colour reproductions or fonts on iOS being that much better - or just more pleasing and familiar to my eye.

On the opposite side of design, I use a Samsung S4 (or S5) for development at work. It feels like going back to Windows XP after using Windows 7 - a dumbed down Fisher Price interface with poor fonts and poorly thought out, garish colours. I wish any provider who used the "official" Android (not AOSP) was forced to release a ROM with just stock Android. Google has a few for some devices, but not nearly enough.

The app itself consists of only a few scenes in the storyboard


  • The loading sequence, telling the user thats going on
  • The list of stops, implemented as a UICollectionView, which can be swiped from left to right. The user can interact with the buttons on the bottom (refresh, favourite, map) and the global information button at the top, as well as scroll the list of stops in the middle
  • The map, which shows the location of the stops around the user
  • And a summary / app info screen, which doubles as the tip jar.

The app is put together with a single storyboard, which segues between the scenes. That allowed for very rapid iteration on the design, and I was able to get a non-functional (no real data), but usable prototype up very quickly.

As it often is, Auto Layout was both a blessing and a curse. It's allowed the app to work on everything from a 4S up to a 6+, but there are some bugs in it which are a bit frustrating, and the UI in Xcode leaves a lot to be desired.

Overall, its a lot better than doing the layout in code tho, which is how the old app used to work.

I've not gone fully in on the material design tho - the main missing part is in the animations. iOS doesn't have some of the animations pre-canned, unlike Android, so I elected to use some more basic animations like a simple crossfade for view transitions, or location-based animation (fly in, fly out etc). I may end up using this app as a test bed for animations, tho - having the map screen fly out of the map button would be nice to implement, even if it never ships.

Materials Animations

Animation Inbox + Material Design from Jovie Brett.

I'd like to add an Action Button system to the app tho - I'm using a similar metaphor with the top info button which is persistent between stop screens, but if I follow materials design, it should be in the bottom right, where the map button is. That might need a bit more thought.

For the look, I did the assets in Sketch, which is very easy to use for most mobile assets. It's easy to draw at @1x resolution, then scale up without losing quality to @2x and @3x.

I can't recommend Sketch enough, it's worth investing the time in learning how to use it, even if you are "not a designer", like me. Meng To' course Learn Sketch 3, on using Sketch and Xcode, is worth getting if you are totally new to it. It covers both the design side, as well as coding, so it's quite suitable for developers wanting to learn design, and designers who want to learn some code.

For bitmap editing - and I didn't do much of that in this app - I've fully switched over to Pixelmator, from Photoshop. The main reason was cost: I needed a photo editor on both my laptops, and we only had one Photoshop license (you can install PS on 2 machines - Leonie had one already as she uses Photoshop a lot more than me, for actual photo editing).

Pixelmator took a bit of getting used to - I've been a Photoshop user since the mid-90's - but it was worth persisting with. It doesn't have every bell and whistle of Photoshop, but it has enough to be a replacement for me, and I still only use a small percentage of what it can do.

Remember the complaint of "Microsoft Word would be so much better if it only had the bits I needed" - well, Pixelmator is like that, vrs Photoshop.

For $130 (USD), total, you can get all the design tools you need. Bargain.

One feature I wanted to add - and will in a future version - is a view of the favourites, from nearest to furthest. It's not as important in London, where there is only a few areas which have a very high concentration of stops (eg Hammersmith Bus Station only has about 8 stops), where as Auckland has a much, much higher concentration in areas like Britomart Bus Depot.

The main reason I've not put it in yet is I've not worked out how to fit it in. I'd need to change how the info button works, most likely, or add a 4th button to the bottom, which I don't want to do. I'm still throwing around the how and where.

In the next part, I'm going to look at the code, and how the app is put together.

March 03, 2015 3:33 GMT

Newsletter Name Change

A little over 6 months ago, I started the XamarinWeekly newsletter and it’s been a hit with the community. Unfortunately during that time, I did not read Xamarin Inc. branding guidelines. The domain name and the hexagon logo I created are not exactly within guidelines.

To rectify my guideline transgressions, this weekend I registered a new domain name (WeeklyXamarin.com) and created a new logo. I then transferred the domain, website, MailChimp account and Twitter account over to the new branding and URL.


Newsletter subscribers will be seeing the new logo and name on this week’s newsletter. Subscribers don’t have to lift a finger; the newsletter will be delivered to their inbox promptly Friday morning.

I want to thank Xamarin for working with me during the name change and supporting our community efforts. Thank you.

The post Newsletter Name Change appeared first on Syntax is my UI.