Community Blogs

April 17, 2014 9:27 GMT

Interactive App Product Tours

By

One of the most important metrics in app development is the retention rate. Unfortunately, often we don't pay much attention to metrics like these in the hustle of designing, developing, and marketing our app. In fact, when testing my own app, Verses, one thing I noticed is that users were having issues learning to use the app. inspireUX lists six ways to help you implement help design patterns to alleviate these issues. While most of these are suitable options, walkthroughs are my favorite. Rather than showing the user what to do, have them do it themselves.

Some people say an app's user experience should be so carefully crafted that it is an entirely intuitive process to learn how to use it. However, I disagree. Think of some of the best apps you've ever used. For me, Tweetbot comes to mind. After a short overview, we are presented with a walkthrough tutorial. OmniFocus, one of the most popular productive apps in use today also utilizes a walkthrough. It's hard to retain users regardless of design or feature set if they don't know how to use your app. The solution is simple: teach them.

Introducing CRProductTour

Quickly and easily build interactive product tours or walkthroughs for your Xamarin.iOS apps with CRProductTour.

Sound awesome? Get it from GitHub.

Demo

Create "bubbles" for each UIView you wish to draw attention to and add them to the product tour. That simple. Even better, CRProductTour is 100% customizable. You can change the font of the bubble, the font size, the background color, the text color, and pretty much everything else you can think of.

Special Thanks

  • Clément Raussin wrote the original library in Objective-C. As always, he is deserving of some love if you decide to use this in any of your apps.
  • Luigi Saggese for alerting me to the existence of this library after what seems like an exhaustive search for something similar. Thanks :)
April 17, 2014 4:15 GMT

Part 2: My StepCounter Android: Step Counting in a Bound Service

By
In Step 1 of bringing My StepCounter to Android I investigate the raw sensor APIs available in Android. It was extremely nice to see that it was easy to tap into the step counter and detectors by simply implementing: ISensorEventListener and register for events. In my first example I was doing this all in my Main Activity, which seems like it would be alright if I was using step counter since it would return a total count since I registered for events, but I would have no way of detecting the current day, if the phone was reset, and just how accurate this data was. So this means that I need to have a background service running so my application can constantly be receiving notifications that steps have been happening.

Services have a few ways of notifying applications that data has changed. We can either use a broadcast and a receiver to parse the data or we can create a bound service from our main activity. The latter is what we will want to do as I don’t trust the speed of the broadcast receiver compared to a nice bound service which gives our activity full access to the services properties. This is sort of what it looks like:



Luckily the Xamarin documents have great documentation on bound services so it was really easy to implement. We need to create 3 different things:
  • StepServiceBinder: Is set in our activity when it requests a BoundService and gives it access to the Service
  • StepServiceConnection: Our activity starts a connection which does the binding to the ServiceBinder.
  • StepService: This is our service, now doing all the processing!


This code is pretty straight forward actually, which all it does is pass in a reference to the service or a reference to the activity which it wants to bind to:



Our service now is pretty powerful and doesn’t have to do anything special to become a bound service, it will just automatically bind. However one thing that I wanted to have happen was for my Main Activity to be able to get property change notifications so it knows when to update the UI when we step. So all I needed to do was have my Service implement INotifyPropertyChanged and I created a public property called StepsToday which will have an up to date count of total steps taken:



Now all I had to do was go back to my MainActivity and OnStart I will attempt to bind to my service, OnStop will unbind, and when my StepServiceBinder gets set from the StepServiceConnection I will register for PropertyChangedNotifications:



And there you have it I am now able to get property changed notifications from my background service! Now of course I will want to start this service when the Activity starts, but I will also want to start the service when the user reboots their phone so I don’t loose any information. I will need to give my app it’s only permission it required which is ReceiveBootCompleted:



Then I will go ahead and create a boot receiver which will start my service automatically:



I am all set, now just to calculate proper steps and animate the UI!

If you want to learn more about bound services please watch Nina Vyedin video from Monkey Space.

Backgrounding/Multitasking in Mobile - Nina Vyedin from Monkey Square on Vimeo.

April 17, 2014 12:56 GMT

Easy In App Purchases for iOS

By

Xamarin.iOS makes it easy to use Apple’s StoreKit API to include In App Purchasing in our iOS mobile applications. However, there’s quite a bit of repetitive code that has to be created for every app that includes it.

That’s where the new Xamarin.InAppPurchase component can help!

Xamarin.InAppPurchase in Use

Using Xamarin.InAppPurchase, we can easily and quickly add iTunes App Store In App Purchasing of products, features or subscriptions to our iOS mobile applications. All without any of the repetitive code required when calling StoreKit directly.

Working with Product Identifiers

By decorating our Product Identifiers with specific keywords, we can have Xamarin.InAppPuchase automatically handle things such as the product type, subscription duration, consumable quantities and downloading of hosted content from the iTunes App Store.

For example, we can use product.nonconsumable to define a non-consumable product, gold.coins.consumable_x25 a consumable package of 25 gold coins, magazine.subscription.duration1month an auto renewing monthly subscription and antivirus.nonrenewingsubscription.duration6months a non-renewing six month subscription.

So let’s take a look at how easy it is to get a list of available In App Products from the iTunes App Store with Xamarin.InAppPurchase by using the following code:

using Xamarin.InAppPurchase;
using Xamarin.InAppPurchase.Utilities;
...
public InAppPurchaseManager PurchaseManager = new InAppPurchaseManager ();
...
// Ask the iTunes App Store to return information about available In App Products for sale
PurchaseManager.QueryInventory (new string[] {
"product.nonconsumable",
"gold.coins.consumable_x25",
"newsletter.freesubscription",
"magazine.subscription.duration1month",
"antivirus.nonrenewingsubscription.duration6months",
"content.nonconsumable.downloadable",
});

After this code runs, the PurchaseManager will contain a list of any valid products with all of the localized information read from the iTunes App Store, ready for us to display to the end user.

When the user is ready to buy a given item, we can use the following code to start the purchase process with the iTunes App Store:

// Ask iTunes App Store to purchase product
PurchaseManager.BuyProduct (Product);

We can then monitor several of the events exposed by the PurchaseManager to update the app’s UI or activate new content or features. At any time we can ask if a given product has been purchased using:

// Was the feature purchased?
if (PurchaseManager.ProductPurchased("my.nonconsumabe.feature")) {
...
}

In addition, Xamarin.InAppPurchase will automatically track our consumable product quantities and subscription expiration dates and provides methods to work with them easily.

Secure Automatic Persistence

The Xamarin.InAppPurchase component includes ways to automatically and securely persist the user’s purchased products. This information can be stored either to the app’s user preferences, a local file, iCloud, or our own custom persistence methods.

Now, let’s look at restoring previous purchase history that has been automatically saved by the Xamarin.InAppPurchase component. We’ll add the following code before our call to QueryInventory above:

// Setup automatic purchase persistence and load any previous purchases
PurchaseManager.automaticPersistenceType = InAppPurchasePersistenceType.LocalFile;
PurchaseManager.PersistenceFilename = "AtomicData";
PurchaseManager.shuffleProductsOnPersistence = false;
PurchaseManager.RestoreProducts ();

With this code in place the Xamarin.InAppPurchase component automatically saves any changes to the user’s purchased products and restores that history when our iOS app starts.

Simulating the iTunes App Store

There are several situations that can arise when working with In App Purchases, many of which can be hard to test for. The Xamarin.InAppPurchase component provides the ability to simulate interaction with the iTunes App Store so we can fully test out our application. This helps to ensure and provide a smooth, issue free In App Purchase experience for our users.

Xamarin.InAppPurchase running in simulation

When running in the simulation mode, decorate your product identifiers with specific keywords to test such things as invalid product IDs, failed purchases, hosted content download, etc. You can even test products before they are added to iTunes Connect and can test In App Purchases inside the iOS Simulator on a Mac.

Let’s look at how easy it is to run the Xamarin.InAppPurchase component in the simulation mode. We’ll modify our code above to look like the following:

// Initialize the purchase manager
PurchaseManager.simulateiTunesAppStore = true;
...
// Ask the iTunes App Store to return information about available In App Products for sale
PurchaseManager.QueryInventory (new string[] {
    "product.nonconsumable",
    "feature.nonconsumable",
    "feature.nonconsumable.fail",
    "gold.coins.consumable_x25",
    "gold.coins.consumable_x50",
    "gold.coins.consumable_x100",
    "newsletter.freesubscription",
    "magazine.subscription.duration1month",
    "antivirus.nonrenewingsubscription.duration6months",
    "antivirus.nonrenewingsubscription.duration1year",
    "product.nonconsumable.invalid",
    "content.nonconsumable.downloadable",
    "content.nonconsumable.downloadfail",
    "content.nonconsumable.downloadupdate"
});
...
// Setup the list of simulated purchases to restore when doing a simulated restore of purchases
// from the iTunes App Store
PurchaseManager.simulatedRestoredPurchaseProducts = "product.nonconsumable,antivirus.nonrenewingsubscription.duration6months,content.nonconsumable.downloadable";

Now we can run our iOS mobile app and test interactions such as the purchasing of a product failing, downloading of hosted content failing halfway through, or any other event that can happen with In App Purchases.

For more details about the Xamarin.InAppPurchase component and to get a full demo iOS application built using it on the Xamarin Component Store.

April 16, 2014 3:56 GMT

Epic Evolve Sessions

By

Last year, Xamarin Evolve 2013 hosted over 80 training and conference sessions on a vast array of topics. This year will be even bigger. Join us in October for Xamarin Evolve 2014, with a full extra day to make room for even more amazing sessions. If you didn’t get to attend last years conference or just want to catch up on the great sessions that were presented you can watch online right now. Here are just a few of our favorites from Xamarin Evolve 2013 that you don’t want to miss:

How C# Saved My Marriage, Enhanced My Career, and Made Me an Inch Taller

with Scott Hanselman

Multiplatformism: Lessons Learned Bringing Bastion to Six New Platforms

with Andrew Wang

Getting the Most from Xamarin Studio

with Michael Hutchinson

Push Notifications with PushSharp

with Jonathan Dick

Buttons are a Hack

with Josh Clark

If you enjoyed these sessions, we have all the videos from Xamarin Evolve 2013 online. And you definitely don’t want to miss Xamarin Evolve 2014 in October — two full days of training from Xamarin University followed by three days live sessions from Xamarin and Industry experts. Don’t wait, Register for Evolve 2014 today!

April 15, 2014 10:31 GMT

C# Meetups featuring Google Glass, Bluetooth LE & More

By

Community growth continues to be explosive with new Mobile .NET developer groups starting all over the world. This month, we have already seen the inaugural meeting for a new group in Paris, France, and we are pleased to announced two new groups in Tampa Bay, FL and Madison, WI! So, April isn’t over yet as it packed full meetups happing everywhere on vast topics from MvvmCross, Intro to Xamarin, and Bluetooth LE!

Mobile .NET Developers Meetups April 2014

Here are some upcoming Xamarin developer group meetups:

New Group: Tampa Bay Xamarin User Group usa flag

  • Tampa Bay, FL: Wednesday, April 16th 7:00PM
  • First TBXUG Meeting – Intro to Xamarin

Boston Mobile C# Developers Group usa flag

  • Cambridge, MA: Thursday, April 17th 6:30PM
  • Developing for Google GlassChris Hardy, Xamarin

.NET BC canada flag

  • Vancouver, BC: Tuesday, April 22nd 6:00PM
  • Cross Platform Mobile Development for the C# Developer with XamarinJames Montemagno, Xamarin

New Group: Madison Mobile .NET Developers Group us

  • Madison, WI: Wednesday, April 23rd 5:30PM
  • Introduction to Xamarin

Dutch Mobile .NET Developers Group Netherlands flag

  • Aalsmeer, Netherlands: Thursday, April 24th 6:00PM
  • Responsive design and Bluetooth LE

Vancouver .NET Mobile Developers Group Canada

  • Vancouver, BC: Thursday, April 24th 6:30PM
  • Mobile Development Techniques using C# and MvvMCross

Detroit Mobile .Net Users Group us

  • Southfield, MI: Monday, April 28th 6:00PM
  • Build / Xamarin Recap, Humanitarian Toolbox

Sydney Mobile .Net Developers Group Australia Flag

  • Sydney, Australia: Tuesday, April 29th 6:30PM
  • Build 2014 and Cross Platform Visual State Management

If you don’t see your city listed above, don’t worry as new events and developer group meetups are being added frequently on the Xamarin Events forum.

If you are interested in starting a developer group in your city we are here to help you get started. We have tips and trick on staring a developer group, a brand new introduction to Xamarin slide deck, and of course our community sponsorship program to get you on your way. We also want to hear from you so please feel free to send us an email or tweet @XamarinHQ so we can help spread the word and continue to grow the Xamarin community.

April 14, 2014 8:25 GMT

Integrating Localytics

By

With all of the great analytics platforms out there, it's tough to pick the right one. Obviously, there is no silver bullet. It all depends what you are looking for. If you want to integrate analytics with your backend, you may go with something like Azure Mobile Services, Parse, or Buddy. Perhaps you go with a more traditional and familiar provider like Flurry or Google Analytics. For me, I just wanted a simple provider that has straightforward pricing, a beautiful web dashboard, and a simple API without all of the complexities of the usual analytics services. That’s when I found Localytics.

Localytics can take as little as ten minutes to integrate into your Xamarin.iOS app. By default, Localytics doesn't ship an assembly compatable with Xamarin.iOS, so I used Objective Sharpie and bindings to create Xamarin.iOS-capable version.

Get Localytics for Xamarin.iOS Today

Setup

The setup process is the same, regardless of the app you are building. A detailed guide on the setup process can be found in the repository for the binding.

Events

Have you ever seen a promotional line around the following “Over 1,000,000 tasks completed!” for an app? This information can be collected via events. Events can provide valuable insight into what users are doing within your application. You can see what features the users like, as well as the ones they don’t like (or don’t know about).

Integrating events into your application can be done via one line of code:

LocalyticsSession.Shared.TagEvent ("EventName");

Localytics offers a detailed guide on when to use events, as well as some general best practices.

Screen Flow

Screen flow can provide valuable insight into how exactly your users are interfacing with your application. Screen flow can help track down the reasons behind a particular feature being used, or help show that a particular process is too tedious. Again, Localytics outdid themselves. You can integrate screen flow with one line of code (AGAIN!?):

LocalyticsSession.Shared.TagScreen ("FirstViewController");

Localytics is an analytics vendor with a simple API that doesn’t bog me down with tedious information that would be tough to find useful. Many of the integrations are just one line of code, making the entire process of collecting data within your app painless. They even have some marketing APIs you can tap into, though the binding doesn’t support those yet.

April 14, 2014 11:38 GMT

Xamarin Presentation at United Diff

By

meetup

I will be giving a talk on Thursday at Unified Diff (Cardiff, Wales) on Xamarin technologies. If you’re in the area and interested to learn about the benefits of using Xamarin on your next App then please come along.

You can sign up below:

http://www.meetup.com/unified-diff/

I should* be bringing some Xamarin swag (if the postman delivers in time) to give away and will be on hand after to answer any questions you might have.

The post Xamarin Presentation at United Diff appeared first on Mike James.

April 14, 2014 2:36 GMT

Observable UITableViews

By

"Lists are the core mobile interaction." - Nic Wise

If lists are the core mobile interaction, why are they sometimes such a pain to work with? I'm currently building an app for iOS called Verses. The basic premise is to store verses and prayers for later viewing, and to allow for verse memorization at your own pace. Because the app is mostly UITableViews (iOS' concept of lists), I found myself annoyed with everything involved with adding and deleting items. Whenever a new item is added, I have to update the collection holding the item, the database, and the UI. Keeping things in sync is a pain.

Then I found Frank Krueger's ObservableTableViewController. I will never write another app without it. The idea: use C#'s INotifyCollectionChanged to help keep the table in sync with the data source. Even better, I don't have to reload the entire table. When the collection is changed, the corresponding rows are either added or deleted, rather than reloading everything in the table. The result: simple, fast tables.

What does observable even mean?

Simply put, an object is being observed for any changes that alter that object's state. If you have worked with C# for a while, you are probably familiar with an interface called INotifyPropertyChanged. Subscribing clients, often UI objects, are alerted whenever the value of a particular property is changed. There is also a lesser-known (at least to me) interface named INotifyCollectionChanged. As you would probably guess, this alerts subscribing clients whenever a collection implementing the interface is altered, be it with a new addition, deletion, or even an object being moved within the collection.

Okay, so what collections can I use?

You can use pretty much any collection you would like, as long as it implements INotifyCollectionChanged. Frank recommends ObservableCollection<T>, and I agree. If you have experience working with Windows 8 development, chances are you already familiar with this. If not, it works just like any other generic collection you have ever used. The absolute best part is you don't have to change your model at all to support this. ObservableCollection<T>'s constructor takes in any type of IList<T>, so you can seamlessly integrate in your existing model. In fact, that's exactly what I did with Verses.

If you want to use a collection that doesn't implement the interface, that's fine too! You just won't be exposed to the same level of magic.

Demo: "Observe" the Magic

You can observe the magic by downloading the solution from GitHub.

As a high-level overview of the demo, there is a Person class which will serve as our data model. Additionally, there is a PersonTableViewController that inherits from ObservableTableViewController. The former is Frank Krueger's brainchild which contains all of the logic for keeping the data source and table in sync. PersonTableViewSource serves as the table's source, a combination of both the data source and delegate classes. Note that it really doesn't look any different than a typical UITableViewSource.

One of the awesome parts of ObservableCollection<T> is that we don't have to update our model to spit out something compatible with our observable collection. In this example, I assume our model returns a List<T>. (Remember from earlier all this has to do is be an IList<T>.) To get this working with our ObservableCollection, just pass it in as an argument into the constructor of our collection. That's it! Additionally, make sure you assign the DataSource property to your collection so the table knows what data to be observing for changes.

    public PersonTableViewController (List<Person> people)
    {
        data = new ObservableCollection<Person> (people);
        DataSource = data;
    }

If you run the app, you will notice two UIBarButtonItems. The one on the right does exactly as you would expect, it adds an item to the collection. Notice the pure magic. I don't update the data source, reload the table, or worry about anything. I just add the item to the collection and ObservableTableViewController does the heavy lifting.

    void AddItem ()
    {
        data.Add (new Person { Name = "New Person", State = "New State" });
    }

So far I have neglected to talk about asynchronous operations. With Xamarin, I can leverage awesome C# features like the Task Parallel Library in my mobile apps to make them as responsive as possible. What happens when I try to update the collection on another thread?

        Task.Factory.StartNew (() => {
            UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
            Thread.Sleep (2500);
            UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;

            data.Add (new Person { Name = "New Async Person", State = "New State" });
        });

Click the left button on the navigation bar. The activity indicator pops up for a bit, disappears, and the table updates. Notice that you can click the right button and add items synchronously while the asynchronous operation completes. It just works. Magic.

What about sorted lists?

If you have run the demo, chances are you have noticed that the item is just added to the bottom of the UITableView. While this is fine for many apps, others require sorted tables. Not a problem. We just need a collection that meets two requirements:

  1. Implements INotifyCollectionChanged
  2. Keeps the collection sorted

Demo: More Magic

None of the collections packaged in the .NET framework meet both of these requirements for sorted lists. After some googling, I found ObservableSortedList<T> from Roman Starkov. As you would expect, nothing changes with our UI from our previous example. All we have to do is change the types of ObservableCollection<T> to ObservableSortedList<T>. As far as the model is concerned, there are two small changes required:

  1. Implement INotifyPropertyChanged
  2. Implement IComparable

Luckily, both of these are very quick and easy updates to our model. You can see a sample implementation of these on the Person class on GitHub. Change the startup project for the solution by right-clicking Project -> Set as Startup Project. Run the app again and you will see that the items are correctly added in sorted order without reloading the whole table. Awesome!

Wrapping Things Up

You were probably a bit skeptical when I said I will never write another app without it, but as you saw it is very true! By utilizing the feature set already present in C#, we were able to vastly simplifiy the way we write tables on iOS.

Without Frank Krueger's ObservableTableView, obviously this wouldn't be possible. If you plan on using this in your apps, please thank Frank Krueger for his hard work! If you will be utilizing sorted tables, both Frank and Roman Starkov are in need of some love!

Of course, without C# none of this is possible. If you like the idea of writing native, cross-platform apps in C#, Xamarin is your answer. And as always, if you have any questions, comments, or just want to talk, I can be found on Twitter @pierceboggan. Oh, and the comments section is always there as well!

Update: Tons of people on Twitter are pointing out ReactiveUI is great for stuff like this as well.

April 13, 2014 11:57 GMT

Codemania 2014 - Native, Cross platform, Mobile

By

Last week, I talked at Codemania about cross platform mobile apps, and specifically the Xamarin tools. The talk appeared to go well (it's always hard to tell from this side of the stage), and I hope people enjoyed it and want to check out the Xamarin tools.

The slides are here, on speakerdeck

And the code is on github.

If you were at Codemania, and have any feedback (good or bad), feel free to get in touch, either via email or twitter.

Thanks to Ben and Ian for organising (another) awesome conference. I suspect I'll be back next year as an attendee.

April 12, 2014 9:24 GMT

Part 1: My StepCounter Android: Step Sensors

By

In February, my fellow Xamarin Michael James published a wonderful app for iOS called My StepCounter. This app uses the new CoreMotion apis in iOS 7 to track your steps on your iPhone 5s. This isn’t a new concept and there are plenty of devices and apps out there that do step tracking, but what makes My StepCounter special is that Michael gave it a beautiful simplistic UI & beautiful animations. On top of that he created it all to be 100% compatible with Xamarin Starter Edition! This is extremely impressive and demos the power of Starter Edition for anyone to start creating apps in C#.

My StepCounter for iOS


Introduced with Android 4.4 was a new step sensor hardware support, which happens to be supported on my Moto X. So naturally as an Android development lover I wanted to test out these new APIs and create My StepCounter for Android. My goal is pretty simple:

  • Track Daily Steps with new APIs
  • Keep the same look, feel, and animations
  • Maintain Starter Compatibility
  • Maximize code re-use from iOS version
  • Add support for browsing history

So with this in my mind and a Southwest plane ride back from Arizona without internet I started my journey on bring My StepCounter to Android.

Step Counter & Step Detector

Android 4.4 introduced 2 new sensors apis for step tracking:
TYPE_STEP_DETECTOR
This sensor triggers an event each time the user takes a step. Upon each user step, this sensor delivers an event with a value of 1.0 and a timestamp indicating when the step occurred.

TYPE_STEP_COUNTER
This sensor also triggers an event upon each detected step, but instead delivers the total accumulated number of steps since this sensor was first registered by an app.

These 2 types seem extremely similar, but the documentation says something very important:

"Be aware that these two step sensors don’t always deliver the same results. The TYPE_STEP_COUNTER events occur with a higher latency than those from TYPE_STEP_DETECTOR, but that’s because the TYPE_STEP_COUNTER algorithm does more processing to eliminate false positives. So the TYPE_STEP_COUNTER may be slower to deliver events, but its results should be more accurate."

So I wanted to test them out for accuracy. For testing I put my main logic in an Activity, although I know I would probably want to put this in a background service at some point. To be able to get notification sensors I had to implement ISensorEventListener, which has 2 methods in it:
OnAccuracyChanged: called when the accuracy changes.
OnSensorChanged: called when the sensor gets an update.
Before I could start testing out these sensors I wanted to make sure that my app could use them and have a way of detecting if the device my app was running on was compatible. So I had to add a little xml to the AndroidManifest.xml and also created a little helper method:

Now to take advantage of these sensors. I didn’t have to do anything for the accuracy changed since I was not interested in that, but for Sensor changed I had to either increase my step count for the step detector or calculate the total for the step counter so I could test accuracy:

With this code in place the only thing left to do was to register for the sensors. This involves grabbing the SensorManager and attempting to get the default sensor for the specific type and then registering the listener. It has multiple delay types, but normal seems to be the way to go:


Now that my sensors are all setup the last thing to do is put in a little UI to do some testing

Tracking steps with Xamarin.Android


There you have it my very first step counter!…. Alright well it isn’t nearly done at all, but this was just Part 1! Here is what I have mapped out currently on my timeline:
  • Part 2: Step Counting in a Bound Service
  • Part 3: Pretty UI
  • Part 4: Pretty Animations
  • Part 5: Saving Info to ADO.NET Database
  • Part 6: Shipping this app!
April 10, 2014 12:00 GMT

Xamarin Evolve 2014 Registration Now Open

By

Untitled-1We are very excited to announce the opening of registration for Xamarin Evolve 2014, our worldwide developer conference! Join us and fellow developers from October 6-10 in Atlanta, Georgia for the largest cross-platform mobile development event of the year!

Even Bigger!

This year, we’re doubling capacity and adding an extra day of conference sessions to make room for more great content covering mobile development with C#, Visual Studio, and Xamarin Test Cloud. Evolve sessions will cover a range of topics, including game-changing Xamarin product announcements by Nat and Miguel, best practices in mobile user experience design, advanced cross-platform techniques, memory management, real world app case studies from leading companies, secure data integration, lightning talks and so much more.

World-Class Training

Xamarin University LogoAttend two days of training from Xamarin University spanning all topics from mobile development fundamentals to advanced areas such as security and code-sharing strategies.

Learn from Mobile Experts

Over the course of three days you will have the chance to attend an immense amount of live sessions covering all areas of mobile development by industry leaders and experts. The entire Xamarin engineering team will be on-hand for one-on-one mobile coaching to answer questions, debug code, and provide advance.

Xamarin Evolve Welcomes Top Sponsor, Microsoft

We are also delighted to announce today that Microsoft will be joining Evolve 2014 again as our sole Platinum Sponsor. In recent months, Xamarin and Microsoft have partnered globally to help developers build great apps with C#, Visual Studio, and Portable Class Libraries, and this past week, Xamarin joined with Microsoft to launch the .NET Foundation. Together, Xamarin and Microsoft bring C# to 2.6 billion devices, and together we will make Xamarin Evolve 2014 an event you won’t forget.

MicrosoftSponsorEvolve2014

Registration Now Open

Tickets for Xamarin Evolve 2014 our second worldwide developer conference, are officially available for purchase today.

Register Now

Team Xamarin

April 09, 2014 10:36 GMT

Swipe To Refresh added to Android

By

Swipe-to-Refresh animation

Google recently released an update to the Android support library bringing in an exciting new standard implementation of a pattern that they have been progressively introducing through applications such as GMail or Google Now.

This pattern, called swipe-to-refresh, uses an upward pull user feedback to inform the app that a data refresh is requested. This complete another common pattern, infinite scrolling, that instead use a downward movement to load more data.

We have updated our component to expose the new SwipeRefreshLayout class that implements the pattern. To make use of it, simply wrap in your existing Xamarin.Android app layout.

<android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/refresher"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</android.support.v4.widget.SwipeRefreshLayout>

Setting up the SwipeRefreshLayout instance is pretty easy from code. You simply have to define a color scheme and a callback that is invoked when an update operation is requested by the user.

refresher = FindViewById<SwipeRefreshLayout> (Resource.Id.refresher);
refresher.SetColorScheme (Resource.Color.xam_dark_blue,
                          Resource.Color.xam_purple,
                          Resource.Color.xam_gray,
                          Resource.Color.xam_green);
refresher.Refresh += async delegate {
	await forum.FetchItems (clear: true);
	refresher.Refreshing = false;
};

The color scheme can be any set of color or the same color. In any case, the first parameter is also used as the initial feedback bar background.

We have also added a dedicated sample that shows how this code can be integrated in a complete scenario, including a complex layout utilizing fragments.

April 09, 2014 9:31 GMT

OpenSSL “Heartbleed” Update

By

You might have read by now that details of the “Heartbleed” OpenSSL vulnerability were published earlier this week. For those that don’t already know, OpenSSL is a popular, general purpose cryptography library in wide use across the internet. Like nearly every company on the internet, we immediately took audit of our systems, and uncovered some systems using a vulnerable version of OpenSSL. We immediately began updating all Xamarin services that were affected, and as of Tuesday afternoon, no Xamarin systems are subject to this vulnerability.

We have also reissued all HTTPS certificates for all xamarin.com domains with new encryption keys, and have had the previous versions revoked by our issuer, which was also completed Tuesday evening. At this point, we believe that it is extremely unlikely that any of our systems were compromised before we patched OpenSSL; however, for an additional layer of security, we recommend that you take the following steps to safeguard your Xamarin account — especially if you used the same password for your Xamarin account as on other accounts hosted elsewhere:

  1. Sign out of your Xamarin account and then sign back in (you’ll want to do this in the IDE as well)
  2. Change your Xamarin account password

At Xamarin we are committed to your security and privacy. We are continuing to track the issue closely and will keep you up to date if anything new is discovered. For more information on this OpenSSL vulnerability visit www.heartbleed.com

April 09, 2014 11:10 GMT

C#, iOS, and Android Take Center Stage at Build

By

It was an exciting week for .NET developers with a slew of announcements at this years Build conference in San Francisco.

Microsoft Build Sign

The most anticipated Build session of the week hands down was Miguel’s “Go Mobile with C# and Xamarin”, where over 1,500 developers packed the main hall for a chance to see Miguel talk on the transformation of mobile development. The audience loves seeing his live coding session where he used iOS’ CoreImage and Twitter integration to add Sepia filter to an image and tweet it out to the world!

Packed house at Miguel de Icaza's build talk

Continuing to wow the crowd, Miguel unveiled our brand new Xamarin T-shirt Store app enabling developers to try out Xamarin to build their first app to order their very own limited edition C# shirt that he was rocking on stage.

A major highlight of the week was when C#’s lead architect, Anders Hejlsberg, open sourced the .NET Compiler Platform, Roslyn, live on stage. This marked a major milestone allowing developers to gain access to a plethora of information that compilers have about the code we write each day. Immediately after Anders open sourced Roslyn, our own Miguel de Icaza hit the stage to showcase the power of an open sourced Roslyn by compiling code with a modified version of Roslyn running on Mono inside of Xamarin Studio on a Mac!

If Roslyn wasn’t enough, Xamarin took part in the official launch of the .NET Foundation. This new foundation will foster open development, collaboration and community engagement on the .NET platform. Xamarin initial contribution consists of six open source .NET Projects including Mailkit, Mimekit, System.Drawing, and more! We are excited to join other community leaders including Laurent Bugnion, Niels Hartvig, Paul Betts, and other to aid in advancing .NET open source projects..NET Foundation

The excitement for Xamarin, C#, and mobile apps continued throughout the week with an always packed Xamarin booth. Thousands of developers got to chat and get a hands on demo of creating beautiful Android and iOS apps in C#.

Packed Xamarin booth at //Build/

Build wouldn’t be complete without an epic Xamarin party, and this year was no different. Our friends .NET joined us to co-host a mega party in downtown San Francisco. Thousands of developers packed in to get face time with Nat, Miguel, Joseph, and the rest of the Xamarin crew at a party that is not to be forgotten! We want to thank everyone that was able to stop by the party and booth.

Xamarin Build Event at Mezzanine

If you thought that Build was epic, you will absolutely want to join us for Xamarin Evolve, the largest mobile developer conference of the year. Tickets go on sale on April 10th, so make sure to visit the official Evolve website to sign up for details.

April 08, 2014 4:30 GMT

Xamarin.Android SwipeRefreshLayout for #MvvmCross

By

I was very excited to see that the latest version of Support v4 for Android was updated to include as most people would says it a “Pull to Refresh”… or as Google would call it a “SwipeRefreshLayout”. It is now available in the Xamarin.Android Support v4 Component so we should probably take advantage of it! This is actually a really slick Layout that you can make the parent of any 1 layout and when the user swipes down on it you will get notified that you are supposed to refresh the content. This means you can now get rid of all of your refresh icon buttons in your UI and follow the same patterns Google has for their apps that your users will be used to.

Naturally I wanted to implement an MvvmCross version of this since I did an MvvmCross binding for UIRefreshControl on iOS a while back. So the goals here are simple:

1.) Execute an ICommand when someone pulls down to refresh
2.) Bind a bool to begin and end the refreshing spinner

So I created a very very simple MvxSwipeRefreshLayout which you can find the Gist for RIGHT HERE! In addition you will just need to implement a bit of code in your .axml layout and in your code behind to set the Refresh command.

April 08, 2014 12:14 GMT

Native Printing with Android

By

The latest version of Android, KitKat, adds long-awaited printing support to the platform. Android applications can now provide low-level control of print jobs, in addition to print integration for applications incorporating web content. This makes KitKat particularly well-suited to hybrid applications built with Xamarin using Razor templates.

Android KitKat Printing

Printing with a WebView

First let’s look at the easy to use print support offered through the WebView control.

Printing requires 3 steps:

  1. In an Activity, get a reference to the PrintManager system service.
  2. Create an instance of a class that inherits from PrintDocumentAdapter.
  3. Call the PrintManager‘s Print method, passing it the print adapter.

The PrintDocumentAdapter is an abstract class that provides a contract to implement for supplying print content. For web content, the WebView class includes a PrintDocumentAdapter, making printing HTML from a WebView incredibly easy to do:

The following example shows a WebView built using the Android WebView template, which uses Razor as an HTML templating engine:

Android Printing from a Xamarin Razor Template

Although printing can be done using any WebView, integrating printing with Razor and this project template makes it really easy to build a hybrid application that can leverage native features such as KitKat printing.

Printing from the WebView with C# is as simple as adding these 2 lines of code in the activity:

var printMgr = (PrintManager)GetSystemService(Context.PrintService);
printMgr.Print("Razor HMTL Hybrid", webView.CreatePrintDocumentAdapter(), null);

When we call Print Android presents a system dialog, allowing the user to choose the print destination, as shown below:

Android Print Dialog

Custom Print Adapter

To print from native Android views, taking low-level control of the print layout, we can implement our own PrintDocumentAdapter.

For example, let’s say we would like to print the layout from the following screen:

Android Print Activity Low Level

In our implementation of PrintDocumentAdapter, the required methods to implement are:

  • OnLayout – Allows laying out print content based on the PrintAttributes.
  • OnWrite – Allows writing a PDF file with content to print.

In OnLayout, we create a PrintDocumentInfo instance, which contains metadata about the document being printed.

public override void OnLayout (PrintAttributes oldAttributes, PrintAttributes newAttributes,
                               CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras)
{
  document = new PrintedPdfDocument (context, newAttributes);
  CalculateScale (newAttributes);
  var printInfo = new PrintDocumentInfo
    .Builder ("MyPrint.pdf")
    .SetContentType (PrintContentType.Document)
    .SetPageCount (1)
    .Build ();
  callback.OnLayoutFinished (printInfo, true);
}

In OnWrite, we implement the code to draw printed content and write it to the output stream to be printed.

public override void OnWrite (PageRange[] pages, ParcelFileDescriptor destination,
                              CancellationSignal cancellationSignal, WriteResultCallback callback)
{
  PrintedPdfDocument.Page page = document.StartPage (0);
  page.Canvas.Scale (scale, scale);
  view.Draw (page.Canvas);
  document.FinishPage (page);
  WritePrintedPdfDoc (destination);
  document.Close ();
  document.Dispose ();
  callback.OnWriteFinished (pages);
}

Printing with our custom adapter is just like using the WebView‘s adapter. Simply pass an instance of the custom adapter, called GenericPrintAdapter in this case, to the PrintManager‘s Print method:

var printManager = (PrintManager)GetSystemService (Context.PrintService);
var content = FindViewById<LinearLayout> (Resource.Id.linearLayout1);
var printAdapter = new GenericPrintAdapter (this, content);
printManager.Print ("MyPrintJob", printAdapter, null);

When the user clicks print, the same system dialog is displayed. In addition to a local printer, you can select Google Cloud Print or print to a PDF file, resulting in the print shown below:

Android Printed to PDF

The printing support added to KitKat is a much welcome feature that is easy to get started with. You can download the code used in this post from my GitHub repo.

Discuss this post in the Xamarin forums.

April 07, 2014 3:30 GMT

Sennheiser Cuts Development Time by 40% with Xamarin

By

SennheiserlogoSennheiser is a world leader in quality audio experiences.  The company recently launched Sennheiser TeamConnect, an end-to-end enterprise-grade meeting solution that integrates speakers, microphones, and a central control unit.  When it came to the central control unit used by employees to remotely control the telephone line and audio levels of TeamConnect, the company sought simplicity for the product’s user interface.

Rather than creating a physical control panel, the company decided to put the controls into the user’s hands via an iOS app for iPads and iPhones.

Dirk Eismann, the main developer on the project had experience using Apache Flex, PhoneGap, and pure Objective-C for iOS development, but this was the first Xamarin project for him.

Screen Shot 2014-03-24 at 11.27.41 AM

“I knew that Xamarin’s performance advantages over other cross platform tools and its rock-solid support for all of the iOS APIs were just what this project needed.“ Eismann says.

With a long background in Java, and a familiarity with C#, Eismann found it easy to make the transition to Xamarin, and completed the application code within just 6 weeks.

“Xamarin makes it surprisingly easy to do native mobile development,” Eismann says. “I especially liked how concepts common to .NET developers like events and delegates are added on top to the iOS API. This greatly simplifies development for anyone who has worked with .NET code.”

Download the full case study to learn more about the benefits Sennheiser has enjoyed from using Xamarin—including 40% faster development time, precisely mapped APIs, ease of use, and the ability to share code across platforms.

View the Case Study

April 03, 2014 8:51 GMT

Xamarin and Microsoft Launch the .NET Foundation

By

dotnet_logoIt has been an amazing day today. Not only did I have the opportunity to share the stage with the creator of C#, Anders Heljsberg, in the Microsoft Build 2014 day 2 keynote, but we also jointly announced with Microsoft the launch of the .NET Foundation, a newly created entity that will foster open innovation on .NET.

Xamarin contributed six projects to the foundation, and we are excited to be working with Microsoft as we take .NET in this new direction.

Miguel on stag with C# shirt

Microsoft contributed Roslyn to the Foundation, and on stage we demoed Roslyn working on a Mac with the iOS version of our new Xamarin Store App – a beautiful, native app that let’s C# lovers order their own limited edition C# t-shirt for free.  This demo was a great proof point for how open source will help get .NET everywhere.  We are very busy integrating the best bits of Roslyn into our technology stack.

Xamarin is contributing six projects to the .NET Foundation:

  • Xamarin Mobile: a library that exposes a single set of APIs for accessing common mobile device functionality across iOS, Android, and Windows platforms.
  • Xamarin.Auth: A cross-platform API for authenticating users and storing their accounts.
  • Couchbase for .NET: A lightweight, document-oriented (NoSQL), syncable database engine.
  • Xamarin’s System.Drawing:our cross-platform implementation of the familiar drawing API
  • MailKit and MimeKit: robust cross-platform email libraries optimized for mobile.

The .NET Foundation will help accelerate the adoption of .NET across every platform and computing form factor—servers, mobile devices and desktops, and we are very excited for Xamarin to be a part of it.

Check out the Build website to see the recordings of the Day 2 keynote. Tomorrow you should also be able to see a recording of my ”Go Mobile with Xamarin and C#” session.

Miguel and Anders on Stage at build

April 02, 2014 4:45 GMT

SlidingUpPanel port for Xamarin Android!

By
I spent some of my time yesterday on a bit of porting Java to C#, instead of sitting in the sun and drinking beer. I found this pretty neat little library, AndroidSlidingUpPanel, which adds a panel to your app, which slides up from either the bottom or top of your screen. The code itself is very inspired by the innards of SlidingPaneLayout from Support v4.

Anyways, here is a GIF of what it looks like:


Adding to your project is pretty simple. Simply grab it from the Xamarin Component store or if you prefer, you can clone or download it from GitHub, which also has the component, but also the source code. There is a nice sample which will show you how to use this library, but if you just want to get started quickly. Simply add the following code to the AXML layout file you want this panel in:



So the SlidingUpPanelLayout should be the root of your layout, and then it will have two children. First child is your content layout, what your originally had in your layout. The second child is the contents of the panel. Now you are good to go! For more info look at the docs on either the component store or on GitHub!
April 02, 2014 10:00 GMT

Build a Cross-Platform, Mobile Golf App Using C# and Xamarin - MSDN Magazine Article

By

One of the fun things about the return of golf season is participating in tournaments that feature events such as a longest drive contest. In these, a person’s first shot off a designated hole is measured against others in the tournament. The longest drive during the day is declared the winner. However, these contests typically don’t have centralized scoring. If you’re in the first group, you don’t know until after the event is over where your shots stand in relation to everyone else’s. Why not use a mobile phone to record the starting point and ending point of drives and store the information in a cloud-hosted database?

The options for building such an app are many, which can be confusing. In this article, I’ll walk through how I built such an app using the back-end options in Windows Azure and how I handled various issues. I’ll show the code for writing an app for Windows Phone as well as iOS using Xamarin.

Several features were required. The app needed to run across mobile devices and multiple device OSes. It had to be a native app that looked just like all of the others on a device. The back-end server had to be always available, with minimal hassle to the developer (me). The cloud services had to provide as much help as possible in the area of cross-platform development. The back-end database needed to provide some amount of geolocation functionality.

Url: http://msdn.microsoft.com/en-us/magazine/dn630648.aspx

 

Many thanks to Brian Prince, Kevin Darty, Tara Walker, Craig Dunn, and a host of others for reviewing the article

PS. You don't have to go to Build to get this Cross Platform Awesomeness

 

April 01, 2014 6:50 GMT

Xamarin Component Store and NuGet: A Love Story

By

I've published a new set of NuGet packages which allow you to depend on Xamarin Store Components in your NuGet packages. These packages, when installed, will add a Component to the target project.

NuGet Packages that have Component Dependencies

If you're writing an Android library, your code often ends up using one of the Google Support Libraries. This goes well until you attempt to package your library into a NuGet package. What to do with the Support Library? If you include it in the package, it will blow up if the target project is already using the Support Library, and if you don't include it, your library doesn't work unless they include the Support Library manually.

This problem isn't solely on Android either - the same applies for certain libraries on iOS as well, such as Xamarin.Auth or Google Maps for iOS. What do we do?

Add xamstore- references

For several Xamarin Components often used in Libraries, I've created "Shim packages". Here's how to use them:

<?xml version="1.0"?>  
<package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd">  
  <metadata>
    <id>glasslib</id>
    <title>Helper code for Glass Apps</title>
    <version>0.1</version>

    <dependencies>
      <dependency id="xamstore-googleglass" version="1.1" />
    </dependencies>
  </metadata>
</package>  

The package name is always the prefix xamstore-, then the Xamarin Component ID (in the URL of the store page)

Wait, so should I use this in my app?

Nope, you should just right-click on the Components folder like you did before, the only reason to use these packages is if you're a library author. If you're not writing a .nuspec file, you don't need these!

What witchcraft is this??

Shim packages don't actually contain any binaries - they simply contain a .props file which trigger Xamarin to install the listed Component into your project. Unfortunately, instead of being able to just install the component, we have to ask the user to close and reopen the solution - if anyone comes up with a clever way around this, I'd love a Pull Request!

How do I add more?

Send a pull request to paulcbetts/component-store-nupkg-builder

March 30, 2014 8:18 GMT

Filtering ListView with SearchView in Xamarin.Android

By
I recently made a video describing how to add a SearchView to your ActionBar, using the Support v7 package to provide backwards support, all this done in Xamarin.Android! I posted it on the Xamarin Forum's, University section, which I have access to, since I am attending Xamarin University. There were some interesting questions, which I found solutions for and I simply wanted to share them, so I am writing this blog post to do so. For background knowledge take a look at this video, which started this, and I am going to use that as a starting point for this blog post.


So the video, shows a very simple implementation of SearchView, which filters simple string elements feeded into the ArrayAdapter, which already has a nice simple Filter implementation, which simply matches the search query to see if it is contained in the items in the ListView. Now this simple implementation might not be sufficient enough for you, because as soon as you need to show something more complicated in a ListView, you will need to implement your own Adapter. Doing so will also require you to implement your own Filter as the Adapter you implement yourself cannot know what arbitrary data you will present.

SearchView filtering ArrayAdapter

Anyways, enough talk, let us dive into the code. So easy mode as described in the video and gist:

So here the magic happens in the OnCreateOptionsMenu method line 39-58, where we find the ActionBar MenuItem and subscribe to the SearchView's ActionView query changes, which invokes the default Filter in the ArrayAdapter.

Reacting on SearchView Expand/Collapse

One of the questions that popped up was, when having the back Action enabled in the ActionBar when using the SearchView, how do you react to the Expand and Collapse events? This is pretty simple, but might not be that super obvious.

You have to create a class implementing IOnActionExpandListener. In this example I am going to remove the filter from the Adapter when collapsing the SearchView.


To hook it up to the SearchView you have to use the helper class MenuItemCompat, to attach it to the MenuItem which you do in the OnCreateOptionsMenu:

Filtering in custom Adapters

Now the other question was, how do I filter my custom Adapter? Very good question if you ask me. As already mentioned, for that you have to implement your own Filter, as the nature of a custom Adapter is that you present custom stuff. Hence the default Filter implementation cannot know how to filter that. I am just going to replicate what the default Filter does on a string property of the model I am going to present in the ListView.

The final solution can be found on → GitHub

So before we begin I have to warn you that FilterResult which is used to store the filtered values temporarily, expects that the object stored is a Java type. So either your model which you populate your Adapter with has to implement Java.Lang.Object or you will have to wrap your values. I will show you the latter, as it will apply to the more use cases, as you probably cannot and probably do not want to implement Java.Lang.Object in your contracts or whatever you are using to store data in, especially when you are communicating and sharing code between platforms.

To wrap up .NET types with a Java type I am using modified code from this monodroid mailing list thread, which looks like this:




The main difference is that the Java holder object is disposed of immediately when it is converted to a .NET object. Also the comparison in the original source, whether the value was null is unsafe, as it does not take value types into consideration. The object disposal is very useful to keep GREF references down to a minimum. I really don't want the app to run high on memory.

Now with that covered, let us get to the actual Adapter and Filter. I have created a class called Chemical, which has Name and DrawableId property. Which are going to be assigned to a custom view, in the Adapter. Not going to cover View creation here, but this one is pretty simple, really.

So Chemical looks like this:

And the Adapter looks like this:


So I am just going to describe what happens in the custom ChemicalFilter, as the rest of the Adapter is pretty trivial. So first thing is that I have to pop in the reference to the ChemicalsAdapter, because I want to store both the original list of Chemicals and the filtered version in the Adapter, so we always can go back to the state we started at. So I always look for matches in the _originalData field, which is looped and matched, lower case, if the Chemical contains anything in the ICharSequence which is passed into the PerformFiltering method. The ICharSequence is just a spartan Java interface providing some simple methods such as lenght, getting a char at at specific position and a sub sequence of chars, nothing too fancy. I simply convert that to a string and match against the Chemical Name property. So the results of that matching is transformed into an array of Java objects, with help of the modifier .NET to Java wrapper I described above using a bit of LINQ. This is done since FilterResults expects an array of Java objects. I also call Dispose on the ICharSquence, as it seems like not doing so builds up the GREF count.

Now in PublishResults the values are converted back to the Chemical .NET type also using a bit of LINQ. The results are set in the Adapter's _item field and the Adapter is notified of the changes in the data set. Both arguments are Disposed of.

So, this is pretty simple stuff. It is just the conversion from Java to .NET and the other way around that can cause some troubles. So just keep in mind, that if your GREF count is rising, then you should probably look into Disposing of some of your stuff.

Again the final solution can be found on → GitHub
March 30, 2014 3:31 GMT

Xamarin.Android Templates Pack!

By

Xamarin.Android already ships with a bunch of great project templates for Visual Studio, however I find that there are a few things missing. I usually start a new project with a Navigation Drawer and I am always adding new Menus, but I can never seem to remember every little bit of XML that is needed for some complex menus such as share and search. This is why I have created the Xamarin.Android Templates Pack. This is the first release that includes these items that I have listed. You can download it immediately from the Visual Studio Gallery and browse the code on GitHub.

Included in the Menu Items are not only the XML required but also the code behind that will help you implement it. Once you have the Template pack installed you will see the items when you starter a new project or add an item to the menu folder in Resources.

Navigation Drawer:


Menu Item:


Share Menu:


Search Menu:


I am going to be continuing to add more and more templates and please feel free to add an issue or do a pull request if you want to see something.

March 23, 2014 4:22 GMT

Meat

By

Meat is a much debated topic. For every meat-a-holic, there is at least one vegan, vegetarian or some other -atarian. Eating it - or not eating is - so so core to our human existence that everyone has an opinion.

Cows are remarkably awesome animals

I never used to eat a huge amount of meat. When I was growing up, it was fairly expensive, given what my parents earned, and after I left home, I was mostly a consumer of fish and chicken as thats all that Leonie would eat. It wasn't until recently that I got a real taste for red meat, and more recently, I've been trying to eat in a Paleo manner, which my body is loving so far.

Protein, and especially red meat, is now something I enjoy very much - both the taste of it, and how it affects my body. Having a protean-heavy breakfast (in my case, scrambled egg(whites)) is the only way I've managed to keep satiated for a long period. Carbs just don't cut it, and looking back, they never have. I'd either drastically overeat (6 slices of toast for breakfast?) or I'd be hungry inside of 2 hours, or often, both. [1]

Back when I was travelling to the US for work often, I read Eric Schlosser's book Fast Food Nation. It scared the hell out of me - the US food production system couldn't be THAT broken, could it?

Clearly, it could, and still is. I was travelling to Wisconsin - "America's Dairy Land" - and I never saw a single cow. Most restaurants proudly proclaimed "100% USDA beef", but Schlosser's book kind of killed that as a quality mark. Even worse, when we were driving back up the I5 from Los Angeles to San Francisco last October, we drove past a few feed lots. That's not something I'd ever seen in my life, and the smell alone was enough.

This isn't a paddock

For me, cows eat grass in a paddock, not corn (and whatever else) in a mud and shit bath.

On Medium, I got to reading The Meat Seeker's Mission. In it, the author asks all of the restaurants in her area - The Mission district of San Francisco, not by any means a backwater - where they get their meat from. The results were astonishing

One-third of the over 100 restaurants we asked refused to tell us where they get their meat. Most of the other two-thirds did so reluctantly and with suspicion. To compound the problem, restaurants that tout “good” meat are too often misleading people, intentionally or not.

This is the exact opposite of places we'd eat at in the UK or New Zealand: hyperlocal is becoming very popular and common. The 25 Mile is a shining example, but by no means the only one we came across - even small local pubs proudly tell the diner where their food is sourced from. It's not every place, for sure, but more often than not.[3]

The Medium article got me thinking back to a conversation I had with my bother in law. He's a dairy farmer, and by most measures a good and successful one. He's not organic, but he also only gives animals drugs - usually antibiotics - when they need it, just like you do with people. He doesn't see value in mass-prescribing, but also cares too much for his cows to see one suffer from a preventable illness for the sake of being "organic".

I was even more surprised when he told me that if a cow has something wrong - Mastitus for example - and was being given antibiotics to fix it, that cow was off limits for milking. It had to be milked, sure, but the milk was dumped. If it got into the supply which was going to the milk company, he could be fined anything up to the cost of the entire tanker trucks load, as well as the cost of cleaning the tanker - something in the range of $30k or more. All the tankers are tested, too, so there was very little chance of him "sneaking it in".

This made a lot of things in the Paleo literature[2] make sense. Tim Ferris' mantra of always eating grass-fed meat makes a lot more sense - but also why I couldn't get it here or in the UK: there is no need to advertise that it's grass fed if all (or close to all) of it is.[3]

So if you are eating meat, especially in the US, mind where you get it from. Read the Medium article and ask your restaurant where they get it from. If you are buying it, look out for companies like Mindful Meats (and listen to Claire's Do Lecture from DO USA 2013). What goes in your mouth affects your body in such a fundamental way, you owe it to yourself to know where it's come from.



[1]: To keep it in perspective, 6 slices of bread is around 900cal, plus butter/marmite/jam/whatever, and as much egg+whites as I can eat is around 300. And the bread mostly breaks down into sugar.

[2]: ok, websites.

[3]: On the flip side, is everything roses and unicorns here? I seriously doubt it. But it appears to be a long way off the state of the US food chain.