May 06, 2015 12:28 GMT

Top 10 Tips for Building an Apple Watch App

Unless you’ve been living under a rock then you already know about the Apple Watch, have ordered one or your wearing one right now. At the moment I’ve been getting my head around how WatchKit apps will work for my the apps of my clients. The truth be told is that not all apps need a WatchKit component, but many do.

After using an Apple Watch in real, one thing I noticed was the inability to edit calendar events, huh? You can add them but you can’t edit them. Actually in regards to most of the built in apps, there isn’t alot of editing operations. After a lengthy conversation with a product manager at Apple, Apple see’s the Watch primarily being used for super super short intervals, 3-5 seconds. Quickly reading an email or replying to a text message. So essentially we need to keep this in mind when we develop any Watch Apps.

1. Re-think your design from the ground app, don’t just take your Phone app and the images from that app and display it on the watch.

2. Five-Ten Seconds is the amount of time you should keep a users attention, anything more and they should pull their phone out.

3. Bluetooth is slow, and even slower on the device. You need to keep everything lean, compress images, keep images the exact size and no bigger, only update items that have changed (if you even need to). Do you need to upload images or can you use text?

4. Keep is simple, only show the exact data a user needs. If for example your using TripAdvisor, what does the user need to see? The rating, the name and address maybe one more thing, no need to overload the screen you’ve only got 5 seconds anyway.

5. The watch is slow and your app needs to be fast. Lazy-Load for fast startup and then background pre-load where possible, cache where possible, show splash/loading screens. Also another reason to use less content in your apps.

6. Use hand off, this is essential, if you’ve given a user a notification and they jump into your watch app it’s likely they might want to continue the action in further detail on their device. An example would be a user looking at a email and might want to reply on the phone, when the user opens their phone then it must deep link into the mail app with the email open (it already does this btw). This is all available to you as a developer via the WKInterfaceController.

7. Let the iPhone do the work. Communication between your iPhone app and watch app is simple, so don’t be afraid to pass tasks/operations back to the phone.

8. Use dictation – User input is a keystone of useful applications, so while you’ve only got a ‘short time’ with the user it’s still possible to get some input.

9. You only have 10 UI elements in Total, but they can be deeply nested and can be used to create advanced views.

10. Get a Watch and use it. You can’t expect that you’ll be able to create a good user experience unless you live the same user experience. As the saying goes eat your own dog food.

The Apple watch is only a first release product, it’s just a given that the apps and device aren’t going to be overly refined but it’s definitely a glimpse into the future. Oh and FYI it’s not called a iWatch, it’s not, so please don’t call it a iWatch.

Please drop me an email if you have any questions or queries about the Apple Watch, I’m always keen to help people.

Thanks

Michael

 

 

The post Top 10 Tips for Building an Apple Watch App appeared first on Michael Ridland.

May 06, 2015 12:00 GMT

Xamarin.Forms Grid Recipe

In a recent “In Anger” post, I used the Xamarin.Forms Grid control to recreate the mobile Google Analytics page view heat map. The map shows when users frequent this blog. Using the Xamarin.Forms Grid made recreating the UI a snap.

Xamarin.Forms Grid

Xamarin.Forms Grid

The Grid control should look and feel very similar to fellow Silverlight developers. You might recognize the Row and Column definitions as well as the Add method.

Row Definitions

The RowDefinitions Collection property houses the configuration and settings for each row in the Grid.  Each definition has a height property which sets the height of the row. The height can be a constant like 100 or a GridLength value.

Column Definitions

The ColumnDefinition Collection is similar to the RowDefinitions. Each definition controls the width of the column. Just like the rows each column has a width property that can be a constant or a GridLength value.

For the HeatMap post, I used the GridUnitType of Auto for the rows and Star for the columns.

Xamarin.Forms.GridUnitType Enumeration

Member Name Descriptions
Absolute Interpret the GridLength.Value property value as the number of device-specific units.
Auto Ignore the GridLength.Value property value and choose a size that fits the children of the row or column.
Star Interpret the GridLength.Value property value as a proportional weight, to be laid out after rows and columns with GridUnitType.Absolute or GridUnitType.Auto are accounted for.

Xamarin.Forms.Grid.Children.Add

Last, but definitely not least, is the Add method for the grids’ children. You have a few choices on how you add children to this collection.

First you can just add a view. This view will be added to the first row and column of the grid.

heatMap.Children.Add (new BoxView);

Second, you can add a view and give it the left and top location within the grid. Remember rows and columns start at zero.

heatMap.Children.Add (new BoxView (), 1 , 1);

Lastly, you can give it the view and its left, right, top and bottom locations. The last one is useful for when you want a view to span more than one column or row. In this example, we are placing a BoxView into the second row and column and having it span two rows and columns.

heatMap.Children.Add (new BoxView (), 1, 2, 1, 2);

I’ve really just scratched the surface of the Xamarin.Forms Grid. Without the Grid control this UI would have been very difficult to recreate. With the control, it took me an hour. I spent a little time after that fiddling with the GridUnitType for the rows and columns.

The Xamarin.Forms Cookbook Series

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

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

May 05, 2015 8:48 GMT

Build 2015: Visual Studio Integration & Developer Celebrations

In addition to achieving the 1 Million developer milestone last week, Xamarin developers also enjoyed a great show at Microsoft Build 2015, with a packed attendee party on opening night, multiple sessions covering mobile development with Xamarin, and the debut of Microsoft’s Visual Studio 2015 Release Candidate with improved Xamarin integration.

Kicking Off Build 2015 with Xamarin

We kicked off Build 2015 in a big way at Jillian’s in San Francisco on April 28th. With over 1,400 attendees and Charles Petzold in attendance signing copies of his Xamarin.Forms book preview, this was our biggest and best Xamarin Build party yet! It was inspiring to see the flood of Xamarin shirts at Build, and exciting to make our three Developer Rig Giveaway contest winners happy.

Xamarin's Microsoft Build 2015 Kick Off Party

One of the most popular features of the night was the Xamarin Test Cloud Wall that showed automated testing on 60 devices—just a fraction of the number of devices most teams need to test on to ensure a high quality user experience.  If you couldn’t make it to Build to see Xamarin Test Cloud in action in person, you can check our new Xamarin Test Cloud overview video out our freshly updated Xamarin Test Cloud page.

Xamarin Test Cloud Wall

Xamarin Integration in Visual Studio 2015

Becoming a Xamarin developer couldn’t be easier with the release of Visual Studio 2015 RC. During the Visual Studio 2015 installation process, you can now choose to install Xamarin and its requirements with a single click, giving you everything you need to get started with native, cross-platform development in C# with Xamarin.

Visual Studio Install with Xamarin

Starter Edition in Visual Studio

Along with an integrated installation experience, our free developer tier, Xamarin Starter Edition now works with Visual Studio. This lets anyone get a taste of mobile development in C# by giving you the ability to write small apps which can be deployed to devices and published to app stores.

These new enhancements to our support for Visual Studio are a great compliment to what we announced with our 1 million developer download milestone — expanded support for Xamarin.Forms for Windows, and WatchKit design and development support in Visual Studio.

Session Recordings

If you weren’t able to attend this year’s Build conference don’t worry — you can experience the magic of Miguel de Icaza and James Montemagno’s session on how to Go Mobile with C#, Visual Studio, and Xamarin online now.

In addition, James Montemagno delivered an additional session at Build focused on Developing Multi-Device Apps with Xamarin and Office 365 APIs that is also available online.

See You at Ignite

If you are in Chicago this week for Microsoft Ignite, we’re at booth #216, so be sure to stop by and say hello. Additionally, Xamarin Developer Evangelist, James Montemagno will be delivering two sessions this year:

 

The post Build 2015: Visual Studio Integration & Developer Celebrations appeared first on Xamarin Blog.

May 05, 2015 7:04 GMT

Summer Camp with Mobile Developers

The events in our lives happen in a sequence in time, but in their significance to ourselves they find their own order: the continuous thread of revelation. - Eudora Welty

We at XHackers strongly believe in this and this summer, we are happy to add two more events to your life, helping you to learn more about Xamarin. We are bringing in some exciting sessions to both the meetups.

Recently at Microsoft //build, there were a series of announcements and one among them is Windows 10 and "Universal App Development". So here's your chance to learn more about it from none other than the team at Microsoft Bangalore.

On May 9th - learn how to start Building & Running your Apps over a Billion devices - with Universal Windows Apps by Abhishek Narian, Technical Evangelist, Microsoft.

There are multiple ways to share your business logic code - you can use PCL, Shared Library, or even File Linking. However, there could be instances when your UI is less complicated, and you wish to maintain a single UI codebase. Learn more about how to build native UIs for iOS, Android and Windows from a single, shared C# codebase.

Join Nish Anil, Developer Evangelist, Xamarin on building a simple Weather app using Xamarin.Forms.

Xamarin.Forms

In continuation to our previous meetup on wearables, we have added one more talk on
Programming Microsoft Band : The Xamarin way by Vidyasagar, Microsoft MVP - XBox.

To be part of this Cross platform learning experience -

RSVP Now

The second event is on May 23rd and this time its at Neudesic Bangalore

Here;s the detailed agenda for this event:

Session 1: Integrating azure mobile services with Xamarin app (Duration 1 hr)

  • Azure Mobile Service overview

  • Getting started with Xamarin and Azure Mobile Services

  • Covering following scenarios:

    • Store data

    • Offline data sync and handle conflicts

    • Authenticate user

    • Add push notification to your app

Speaker: Sanjeev Dhawala, Senior Consultant, Neudesic

Session 2: Explore Xamarin Test cloud with Xamarin Store App (Duration 1 hr)

  • Overview of Xamarin.UITest to automate the execution of existing iOS and Android apps.

  • Explore the creation of acceptance, behavior and regression tests and how the Xamarin.UITest tooling can be used to speed up the development of your acceptance tests.

  • Finally, we will learn how to deploy the apps + UI Tests up to Test Cloud for complete coverage across devices, OS versions and form factors using Xamarin Store App.

Speaker: Srinivasu Amjuri, Senior consultant, Neudesic (QA Practice)

To take part -

RSVP Now

Please note: The Venue for both the events are different. Make sure make necessary travel arrangements for the same.

See you there!

Cheers
Xhackers Core Team
core@xhackers.co

May 04, 2015 8:40 GMT

Xamarin Events Happening in May

It’s conference season again and May is the perfect time to catch a Xamarin event near you! Here is a list of a few events happening around the world you won’t want to miss.

May 2015 Meetups Banner

Microsoft Ignite us

  • Chicago, IL: May 5th – 8th
  • Go Mobile with C#, Visual Studio, and Xamarin by James Montemagno

Xamarin Dev Days – Chicago us

  • Chicago, IL: May 9th
  • Bringing mobile development with Xamarin to Chicago

Software Design & Development uk

  • London, England: May 11th – 15th
  • Cross-Platform Mobile Development with Xamarin by Mark Smith

Techorama Belgium

  • Mechelen, Belgium: May 13th
  • Go Mobile with C#, Visual Studio, and Xamarin by Mike James

Chicago Coder Conference us

  • Chicago, IL: May 14th – 15th
  • Xamarin.Forms: Native iOS, Android, and Windows Phone apps from ONE C# Codebase by James Montemagno

Xamarin Dev Days – Mountain View us

  • Mountain View, CA: May 17th
  • Bringing mobile development with Xamarin to the Bay Area

DEVIntersection us

  • Phoenix, AZ: May 18th – 21st
  • Integrating Office 365 APIs into Multi-Device Mobile Applications by James Montemagno

Twilio Signal us

  • San Francisco, CA: May 19th – 20th
  • C# and Twilio-Powered iOS and Android Experiences by James Montemagno

Xamarin Dev Days – Phoenix us

  • Phoenix, AZ: May 23rd
  • Bringing mobile development with Xamarin to Phoenix

Xamarin Dev Days – Houston us

  • Houston, TX: May 30th
  • Bringing mobile development with Xamarin to Houston

Xamarin Dev Days – Austin us

  • Austin, TX: May 31st
  • Bringing mobile development with Xamarin to Austin

 

Look to the Events Forum for even more upcoming Xamarin events, meetups, and presentations happening this month near you!

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 Xamarin Events Happening in May appeared first on Xamarin Blog.

May 04, 2015 7:01 GMT

Generating Android Color Palettes Super Fast with Rev 22.1

Google went on a spree a few weeks back updating all of their support libraries to rev 22.1. If you haven’t read about all the changes be sure to read through the official Android Developer’s blog for a full breakdown. The most drastic change to the support libraries was to v7 AppCompat with the new AppCompatActivity, but there were several other enhancement to the libraries including one of my favorite Palette. If you don’t remember what palette is, it allows you to sample a color palette from any bitmap to theme your application. Here is a simple example of the before and after:

With rev 22.1, available as a NuGet package for your Xamarin.Android applications, the speed in which palettes are now generated are now 5 to 10 times faster! Here are some stats from Chris Banes’ blog:

After you update your NuGets to the latest version (currently 22.1.1.1 as of May 2nd 2015), you may notice that your old Palette methods were deprecated. This is because Google has replaced the older Palette.Generate and Palette.GenerateAsync methods with the tried and true Builder pattern. This will feel very familiar if you have worked with AlertDialogs or Notifications. It is basically a way of chaining property setters in a row (kind of linq style) since java doesn’t really have getters for properties that you could construct. So here is our old code:

In the latter method call the “this” is your current implementation of  Palette.IPaletteAsyncListener, which will get a callback when the generate has been completed and the new way of generating a palette uses this same interface implementation, but looks a bit different:

Updating to the latest NuGet packages will have some drastic improvements in speed as you saw in Chris’ chart because according to Chris Banes: “In this release, we went back to some old-style optimizations for the colour quantization. Things like less object allocations, more appropriate data structures and a reduction in algorithmic complexity. “

There you have it! You can grab a sample from our Xamarin.Android samples gallery. Now go make things beautiful.

May 04, 2015 3:12 GMT

BDD Tests with Xamarin.UITest and SpecFlow

Sample code is available at my Github repo

Writing applications, whether desktop, web, or mobile, is expensive. Developer time is a very limited commodity; one that we have to be careful not to waste. Two very common ways to waste developer time include writing code twice in order to fix what was broken the first time, and writing code that never should have been written in the first place.

Unit testing can help us deal with the issue of not shipping broken code. We should have a full suite of unit tests focused on the method level of our code. These unit tests should be lightning fast, run constantly, and verify that the code we wrote works the way that we expect it to.

Unit tests are invaluable, and I'm a huge fan of them, but they don't necessarily help us avoid writing the wrong code. As developers, every line of code that we write should be driven by an actual business requirement. These requirements are defined by the developers, the product managers, executives, possibly some users, and other important stakeholders working together. This communication between people is extremely important to writing the correct application and features from the start. It doesn't matter how wonderfully our code is executing if it's the wrong code. Typically, these requirements are written down in something like a Microsoft Word document, and passed around between all of the interested parties. The problem with this approach, though, is that it is very, very easy for these documents to be written once, and then become out of date or ignored as the development process begins. What we would really like is for our requirements to written in such a way that they are readable and understandable by all stakeholders, but also have them actually execute against our application in the same way that unit tests are executable.

Behavior Driven Development

This is where Behavior-driven development, or "BDD", comes in.

"Behavior-driven development combines the general techniques and principles of TDD with ideas from domain-driven design and object-oriented analysis and design to provide software development and management teams with shared tools and a shared process to collaborate on software development.

Behavior-driven development borrows the concept of the ubiquitous language from domain driven design. A ubiquitous language is a (semi-)formal language that is shared by all members of a software development team — both software developers and non-technical personnel."

Wikipedia

The main purpose of BDD is to facilitate the communication of an application's requirements between the stakeholders. We can write our software specifications in an easily readable and understandable syntax called Gherkin, which can also be used to create executable tests.

For this example, I'm going to use the Xamarin TaskyPro sample application. You can download the source code and run the application yourself, if you'd like. A precompiled binary is included in my sample.

Here you can see an example of defining the user-centric feature to add a new task to the TaskyPro list. Notice that this specification is easily understandable by developers and non-developers alike.

Feature: Adding a task  
  I want to be able to quickly add a task

  Scenario: Add a task
    Given I am on the Home screen
    When I add a new task called "Get Milk"
    And I save the task
    Then I should see the "Get Milk" task in the list

Unlike unit tests, these tests generally concentrate on exercising the full running application. In our case, this will mean running an iOS or Android application on a simulator/emulator or on a physical device.

Cucumber and Calabash

When testing mobile apps, there is an existing solution that brings BDD and Gherkin to iOS and Android testing. This is the open source project named Calabash. Calabash uses the Ruby based framework named Cucumber to execute the acceptance tests defined from our specifications.

Xamarin.UITest

Xamarin.UITest is a very similar framework to Calabash, except it allows us to write our tests using C# and execute them using one of the common .Net unit testing frameworks, typically NUnit.

Xamarin.UITest gives us the means to write tests which interact with and verify the running iOS and Android applications, much like Calabash, but it does so in a much more developer oriented way.

The same test as above, written in Xamarin.UITest, would look like this.

app.Tap (c => c.Class("UIButton").Marked ("Add"));  
app.EnterText (c => c.Class ("UITextField").Index (0), "Get Milk");  
app.EnterText (c => c.Class ("UITextField").Index (1), "Make sure to get the milk!");  
app.Tap (c => c.Class("UIButton").Marked ("Save"));  

While this obviously achieves our goal of having automated acceptance tests, it doesn't help very much with our goal of improving communication among all the stakeholders. Developers are very comfortable reading code, but managers, QA, executives, users, and other stakeholders are not. What's missing from Xamarin.UITest is the Gherkin language.

SpecFlow

SpecFlow fills that void and allows us to write our specifications as Features and Steps written using Gherkin. SpecFlow then enables us to write the definition of those steps as C# code.

We can combine SpecFlow and Xamarin.UITest to give us all the benefits of BDD and Gherkin while using the C# language that we know and love.

Create the test project

SpecFlow has a Visual Studio extension available which adds some templates and integration with the VS IDE. In Xamarin Studio, there is a SpecFlow addin available. The template will be installed in Other > Miscellaneous > General > SpecFlow NUnit Library Project

This will create a new class library with the NUnit and SpecFlow Nuget packages already added. Be sure to update the Nuget packages when you first create the project.

Add Xamarin.UITest

Next, we need to add the Xamarin.UITest Nuget package to the project.

Once the Xamarin.UITest Nuget package has been added, the Unit Test window in Xamarin Studio will show a new section titled "Test Apps". We'll use this shortly.

Cross platform tests

If we had used the Xamarin.UITest template when we first created our test project, instead of the SpecFlow template, we would have had a project containing two files; AppInitializer.cs and Tests.cs. The AppInitializer class is a static helper class that will return an appropriate IApp instance configured for the currently executing platform.

public class AppInitializer  
{
    public static IApp StartApp (Platform platform)
    {
        if (platform == Platform.Android) {
            return ConfigureApp
                .Android
                .StartApp ();
        }

        return ConfigureApp
            .iOS
            .StartApp ();
    }
}

The Tests class is where our NUnit tests would be defined. Notice the parameter to the [TestFixture()] attribute, which is where we can specify which platforms to run this set of tests on.

[TestFixture (Platform.Android)]
[TestFixture (Platform.iOS)]
public class Tests  
{
    IApp app;
    Platform platform;

    public Tests (Platform platform)
    {
        this.platform = platform;
    }

    [SetUp]
    public void BeforeEachTest ()
    {
        app = AppInitializer.StartApp (platform);
    }

    [Test]
    public void AppLaunches ()
    {
        app.Screenshot ("First screen.");
    }
}

Add test apps

When configuring our IApp instance, we will need to specify where the Xamarin.UITest framework can find the binary applications to install and run. In the AppInitializer class, we actually have two different ways to specify the path to these apps.

First, we could simply pass the path to the binary to the appropriate platform specific method, either ApkFile for Android, or AppBundle for iOS. This allows us to execute acceptance tests against any compiled Android or iOS application, even ones written in Java or Objective-C/Swift (along with Xamarin.iOS and Xamarin.Android, of course).

public static IApp StartApp (Platform platform, string iOSSimulator)  
{
    if (platform == Platform.Android) {
        return ConfigureApp
            .Android
            .ApkFile ("../com.xamarin.samples.taskydroidnew.exampleapp.apk")
            .StartApp ();

    } else if (platform == Platform.iOS) {
        return ConfigureApp
            .iOS
            .AppBundle ("../TaskyiOS.app")
            .StartApp ();
    }
}

Alternatively, as of Xamarin Studio 5.9, if we have the source code projects loaded in Xamarin Studio along with our test project, we can use the new Test Apps feature to point the test project at the source code project.

Once the test project knows about the source projects, the configuration no longer needs the path specified, and we can remove the ApkFile and AppBundle methods.

public static IApp StartApp (Platform platform, string iOSSimulator)  
{
    if (platform == Platform.Android) {
        return ConfigureApp
            .Android
            .StartApp ();

    } else if (platform == Platform.iOS) {
        return ConfigureApp
            .iOS
            .StartApp ();
    }
}

Adding features

At this point, the test project is ready to start defining our features. The first feature for our TaskyPro application will be Add a Task. Features in SpecFlow are defined using a feature file. We can add one of these to our test project using the built in Xamarin Studio template.

You can delete the contents of this file, and replace it with the business defined specification for our application.

Feature: Adding a task  
  I want to be able to quickly add a task

  Scenario: Add a task
    Given I am on the Home screen
    When I add a new task called "Get Milk"
    And I save the task
    Then I should see the "Get Milk" task in the list

When the project is saved and built, SpecFlow will read this feature file and create a partial C# class which can execute our test.

[System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "1.0.0.0")]
[System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[NUnit.Framework.TestFixtureAttribute()]
[NUnit.Framework.DescriptionAttribute("Adding a task")]
public partial class AddingATaskFeature  
{
  // .....
}

If there are any additions or customizations that we want to make to this class, we can implement the other part of the partial class (AddingATaskFeature.cs) and do it there.

public partial class AddingATaskFeature : FeatureBase  
{
  public AddingATaskFeature (Platform platform, string iOSSimulator) : base(platform, iOSSimulator)
  {
  }
}

Customizing the steps

You may ask "What magic lets the computer know what I mean by 'When I add a new task...' ?". Well, it's not magic, it's the magic of C#! Each SpecFlow step that you write needs to have a corresponding method defined in a C# class somewhere. The class needs to have a [Binding] attribute, and the methods will have either a [Given], [When], or [Then] attribute with a Regular Expression that will match the step defined in the feature file.

using TechTalk.SpecFlow;  
using Xamarin.UITest;

[Binding]
public class CommonSteps  
{
    readonly IApp app;

    [When (@"I add a new task called ""(.*)""")]
    public void WhenIAddANewTaskCalled (string taskName)
    {
        // Test code defined here ...
    }

    // More methods defined here ...
}

Each method will then use the Xamarin.UITest framework to exercise and test the app.

[When (@"I add a new task called ""(.*)""")]
public void WhenIAddANewTaskCalled (string taskName)  
{
  app.WaitForElement (c => c.Marked("Add Task"));
  app.Tap (c => c.Marked("Add Task"));
  app.Screenshot ("When I add a new task called '" + taskName + "'");
  app.WaitForElement (c => c.Marked("txtName"));
  app.EnterText (c => c.Marked("txtName"), taskName);
  app.Screenshot ("When I add a new task called '" + taskName + "'");
}

Cross Platform tests (part 2)

As you can see, our tests end up just being C# code. As with all code, we should try to not repeat ourselves. We want to write these test steps once and have them executed on both iOS and Android. The TaskyPro application presents a problem though. When the application was written, the various controls on the two platforms did not end up with the same text or the same name/id. This means that code which uses hard coded names in the Xamarin.UITest query selectors work on one platform and fail on the other.

app.EnterText (c => c.Marked("txtName"), taskName);  

To get around this, we first will define an interface for the "screen" in the app that we'll be testing. The interface has properties for each control on the screen that we want access to.

public interface IAddTaskScreen  
{
  Func<AppQuery, AppQuery> nameEntry { get; }
  Func<AppQuery, AppQuery> saveButton { get; }
  Func<AppQuery, AppQuery> deleteButton { get; }
}

Then, we create implementations of this interface for each platform, with the appropriate query selector.

Android

public class AndroidAddTaskScreen : IAddTaskScreen  
{
  public Func<AppQuery, AppQuery> nameEntry { get; } = new Func<AppQuery, AppQuery> (c => c.Marked("txtName"));
  public Func<AppQuery, AppQuery> saveButton { get; } = new Func<AppQuery, AppQuery> (c => c.Marked("btnSave"));
  public Func<AppQuery, AppQuery> deleteButton { get; } = new Func<AppQuery, AppQuery> (c => c.Marked("btnCancelDelete"));
}

iOS

public class iOSAddTaskScreen : IAddTaskScreen  
{
  public Func<AppQuery, AppQuery> nameEntry { get; } = new Func<AppQuery, AppQuery> (c => c.Marked("Name"));
  public Func<AppQuery, AppQuery> saveButton { get; } = new Func<AppQuery, AppQuery> (c => c.Marked("Save"));
  public Func<AppQuery, AppQuery> deleteButton { get; } = new Func<AppQuery, AppQuery> (c => c.Marked("Delete"));
}    

Depending on the current platform, as defined in the [TestFixture] attribute, we can add the correct screen definition to SpecFlow's FeatureContext object from the AppInitializer class. Note that I also defined some ScreenName constants in order to get nice IntelliSense.

public static void InitializeScreens(Platform platform)  
{
    if (platform == Platform.iOS) {
        FeatureContext.Current.Add (ScreenNames.Home, new iOSHomeScreen ());
        FeatureContext.Current.Add (ScreenNames.AddTask, new iOSAddTaskScreen ());
    } else if (platform == Platform.Android) {
        FeatureContext.Current.Add (ScreenNames.Home, new AndroidHomeScreen ());
        FeatureContext.Current.Add (ScreenNames.AddTask, new AndroidAddTaskScreen ());
    }
}

In the FeatureBase class, which is the base class for each Feature test in the project, we then call the InitializeScreens method before each NUnit test executes.

[SetUp]
public void BeforeEachTest ()  
{
  app = AppInitializer.StartApp (platform, iOSSimulator);
  FeatureContext.Current.Add ("App", app);
  AppInitializer.InitializeScreens (platform);
}

The class which defines our steps will then grab the implementations out of the FeatureContext. We now can rewrite our Step using strong typed abstractions which will use the correct query selector for the platform.

[Binding]
public class CommonSteps  
{
    readonly IHomeScreen homeScreen;
    readonly IAddTaskScreen addTaskScreen;
    readonly IApp app;

    public CommonSteps ()
    {
        app = FeatureContext.Current.Get<IApp>("App");
        homeScreen = FeatureContext.Current.Get<IHomeScreen> (ScreenNames.Home);
        addTaskScreen = FeatureContext.Current.Get<IAddTaskScreen> (ScreenNames.AddTask);
    }

    [When (@"I add a new task called ""(.*)""")]
    public void WhenIAddANewTaskCalled (string taskName)
    {
        app.WaitForElement (homeScreen.addButton);
        app.Tap (homeScreen.addButton);
        app.Screenshot ("When I add a new task called '" + taskName + "'");
        app.WaitForElement (addTaskScreen.nameEntry);
        app.EnterText (addTaskScreen.nameEntry, taskName);
        app.Screenshot ("When I add a new task called '" + taskName + "'");
    }
}

Multiple simulators/emulators

Lastly, when running the tests it is helpful to specify which simulators or emulators, including the operating system version, that you wish to execute on. Also, we generally want to reset the state of the simulator to clear any persistent state and run each test cleanly.

Note : resetting the iOS simulator currently only works on Mac, not through Visual Studio on Windows.

[TestFixture (Platform.Android, "")]

[TestFixture (Platform.iOS, iPhone5s.OS_8_1)]
[TestFixture (Platform.iOS, iPhone5s.OS_8_2)]
[TestFixture (Platform.iOS, iPhone5s.OS_8_3)]

[TestFixture (Platform.iOS, iPhone6.OS_8_1)]
[TestFixture (Platform.iOS, iPhone6.OS_8_2)]
[TestFixture (Platform.iOS, iPhone6.OS_8_3)]

[TestFixture (Platform.iOS, iPadAir.OS_8_1)]
[TestFixture (Platform.iOS, iPadAir.OS_8_2)]
[TestFixture (Platform.iOS, iPadAir.OS_8_3)]
public class FeatureBase  
{
    // ...
}

You can read the code for this in the source project.
Thanks to everyone on this forum post for the code

Running the tests locally

Xamarin Test Cloud

Even better than running these tests on local simulators and emulators would be to run them on hundreds or thousands of real devices. The great thing about using Xamarin.UITest is the ability to upload these tests to Xamarin Test Cloud. Xamarin Studio makes this as simple as right-clicking on the tests in the Unit Tests pad, and choosing Run in Test Cloud.

This will run all of the tests on either Android or iOS. You'll be able to see which tests pass or fail, the number of devices, OS versions, and a wealth of other information. We can even see the Gherkin steps in the Xamarin Test Cloud UI.

Sample code is available at my Github repo

May 04, 2015 2:08 GMT

Finding Nemo – Implementing Xamarin.Forms SearchBar

Xamarin.Forms gives you a component called the SearchBar, by default.

Like you would expect, this gives you a simple text edit box which is specifically designed to serve in search operations.

To show you how easy it is to implement, I will demonstrate how I built it into the sample app I have been using up till now, if you need to refresh your memory take a look at my previous post.
In this app there is an employee directory. Although this isn’t a endless list, it is desirable to quickly navigate to the right person. And how could we do it better than by searching?

First let’s take a look at how my ListView is before I make any changes.

<?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="FourDotNet.Pages.EmployeesPage"
             Title="Medewerkers">
  <StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand">
    <ListView IsPullToRefreshEnabled="True" Refreshing="EmployeeListView_OnRefreshing" ItemTapped="EmployeeListView_OnItemTapped" x:Name="EmployeeListView">
      <ListView.ItemTemplate>
        <DataTemplate>
          <ImageCell ImageSource="{Binding PhotoUrl}" Text="{Binding Name}" Detail="{Binding Function}">

            <ImageCell.ContextActions>
              <MenuItem Text="Stuur e-mail" Clicked="EmployeeContextEmail_OnClicked"></MenuItem>
            </ImageCell.ContextActions>
          </ImageCell>
        </DataTemplate>
      </ListView.ItemTemplate>
    </ListView>
  </StackLayout>
</ContentPage>

As you can see I’ve made use of a simple StackLayout to put in a ListView which can be pulled to refresh, does something when an item is tapped and tells the list how to display a cell to the user.

In the running app this will be shown as underneath.

ListView without SearchBar

ListView without SearchBar

Adding a SearchBar is pretty easy, just go like this:

[...]
<StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand">
    <SearchBar Placeholder="Zoeken..." TextChanged="SearchBar_OnTextChanged"></SearchBar>
    <ListView IsPullToRefreshEnabled="True" Refreshing="EmployeeListView_OnRefreshing" ItemTapped="EmployeeListView_OnItemTapped" x:Name="EmployeeListView">
[...]

The Placeholder attribute sets the placeholder text when no search-term hasn’t been entered. The TextChanged is as advertised on the tin; the event that gets fired when the text is changed.

For the end-user the screen now looks like this;

ListView with SearchBar

ListView with SearchBar

Now lets have a look at the SearchBar_TextChanged event-handler.

private void SearchBar_OnTextChanged(object sender, TextChangedEventArgs e)
{
   EmployeeListView.BeginRefresh();

   if (string.IsNullOrWhiteSpace(e.NewTextValue))
      EmployeeListView.ItemsSource = _container.Employees;
   else
      EmployeeListView.ItemsSource = _container.Employees.Where(i => i.Name.Contains(e.NewTextValue));

   EmployeeListView.EndRefresh();
}

We are starting with telling the ListView that we are going to do some updates, so it will probably skip some redraw operations while we update the data inside it.

After that we check if the user has entered text, or cleared all text from the SearchBar and supply a corresponding ItemSource. Don’t forget to call the EndRefresh method, and that’s about it! Simple is it not?!

Now when you start entering text in the field it will start filtering in your ListView.

As a next step you would want to clean up your form code and not handle this there. So create a inheritance of a ListView which will handle filtering in its own, or create a composition of the SearchBar and the ListView to form a whole new component, a component which I like to call..

SearchableListView Dr. Evil meme

So far on the SearchBar for right now! Hope you’ll put it to good use.

May 04, 2015 12:40 GMT

Akavache is AKA Awesome!

In the last post we covered how to implement data caching in a cross platform application using Xamarin. And we also showed why providing a data cache to the users of our mobile applications is important.

Why caching is important
  • Network resiliency
  • Perceived app performance

However, the plumbing for the caching can be a bit of a pain to implement. The following diagram gives an example of the flow needed to implement caching. The order in which the tasks are implemented may vary based on the business requirements, some tasks may be omitted, but generally they are the same.

Ugh ... and this is just one of many different workflows!

Ugh … and this is just one of many different workflows!

Then we get to the characteristics of the data we want to cache. Obviously the data’s not volatile since we’re saving it for later use. Most likely we already know where and how we want to use the data within our app, so if we thought our design through, we’re saving the data in a way that it’s easy to get it and we’re not querying it in a relational manner. And the business requirements will dictate this, but the data already in the cache may not change where we have to update it.

So what if I told you there was a framework that provided everything above (and more), and made it super easy to implement the caching plumbing in a cross platform manner?

Enter Akavache

The official definition from Akavache’s GitHub site:

Akavache Logo

Akavache is an asynchronous, persistent (i.e. writes to disk) key-value store created for writing desktop and mobile applications in C#, based on SQLite3. Akavache is great for both storing important data (i.e. user settings) as well as cached local data that expires.

In other words, Akavache provides an awesome framework for caching data. It implements everything we mentioned above, and more (and in a way most likely better than we could have ourselves). Written by Paul Betts, it’s a library that I’m finding more and more useful every time I use it.

In the rest of this post we’ll take a look at the basic API that Akavache provides. Then in the next post we’ll refactor the code from the Cold Hard Data Cache Post on caching and see how much simpler and more elegant Akavache makes it.

Basic Installation and Usage

First things first – we’re going to need to install Akavache. It’s available via NuGet. Search “Akavache” and the top 3 results will look something like the following:

Akavache NuGet Options

Akavache NuGet Options


I found that trying to select “Akavache”, “Akavache.Core”, and “Akavache.SQLite3″ to install all at once makes Xamarin Studio unhappy. Select “Akavache.SQLite3″ first and install it. Then install “Akavache” and you’ll be off and running.

Akavache is asynchronous – which means it won’t block our UI. That’s not a bad thing and not even a difficult thing, just something to be aware of.

At its heart, Akavache is a key/value store with a SQLite backend. To simplify how it stores data, there’s a table which has a column for the key which is a VARCHAR and another for the value which is a BLOB. (There are also columns for the CLR type of data in the blob column, another column for the expiration date of the cached data, and another for the created date).

The cool thing about using the key/value model of persisting data is that we can put anything into the value portion. It can range from a simple object with nothing but properties, to a collection of objects, to a complex object hierarchy with nested objects within objects … etcetera and so forth.

As far as using the Akavache framework, the first thing to note is that everything in Akavache is accessed through an objected called

BlobCache
.

To define where the database will reside within the app’s sandbox, we set a property on the BlobCache object called ApplicationName. So we end up with something like the following:

Akavache.BlobCache.ApplicationName = "AkaAwesome";
There’s nothing fancy going on here, this is just basic setup stuff.

The BlobCache object exposes 4 different objects which can cache data for us. Each of these object implement the IBlobCache interface.

IBlobCache Description
BlobCache.LocalMachine Local machine cache (normal SQLite as described above).
BlobCache.InMemory Volatile cache (gone on restart).
BlobCache.Secure Encrypted cache within SQLite.
BlobCache.UserAccount User account cache. This acts the same as the LocalMachine above, except the SQLite database file will get backed up by Apple backups, while the LocalMachine database file does not.
Update (5/5/15): Paul Betts sent me a tweet to clarify the difference between the LocalMachine and UserAccount objects. Previously I had stated the UserAccount object was not of much use on a mobile device, turns out it is very useful.

When using the UserAccount cache in iOS, Akavache will ensure the SQLite database file is created in the proper location so the file is backed up (as in iCloud or iTunes backups). The database file used by the LocalMachine cache object is created in a location where it is not backed up.

The vast majority, if not all, of the time we’ll be using the LocalMachine or UserAccount object in our mobile apps. So let’s talk about getting data into, and out of the cache.

Inserting Objects

Method Description
InsertObject<T>(key, T, expiration) Insert single object of type T with key and optional DateTimeOffset expiration
InsertAllObjects<T>(dictionary, expiration) Insert all objects in IDictionary with optional expiration

The first function above will insert any object into the cache taking an optional parameter of when it should expire – or be deleted and not be returned from the cache any longer.

The second function does the same, but with multiple objects at a time.

A quick code example of adding a Question object that expires 2 hours from now:

var question = new QuestionInfo { QuestionID = 1, Title = "Hello?" };

await BlobCache.LocalMachine.InsertObject<QuestionInfo> (
    "first", 
    question, 
    DateTimeOffset.Now.AddHours (2));

Getting Objects

Method Description
GetObject<T>(key) Return single object via its key
GetAllObjects<T>() Return all objects of type T

These methods will return an object of type T if it exists in the cache. Pretty straight forward. One thing to watch out for is that if the key does not exist, an exception of the type
KeyNotFoundException
will be thrown.

In action it looks like the following:

try {
    var question = await BlobCache.LocalMachine.GetObject<QuestionInfo> ("first");
} catch (KeyNotFoundException) {
    // do something useful
}

Fetching Objects

Method Description
GetOrFetchObject<T>(key, Func<T>, expiration) Returns cached result – if none exists – execute the Func<T> parameter to load result, put it in the cache and expire it according to optional expiration parameter
GetAndFetchLatest<T>(key, Func<Task<T>>, Func<DateTimeOffset, bool>, DateTimeOffset?) Returns cached result. Also goes ahead and uses the function in the second parameter to load the latest value and put that into the cache. So this method will return twice – once with the value from the cache and again when it updates with the latest value. So as the official documentation says, awaiting this function is a "Bad Thing" and that we subscribe to it instead.

These two functions are where Akavache really starts to become awesome! In the first function we’re saying – give me what’s in the cache – can’t find it? No worries, just call the function I’m passing in, stick the result in the cache and give me the result. That’s awesome!

var question = await BlobCache.LocalMachine.GetOrFetchObject<QuestionInfo> (
    "first",
    async () => await StackAPI.GetQuestionFromWeb (123),
    DateTimeOffset.Now.AddHours (3)
);

The second is even better – it takes a bit to fully understand it though. We’re saying, give me what’s in the cache, but at the same time call the function I’m passing in and get the latest value. This way we can make our user interface super responsive and keep the UI and cache up to date with the latest data!

But because the function is returning twice we can’t await it – so we have to use Subscribe, so every time our value changes we’re alerted to it.

I told you – flipping awesome!

QuestionInfo augusteRodin;

BlobCache.LocalMachine.GetAndFetchLatest ("theThinker", 
    async () => await DownloadQuestion (), null, null).Subscribe (
    cachedThenUpdatedThought => {

        augusteRodin = cachedThenUpdatedThought;

        Device.BeginInvokeOnMainThread (() => theStatue.Text = augusteRodin.Title);


    });

Downloading

Method Description
DownloadUrl(url,IDictionary(string,string) headers, fetchAlways, expiration) Download the contents of the URL (using the URL as the key in the cache). By setting the fetchAlways boolean, can always hit the web to download.
LoadImageFromUrl(url, fetchAlways, desiredHeight, desiredWidth, expiration) Tries to load the image from the cache and if it does not exist, then download it from the internet. Of course, obeying the fetchAlways boolean.

These are pretty awesome functions too, and they’re straightforward.

We’re going to download either an array of bytes, as in the first function, or a cross platform IBitmap in the second function.

var talkingCats = await BlobCache.LocalMachine.LoadImageFromUrl ("http://catimages.com", false);

Deleting Objects

InvalidateObject<T>(key) Removes object corresponding to the key with type of T from the cache
InvalidateAllObjects<T>() Removes all objects of type T from the cache
Vacuum Removes all expired objects from the cache

Maintenance functions – not the most glamorous, but still necessary (and hopefully self-explanatory).

Conclusion

Akavache – our new most awesome friend in the world! Taking all of the tedious maintenance out of implementing caching plumbing so we can concentrate on creating great apps for our users.

Akavache employs a SQLite backend to store key/value pairs of objects. The value portion of those objects are stored in BLOB fields so they can hold anything from a plain POCO object to the most complex object hierarchy. Akavache gives us an easy to use API to store, delete and retrieve objects from the cache, including some sweet functions to automatically download info if it doesn’t exist and update the cache with the latest info.

So fire up Xamarin Studio or head on out to Github or NuGet and see for yourself why Akavache is Also Known As Awesome!

May 04, 2015 12:00 GMT

Xamarin.Forms in Anger – HeatMap

I am a Google Analytics junkie! There, I said it, I’m addicted to Page Views and Sessions statistics. My addiction is so bad that I installed the Google Analytics App on my iPhone and I check it often. Too often.

The Page Views heat map is the feature I like the most. The map shows me when people visit this site. My heat map shows a concentration of visitors whenever I release new blog posts, no surprise there. What is a surprise is how nice the heat map looks. Whenever I see a good looking UI, I think, can I build it in Xamarin.Forms? And the answer is, yes, yes we can.

The Blueprint

I think this might be the easiest blueprint of all the “In Anger” posts. Only 6 types and most of them are just supporting actors. The Grid and BoxView are the heroes of this UI.

HeatMap

The Code

For this post I went all out and separated the data and styles into different classes. I want you to see how easy it was to build this UI without all the B list celebrities getting in the way. If you want to see all the gory details, check out the GitHub repository.

public class HeatMapApp 
{
	Grid heatMap;

	public Page GetMainPage ()
	{
		SetupHeatMap ();

		AddHoursColumn ();
		AddWeekDayRow ();

		AddHeatSquares ();

		var stack = new StackLayout () {
			Padding = new Thickness (5, 0, 10, 0),
			Spacing = 0,
			Children = {
				new Label () {
					Text = "Page Views",
					Style = AppStyles.PageViewLabelStyle
				},
				new Label () {
					Text = "24,098",
					Style = AppStyles.PageViewCountLabelStyle
				},
				heatMap
			}
		};

		return new NavigationPage (new ContentPage () {
			Title = "Behavior",
			Padding = new Thickness (0, 5, 0, 0),
			Content = new ScrollView () { 
				Content = stack
			}
		});
	}

	public void SetupHeatMap()
	{
		heatMap = new Grid () {
			ColumnSpacing = 2,
			RowSpacing = 2,
			VerticalOptions = LayoutOptions.FillAndExpand
		};

		Enumerable.Range (1, 25).ToList ().ForEach (x =>
			heatMap.RowDefinitions.Add (
				new RowDefinition { Height = GridLength.Auto }
			));

		Enumerable.Range (1, 8).ToList ().ForEach (x =>
			heatMap.ColumnDefinitions.Add (new ColumnDefinition { 
				Width = new GridLength (1, GridUnitType.Star) 
			}));
	}

	private void AddHoursColumn()
	{
		var hours = AppData.Hours;

		for (int i = 0; i < 24; i++) {
			heatMap.Children.Add (new Label () { 
				Text = hours [i],
				Style = AppStyles.HoursLabelStyle
			}, 0, i + 1);
		}
	}

	private void AddWeekDayRow()
	{
		var days = AppData.Days;

		for (int i = 0; i < 7; i++) {
			heatMap.Children.Add (new Label () { 
				Text = days [i],
				Style = AppStyles.DaysLabelStyle,
			}, i + 1, 0);
		}
	}

	private void AddHeatSquares()
	{
		var values = AppData.Values;
		var colors = AppStyles.Colors;

		for (int i = 0; i < 7; i++) {
			for (int j = 0; j < 24; j++) {
				heatMap.Children.Add (new BoxView () { 
					Color = colors [values [i, j]],
					HeightRequest = 15
				}, i + 1, j + 1);
			}
		}
	}
}

The majority of the sample code deals with the setup and labeling of the Xamarin.Forms Grid. The only tricky bit was using the Enumerable.Range to loop through the days and hours for the labels. You can replace these with ForEach blocks if you like.

I’ve never needed a heat map for my applications but when I do, I’ll be ready. How about you? Have you ever used a heat map?

PS. I just want to say thank you for visiting my blog. I hope you find it helpful. If you have a question, please ask.

Xamarin.Forms in Anger Series

Can Xamarin.Forms produce good looking cross-platform UI from a single codebase? 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. InAnger-Strip-5

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

May 03, 2015 1:00 GMT

NuGet Support in Xamarin Studio 5.9

Changes

  • NuGet 2.8.3 support
  • Always show Packages folder in Solution window
  • Target framework change detected on project reload

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

NuGet 2.8.3 support

Xamarin Studio now supports NuGet 2.8.3. This allows a NuGet package to target NuGet 2.8.3 explicitly. For example the PCLStorage 1.0.1 NuGet package will not install into Xamarin Studio 5.8, since it requires NuGet 2.8.3, but will install into Xamarin Studio 5.9.

NuGet packages, such as xunit, that target the new ASP.NET target frameworks, ASP.NetCore 5.0 and ASP.Net 5.0, can now be installed into Xamarin Studio now that it supports NuGet 2.8.3. Previously you would see an error message in the Package Console window:

'xunit.core' already has a dependency defined for 'xunit.extensibility.core'.

Support for NuGet 2.8.5 is planned for Xamarin Studio 5.9.1.

Always Show Packages Folder in Solution window

The Packages folder is now always shown in the Solution window even if the project has no NuGet packages. Previously the Packages folder would only be shown if one or more NuGet packages were installed in a project.

Packages folder in Solution window

Target Framework Change Detected on Project Reload

Xamarin Studio will detect a project file has been changed outside of Xamarin Studio and will reload the project. Now Xamarin Studio on reloading will detect the project’s target framework has been changed and will check the NuGet packages are compatible with the new target framework. Previously Xamarin Studio would only check the compatibility of NuGet packages if the target framework was changed from within Xamarin Studio via the project options.

This allows Xamarin Studio to check the NuGet packages are compatible when an iOS Classic project is converted to an iOS Unified project using Xamarin Studio’s migration tool. The NuGet packages, such as Xamarin.Forms, can then be retargeted by Xamarin Studio using the Retarget menu.

May 03, 2015 12:03 GMT

Introducing SVQXDG

Going back from past dotNet Conference Spain 2015, Javier Suárez and I shared our passion on Xamarin at the train’s cafeteria. We both liked the idea of having a local user group where talking about our projects made with Xamarin, which are the latest news, meet some other people doing the same things, etc.

Today I would like to introduce Sevilla Xamarin Developer Group, specially our first meetup, this following Wednesday 6th. We will have people who are landing from Build 2015, and it is thrilling for me to chat with those since the past days have been quite interesting for cross-platform mobile developers.

SVQXDG

If you are around Seville during this week (hey Andalusians we are looking at you!), and would like to attend, please visit our Meetup group and join us! Thank you!


May 02, 2015 6:40 GMT

Voice Dictation with WatchKit and Xamarin

Apple Watch has fantastic support for converting speech to text. However, there isn’t any direct API access to the text to speech engine in WatchKit. You can get access to it in your apps though via the Apple provided text input controller.

golf watch text input

You can open a text input controller via WKInterfaceController’s PresentTextInputController method. For example, here’s how I show a list of golf course names to start a new golf round in my app GolfWatch:


PresentTextInputController (courseNameList.ToArray (), WKTextInputMode.Plain,
delegate(NSArray results) {
// ...
}
});

In this case a list of course names is displayed along with a button, which when tapped opens a ui to receive speech input. The results are passed to the completion method specified in the third argument to PresentTextInputController. If you only want speech input, simply pass an empty suggestions array in the first argument and the user will be taken directly to the speech input screen on the device (speech input isn’t supported in the simulator).


May 02, 2015 4:16 GMT

Using compiled bindings in your Windows 10 universal app

One of the news in the Windows 10 SDK is that you can use compiled binding. In pre Windows 10 bindings was created in run time. When you’re building your windows universal app for windows 10 you can created bindings in compile time. This to boost the performance of the bindings, compiled bindings will make the page load much faster. This blog post will introduce you with the basics of compiled bindings.

To create a binding that will be created in compile time you will use x:Bind instead of Binding to create the binding.

      <TextBlock Text="{x:Bind Title}" />

One big difference against is that the binding will not be to DataContext, it will be to the page. If the code above should work you have to create a Title property in the code behind file. If you don’t do that you will get a error when you compiling your app. The reason to to bind to the actuall page instead of DataContext is that DataContext is of type object and the compiler will not know what you will assign to it during run time. Because you binding to the actual page it is also possible to bind directly to other controls on your page.

If you using a binding in a data template you have to specify data type for the data template with x:DataType as in the code below. Don’t forget to declare the namespace for your data type. In this example I have created a property in my code behind file called ViewModel that has a Items property that I binding to the ItemsSource of the ListView.

<ListView ItemsSource="{x:Bind ViewModel.Items}">  
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="model:ItemModel">
                        <TextBlock Text="{x:Bind Title}" />
                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

The code behind can looks like the code below. In this example DataContext is set when the view is created and the ViewModel will have a method for loading data.

public sealed partial class ItemsView
{
        protected ItemsViewModel ViewModel { get { return DataContext as ItemsViewModel; } }
 
        public ItemsView()
        {
            this.InitializeComponent();
            DataContextChanged += ItemsView_DataContextChanged;
        }
 
        private async void ItemsView_DataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args)
        {
            if(ViewModel != null)
            {
                await ViewModel.LoadData();
            }
        }
}
May 01, 2015 5:33 GMT

Developer Rig Giveaway Winners

After 913 submissions from 485 entrants, we’re happy to announce the randomly selected winners of our Build 2015 developer rig contest!

Build 2015 Xamarin Developer Rig Winners

The winning tweets were:

Cameron VetterCameron Vetter from Wisconsin, USA: @xamarinhq I’m standing in line for the keynote at #bldwin thanks for the great year of mobile development
 
 
 
 
 
 
Thimo BuchheisterThimo Buchheister from Germany: Now waiting to meet Alex from Xamarin partner program – still wearing my Xamarin Shirt ;-) @xamarinhq #bldwin
 
 
 
Robb SchieferRobb Schiefer from Alabama, USA: Selfie @bldwin in my @xamarinhq tshirt #azure #build2015 #visualstudio
 
 
 
 
 
Congratulations to our three winners, and a big thank you to everyone who participated in the contest – we loved seeing all of your submissions!

The post Developer Rig Giveaway Winners appeared first on Xamarin Blog.

May 01, 2015 2:56 GMT

Damn it! Can’t you make your code less complex?

<Rant>

I am so tired of complex code that can’t be read without having to trace definitions within definitions withshutterstock_132360455in references, within Interface definitions within indirection….  until I have no flippin’ idea what is going on.

This is even worse when perpetrated in sample code.  Can someone please tell sample code writers that the rule is “make it as simple as possible and demonstrate only one thing; and that one thing is not how clever you are.”

Continued

 

 

May 01, 2015 1:27 GMT

Weekly Xamarin Newsletter Issue #38

Objective-C Categories in Xamarin.iOS
Adam Kemp shows you how to do the difficult and impossible with C#.

Xamarin.Forms TableView Recipe – with Bacon
I (Adam) save my bacon and my pride with Xamarin.Forms TableView.

Xamarin Passes 1 Million Developer Milestone
Nat Friedman, from Xamarin Inc., announced that Xamarin passed 1 million developers.

Creating a Xamarin Forms Accordion Control, without custom renders
Jonathan Yates gets creative without using custom renderers in Xamarin.Forms.

Sara Silva Xamarin Workshop Guide

7. Add support for WinRT Apps
8. Change the App.cs to App.xaml
9. Use MVVM pattern

Xamarin.Forms RelativeLayout Recipe
I (Adam) put my dog Alabama in the spotlight for Xamarin.Forms.

Delivering High Quality Apps with Every Submission
Michael James gets serious about testing with Xamarin Test Cloud.

Taming The Android Activity, Part 1
Adam Kemp gets back to basics with Android’s core building block, the Activity.

CocosSharp Beginner Series : Setup your Machine
XHackers Team shows you how to get up and running with CocosSharp.

Setting up a VPN server on a Mac and using it for #Xamarin.iOS development
Laurent Bugnion, from GalaSoft, gives Windows uses more options when developing for iOS.

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

May 01, 2015 1:41 GMT

Combining Xamarin Forms with Windows Universal Apps

One of the most exciting news at this years //Build/ conference was Microsofts commitment to Universal Apps. One binary and one store for all Windows 10 devices available, ranging from a Rasberry Pi to Xbox.

This did however raise a concert from my part. What will the integration with Xamarin and specifically Xamarin Forms look like?

The way I would most probably suggest, knowing what I know today, is to create a Xamarin Forms project but drop the Windows Phone project and create a universal project to represent the windows platform. You might want to keep the WP project if you want to support WP 8.0 (silverlight) though.

I would also use a Mvvm-framework, like MvvmCross or MvvmLight to share ViewModels between all projects. I still think MVVM is the way to go to achive the most code share possible.

It's also going to be interesting to see what Xamarin Forms for Windows is going to target in the end.

Bottom line, it looks like you are going to have build two sets of UIs from now on...
April 30, 2015 3:37 GMT

Objective-C Categories in Xamarin.iOS

One of the cool things about Objective-C is how dynamic it is. This includes the ability to add methods to classes that already exist even at runtime. Categories are a feature of Objective-C that can be used to do all kinds of things that might otherwise be difficult or impossible, but until very recently this feature has been inaccessible from C#. This post will explain what categories are, what they're used for, how to use them in C# using Xamarin.iOS 8.10, and a useful example.

What are Categories?

A category in Objective-C allows you to add a method to a class that already exists. This method can then be called from other code as if that method were a normal method on the original class. For example, you could add a ROT13 method to NSString. In Objective-C that would look like this:

@interface NSString (ROT13)

-(NSString*)rot13;

@end

@implementation NSString (ROT13)

-(NSString*)rot13
{
// ...
}

@end

Once you've written that code anyone who knows that this method exists (by #importing the right header) can call this method on any NSString:

self.textField.text = [self.textField.text rot13];

Categories vs. Extension Methods

Objective-C categories are similar to C# extension methods. An extension method is also a way of adding a new method to an existing class in C#. For instance, you could add the same kind of ROT13 method to the C# string class like this:

public static class MyStringExtensions
{
public static string Rot13(this string input)
{
// ...
}
}

And then any code that has access to MyStringExtensions can call that method on any string:

textField.Text = textField.Text.Rot13();

Obviously these two features are very similar, but there are a few key differences. One of the biggest differences is that an Objective-C category is treated just like any other method, and every method in Objective-C is virtual. Therefore category methods are also virtual, which means you can define one for a class and then a subclass can override it like any other method. Likewise, you can use a category to override a method from a parent class from outside that class.

For example, consider these classes:

@interface Parent : NSObject

-(void)doSomething;

@end

@interface Child : Parent

@end

@implementation Parent

-(void)doSomething
{
NSLog(@"Parent");
}

@end

@implementation Child

@end

With this code it is obvious that calling doSomething on an instance of Child will print "Parent" because the child class doesn't have its own implementation. Using a category, however, you could add an implementation from some other file (even if you don't have the source code to either class) like this:

@interface Child (MyCategory)

-(void)doSomething;

@end

@implementation Child (MyCategory)

-(void)doSomething
{
NSLog(@"Child");
}

@end

Now if you call doSomething on an instance of Child you will see "Child" printed.

Another difference between extension methods and categories is that extension methods are just syntactic sugar for calling a normal static method. That is, these two lines compile to the exact same code:

textField.Text = textField.Text.Rot13();
textField.Text = MyStringExtensions.Rot13(textField.Text);

The method isn't really added to string, and if you use reflection you won't see it listed. On the other hand, Objective-C categories are just like any other method in Objective-C, which means if you use the runtime to list the available methods for NSString you would find your rot13 method listed.

Categories in Xamarin.iOS

Starting in Xamarin.iOS 8.10 you can now create your own categories from C#. This allows you to do some things in C# that you previously might have to resort to writing some Objective-C code to do (see below for a useful example).

The syntax for writing categories in Xamarin.iOS is actually the same as writing an extension method but with a few added attributes. Here is our ROT13 category again in C# this time:

[Category(typeof(NSString))]
public static class MyStringExtensions
{
[Export("rot13")]
public static NSString Rot13(this NSString input)
{
// ...
}
}

The cool thing is that this method is now both an extension method and a category. That means that you can call if from C# code:

textField.Text = textField.Text.Rot13();

and from Objective-C:

self.textField.text = [self.textField.text rot13];

Example: Find The First Responder

Like most UI platforms, iOS has the concept of a focused element. There is a class called UIResponder that has methods for things like touch events and deciding what kind of keyboard to show and so on. At any given moment in time there is exactly one of these responder objects that is the "first responder"1. For example, when a UITextField gains focus it becomes the first responder (by calling BecomeFirstResponder()), which ultimately triggers the keyboard to appear. The keyboard can then ask the first responder which type of keyboard should appear.

However, there is an annoying gap in the iOS API for responders: there is no public API for getting the first responder. That is, while the iOS keyboard can ask the first responder which type of keyboard should appear there is no way for your code to even know what the first responder is so that you can ask the question.

However, there is a way to work around this by using categories along with the UIApplication SendEvent method. SendEvent lets you send a message up the responder chain starting from the first responder. "Sending a message" in Objective-C means "calling a method" so this lets you call a method on the first responder. The trick then is to call your method on the first responder, and you can do that if you create a method just for that purpose. Once your method is called you have access to the first responder in the this variable, and you can send that back to the sender.

Here is what it looks like:

/// <summary>
/// Utilities for UIResponder.
/// </summary>
public static class ResponderUtils
{
internal const string GetResponderSelectorName = "AK_findFirstResponder:";
private static readonly Selector GetResponderSelector = new Selector(GetResponderSelectorName);

/// <summary>
/// Gets the current first responder if there is one.
/// </summary>
/// <returns>The first responder if one was found or null otherwise..</returns>
public static UIResponder GetFirstResponder()
{
using (var result = new GetResponderResult())
{
UIApplication.SharedApplication.SendAction(GetResponderSelector, target: null, sender: result, forEvent: null);
return result.FirstResponder;
}
}

internal class GetResponderResult : NSObject
{
public UIResponder FirstResponder { get; set; }
}
}

[Category(typeof(UIResponder))]
internal static class FindFirstResponderCategory
{
[Export(ResponderUtils.GetResponderSelectorName)]
public static void GetResponder(this UIResponder responder, ResponderUtils.GetResponderResult result)
{
result.FirstResponder = responder;
}
}

What I'm doing here is adding a method (using a category) to UIResponder, and then I'm calling that method by using SendEvent. Since the call is going to ultimately come from Objective-C I'm using the Selector (the name of the method in Objective-C2) to tell it which method to call, and that Selector matches the string I used in the Export attribute.

When my category method is called the first responder is the this argument of the extension method. Once I have that I just need to somehow send it back to the code that called SendEvent. For that I use a temporary container class allocated in the caller and sent as an argument. The category method just pokes the this argument into the container, and then the caller will have access to it.

There is a complete example of this on GitHub. In the full example application I use GetFirstResponder to find which text field got focus when the keyboard is shown, and I use that to change a property of the text field. This is easier than handling an event on each text field separately. You could also use this to find the view that has focus in order to scroll so that the focused view remains visible.

Summary

Categories are a powerful feature in Objective-C, and now that they are available to C# developers there are all kinds of possibilities for what you can do that was just not possible before (without writing Objective-C).


  1. The word "first" is used because the responders actually form a linked list called the "responder chain", and events can propagate up the responder chain. The responder chain usually mirrors the view hierarchy, but other objects like view controllers, the application delegate, and the application itself also participate in the responder chain. 

  2. For more information about Objective-C selectors, how the runtime works, and how Xamarin.iOS is implemented see this video

April 29, 2015 10:36 GMT

1 Million Developers, Xamarin.Forms UAP, & I’m Speaking at Build!

Whoa! What an amazing day! Today Xamarin reached 1 Million Developer downloads, released awesome new Xamarin.Forms goodness, and tons of other updates to kick off Build. If you didn’t see the full announcement be sure to check it out on the Xamarin Blog.

If you are here at Build I hope that you are sporting that awesome Xamarin shirt from the Xamarin Build party. 

I am honored to be giving two presentations at this years Build, including a sessions with one of my favorite people in the entire world, Miguel de Icaza.

Be sure to stop by the Xamarin booth and say hi and come to one of my presentations on Friday!

Building Multi-Device Apps with Xamarin and Office 365 APIs

  • Date: May 1, 2015 from 9:00AM to 10:00AM
  • Day 3
  • Room 2014
  • 3-661

Go Mobile with C#, Visual Studio, and Xamarin

  • Date: May 1, 2015 from 2:00PM to 3:00PM
  • Day 3
  • Hall1 B
  • 3-770
April 29, 2015 5:46 GMT

Visual Studio Code with Xamarin on a Mac

Microsoft just announced a new cross-platform editor that has many of the features of Visual Studio called Visual Studio Code. I downloaded it on my Mac to try out with a Xamarin.iOS project and see if it works. I was pleased discover it works out of the box (as far as I can tell on a first look).

Visual Studio Code works against files and folders. When you open a folder where a Xamarin.iOS project lives, all the files load fine and features such as links to references and even intellisense on iOS classes work great.

Here’s a class that implements a UIView subclass for example showing intellisense on CALayer:

vscode

You can download Visual Studio Code at: https://code.visualstudio.com/Download


April 29, 2015 12:00 GMT

Xamarin.Forms RelativeLayout Recipe

Xamarin.Forms RelativeLayout

In a recent “In Anger” blog post, I used the Xamarin.Forms RelativeLayout as my page layout. You might say I got carried away with the layering of UI elements in that post but I love the way it turned out.

Xamarin.Forms RelativeLayout

One of the key benefits of the Xamarin.Forms RelativeLayout is the ability to overlap or layer UI elements. The other benefit is how you can layout UI elements based on their parent’s position and dimensions as well as other view position and dimensions.

Xamarin.Forms Constraint.Constant

Let’s take a look at a simple example of adding 4 colored circles to a Xamarin.Forms RelativeLayout that takes up the whole ContentPage. We will be relying on the Constraints class. The first sample will use the Constraints.Constants exclusively.

layout.Children.Add (
	blue,
	Constraint.Constant (50),
	Constraint.Constant (50),
	Constraint.Constant (100),
	Constraint.Constant (100)
);

layout.Children.Add (
	navy,
	Constraint.Constant (150),
	Constraint.Constant (50),
	Constraint.Constant (100),
	Constraint.Constant (100)
);

layout.Children.Add (
	orange,
	Constraint.Constant (50),
	Constraint.Constant (150),
	Constraint.Constant (100),
	Constraint.Constant (100)
);

layout.Children.Add (
	green,
	Constraint.Constant (150),
	Constraint.Constant (150),
	Constraint.Constant (100),
	Constraint.Constant (100)
);

Xamarin.Forms RelativeLayout 4 colors

The results of our experiment is a simple layout with four circles. The four child views are laid out in the RelativeLayout according to the X, Y, width and height constants.

The constant constraint gives you the ability to control the placement of your views but it’s not very relative is it? I had to calculate the placement of each of the circles by getting the X and Y coordinates and adding the height and width where appropriate.

In the Xamarin.Forms in Anger – Woofer post I did, I used constant constrains but only for the X and Y coordinates of the elements that needed to start at 0,0. Most of the time I used the RelativeToParent or RelativeToView constraints.

Xamarin.Forms Constraint.RelativeToParent

Now that we’ve seen the constant constraint, let’s use the RelativeToParent constraint. This constraint looks a little different because you use a Lambda to return the value for either the X, Y, width or height. Let’s take a look.

layoutCenter.Children.Add (
	blue,
	Constraint.RelativeToParent ((parent) => {
		return (parent.Width * .5) - 50;
	}),
	Constraint.Constant (50),
	Constraint.Constant (100),
	Constraint.Constant (100)
);

layoutCenter.Children.Add (
	navy,
	Constraint.RelativeToParent ((parent) => {
		return (parent.Width * .5) - 50;
	}),
	Constraint.Constant (150),
	Constraint.Constant (100),
	Constraint.Constant (100)
);

layoutCenter.Children.Add (
	orange,
	Constraint.RelativeToParent ((parent) => {
		return (parent.Width * .5) - 50;
	}),
	Constraint.Constant (250),
	Constraint.Constant (100),
	Constraint.Constant (100)
);

layoutCenter.Children.Add (
	green,
	Constraint.RelativeToParent ((parent) => {
		return (parent.Width * .5) - 50;
	}),
	Constraint.Constant (350),
	Constraint.Constant (100),
	Constraint.Constant (100)
);

Xamarin.Forms RelativeLayout 4 colors centered

Does this sample picture remind you of shish kabob? No! It’s making me hungry just looking at it. Maybe it’s time for a snack.

Each RelativeToParent constraint is passed the parent view. In this example, we want to center our colored circles.

To do that, we get half of the parents width and subtract half of our colored circles width to get a starting X position.  When we apply that value to the X of our circle, it becomes centered in the parent view.

For the Y coordinate, we are still calculating the offset by hand.

Xamarin.Forms Constraint.RelativeToView

To free ourselves from calculating our Y position, we can use another views Y position and add its height to get its lower Y position. We will still need to set the first circles Y by hand.

layoutRelativeToView.Children.Add (
	blue,
	Constraint.RelativeToParent ((parent) => {
		return (parent.Width * .5) - 50;
	}),
	Constraint.Constant (50),
	Constraint.Constant (100),
	Constraint.Constant (100)
);

layoutRelativeToView.Children.Add (
	navy,
	Constraint.RelativeToParent ((parent) => {
		return (parent.Width * .5) - 50;
	}),
	Constraint.RelativeToView (blue, (parent, view) => {
		return view.Y + view.Height + 10;
	}),
	Constraint.Constant (100),
	Constraint.Constant (100)
);

layoutRelativeToView.Children.Add (
	orange,
	Constraint.RelativeToParent ((parent) => {
		return (parent.Width * .5) - 50;
	}),
	Constraint.RelativeToView (navy, (parent, view) => {
		return view.Y + view.Height + 10;
	}),
	Constraint.Constant (100),
	Constraint.Constant (100)
);

layoutRelativeToView.Children.Add (
	green,
	Constraint.RelativeToParent ((parent) => {
		return (parent.Width * .5) - 50;
	}),
	Constraint.RelativeToView (orange, (parent, view) => {
		return view.Y + view.Height + 10;
	}),
	Constraint.Constant (100),
	Constraint.Constant (100)
);

Xamarin.Forms RelativeLayout 4 colors relativetoview

I had to add some space between the circles to remove the shish kabob effect.

Now that we are using the RelativeToView constraint, we no longer have to do the math to figure out where our next circle needs to start. This is a handy way of laying out a UI especially if you’re calculating sizes by the percentage of screen heights, like in the “Woofer” post.

One issue you might run into is a view sent to the RelativeToView constraint has no width or height. The problem happens when the view you’re depending on is not laid out into the RelativeLayout.

To fix this issue you will need to hook into the SizeChanged event on the dependent view and force the RelativeLayout to redo the layout of all child views.

I have only scratched the surface of what you can do with the Xamarin.Forms RelativeLayout. In the future, I’ll have more posts on the RelativeLayout, especially on how to use percentages of the screen for layout and layering UI elements.

Now, where can I get shish kabob in Phoenix?

 

Download the Xamarin.Forms RelativeLayout Example Project

The Xamarin.Forms Cookbook Series

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

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

April 29, 2015 6:15 GMT

Xamarin Passes 1 Million Developer Milestone

Today we announced that over 1 million unique developers have downloaded Xamarin since we started shipping C# for iOS and Android in July 2011. In addition to passing this major milestone, we are excited to announce some amazing new features that you can get today.

Xamarin reaches 1 million downloads

Xamarin.Forms for Windows

Xamarin.Forms for Windows 8.1 and Windows Phone 8.1

This March, we released Xamarin.Forms for Windows and Windows Phone Preview with a very positive response from developers. Today, we are pleased to announce the general availability of support for these platforms, enabling developers to build and ship Xamarin.Forms apps targeting all of the major mobile platforms from a single code base. Xamarin.Forms for Windows and Windows.Phone will be available to install via NuGet later today.

Hanselman.Forms on All Devices

Availability of Private Previews of Xamarin.Forms for Windows 10 UAP

In addition to the stable release of Windows 8.1 and Windows Phone 8.1, we’re also announcing the start of a private preview of Xamarin.Forms for the Windows 10 Universal App Platform, enabling developers that build apps for all Windows platforms to share even more code. This is a very early preview and we’ll be making the Xamarin.Forms for Windows 10 pre-release packages available to small batches of developers over the coming weeks. If you’re interested in joining our preview program, please sign up here.

New Visual Studio Features

Code Completion for Xamarin.Forms XAML

Declarative UI development in Visual Studio gets even more powerful with code completion for Xamarin.Forms. Now you can easily explore Xamarin.Forms user interface APIs, quickly build complex screens, and avoid typos and other common mistakes while creating UIs in XAML.

XamlCodeCompletion

Microsoft Visual C++ Debugger Integration

We’ve worked with the Visual C++ team at Microsoft to make it easy to reference and debug C++ libraries in Xamarin.Android apps. In the Visual Studio 2015 Release Candidate, you will now find a new option to pick which debugger you would like to use when running your Xamarin.Android apps from the project’s property window. Simply choose Microsoft and you will be able to debug through your native C++ library with all of the debug features you know and love, including expression evaluation, watch window, and auto window.
DebugCppAndroid

Enhanced WatchKit Support

Our iOS designer in Visual Studio is now fully enabled for editing Apple Watch storyboards. Drag interface controllers and UI controls onto the storyboard from the Visual Studio Toolbox and configure properties on the Properties pad and use control + drag to move buttons, tables, or interface controllers onto another interface controller to create segues.watchdesigner-vs

iOS Binding Projects

When developing iOS projects in Visual Studio, you might encounter cases where you want to consume a third-party Objective-C library. In those situations, you can now use Xamarin.iOS Binding Projects in Visual Studio to create a C# binding that will allow you to consume the library in your Xamarin.iOS apps.

Get Started With Xamarin Today

Join over 1 million developers by downloading your free trial of Xamarin to build native iOS, Android, Mac, and Windows apps today. Then, head over to our developer portal where you’ll find samples, documentation, and upcoming events to help you get started with Xamarin.

The post Xamarin Passes 1 Million Developer Milestone appeared first on Xamarin Blog.

April 28, 2015 6:58 GMT

Delivering High Quality Apps with Every Submission

Have you ever uploaded an app for review and had it rejected? Or worse, fail in the hands of users? The former can cause delays to shipping your newest release and the latter can taint an otherwise great brand.

Rejection

I have personally experience a slew of these issues with the several apps I’ve published. Most recently, I had an app review failure when attempting to prepare Dutch Spelling for release. I manually tested the app on my local devices (an iPhone 5s and an iPhone 4) where it looked fantastic and ran without any issues. I was ready to upload it to the app store for review, as I thought it was ready for publishing, but apparently it wasn’t! I hadn’t tested the app on any newer devices or outside of my development devices. Having released a version of Dutch Spelling a few years ago that crashed on launch, and in turn learning all about Apple’s expedited review process, I wanted to make sure I didn’t have another case of “It works on my machine.”

An Easy Solution

I knew it was about time that I took testing seriously and stopped thinking of it as an afterthought to the development process. It’s easy to get carried away in the excitement of seeing the app run locally without any issues and forget that more device configurations exist in the wild. I could have purchased more devices to test on locally, but if I app want to target Android in the future, I would need 134 devices just to get coverage of the most popular devices in the US alone. This clearly wasn’t a scalable solution or a problem that’s easily tackled in-house. Instead, I opted to use Xamarin Test Cloud, where I knew I could run my app on every iOS device ever released. If I port the app to Android in the future, I’ll have the option of thoroughly testing on the huge array of constantly-updated devices available on the platform.

Getting Started

There are two parts to Xamarin Test Cloud, the local UITest authoring and the remote device cloud. I created the UITests locally and tested them within the iOS simulator, where everything seemed to work perfectly. At this point, it’s easy to assume that it’s ok to submit the app for review, but I still wanted to know if the app worked as expected across all devices.

Screen Shot 2015-04-28 at 18.23.25

My initial reaction to seeing the dashboard was one of elation, as it appeared on first glance that all the tests had passed as expected. However, on further inspection I could see that the custom views were being drawn incorrectly. I hadn’t accommodated for the differences in width between the iPhone 5 and the iPhone 6 (Plus). This is a fairly common issue for iOS developers at the moment as it has historically been very easy to use hardcoded position values when developing for iOS.

First TestCloud - Dutch Spelling

In order to save time and release the app as quickly as possible, I updated my custom controls to offset the position values based on the size of the screen. Although this isn’t a forever solution, it does allow me to submit the app and know it will look great on all iPhones. In the future, I’ll move the custom controls to Storyboards, which will make layouts much more flexible. Here’s an updated screenshot of how the devices looked after the update:

Screen Shot 2015-04-28 at 18.30.30

 

You can see the app now looks great across every device, no matter what the width, and I can rest assured that it works on devices outside of my office. Not only is Xamarin Test Cloud a fantastic way to find bugs in your apps before you ship them, but it doubles (as we’ve seen here) as a way to check how your app looks on different devices.

Learn more

If you’re interested in learning more about Xamarin Test Cloud features and how to get started, you can find lots of information in our developer center or request a demo from our team.

The post Delivering High Quality Apps with Every Submission appeared first on Xamarin Blog.

April 27, 2015 8:44 GMT

The best design is no design at all: AppleWatch Edition

No, not THAT AppleWatch Edition. From Supertop, makers of Unread

One Less Thing… We spent a lot of time not making a Watch app. We love our new wrist computers but they are not the place for reading articles.

This. 100 times this. So many of the watch apps I've seen - and Today Extensions - should never have been written. Just because you CAN write a Watch extension, doesn't mean you should, especially if all it does is launch your phone app (ahem Evernote).

Out of my three remaining apps:

  • Nearest Bus is a prime candidate for a watch app. That's next on my list.
  • Trip Wallet should never have one. Ever. No reason at all.
  • MobileAgent could - starting a timer or mileage maybe, but otherwise, no. If there was a way to get realtime, pushed bank account info that might be somewhat useful, but really, it's just a notification.

And of the ones I work in at the day job (not that I have much say in which ones would get it):

  • goMoney - balances and transfers maybe, but as there is no push of information to the phone (and hence watch), it's not overly useful (IMO - the company might think otherwise). It's just a notification in the end (and how often do you do a transfer?)

So think carefullly about if a Watch app - or a Today Extension for that matter - even makes sense1 before you commit to making one.


  1. It might be that it doesn't make UX/technical sense, but it has marketing value. Thats fine, I guess.... ¯\_(ツ)_/¯

April 27, 2015 2:59 GMT

Monday morning i San Francisco

Today it’s the second day in San Francisco. The day started early with running, the second run with my new Microsoft Band (I bought it the first I did when we arrived). I really enjoy it. I have a lots of ideas how to use Microsoft Band in my apps.

Right now we’re sitting in the hotel lobby (me, Karl-Henrik, Johan and Anders) and writing code, Johan is working on new cool Xamarin.Forms control for iOS and I will start to write the Windows Phone implementation for it.

On Wednesday the Build conference will start, the reason for our trip to San Francisco. Really looking forward to it. The key note was amazing last year and I think it will be at least so amazing this year.

April 27, 2015 2:32 GMT

Xamarin.Forms and iOS segemented control

A common control in many iOS apps is the segmented control. Xamarin.Forms has no support for the segemented control out of the box. This blog post will show you how to create a control in Xamarin.Forms that is mapped to UISegmentedControl in iOS.

In my sample I have named the control, FilterControl because is often used as a filter control and if you write a implementation of the control on the other platforms it will maybe not look lite the segmented control.

To make the control usefull I need to be able to bind items to it, bind to selected index, have an event that is thrown when selected index is changed and be able to change the color.

The first I will do is to create a class in the shared project that inherits from View.

If the properties will be bindable you have to create a BindableProperty as shown in the code below.

To set the choises (items) of the control we’re creating a List of strings.

public static readonly BindableProperty ItemsProperty =
			BindableProperty.Create<FilterControl, List<string>>
		(p => p.Items, new List<string>());
 
public List<string> Items 
{
	get 
        {
		return GetValue (ItemsProperty) as List<string>;
	}
	set 
        { 
		SetValue (ItemsProperty, value);
	}
}

When the control is defined next step is to create a renderer for iOS. The renderer will inherit from ViewRenderer.

public class FilterControlRenderer : ViewRenderer<FilterControl, UISegmentedControl>

In the override of the OnElementChanged we will create the native control, UISegmentedControl. I will put the code to map the list of choises to the segment control in a separate private method so I also can use it if the list of choices is changed. Then I will call it from the override of the OnElementPropertyChanged method.

You need to listen to ValueChanged of the UISegmentedControl so you can write the value back to the Xamarin.Forms control. In the event for selection changed I want both the old and new value, there for will I dont set selected index from the renderer. Instead I call a method in the control that is setting SelectedIndex and throwing the selection changed event.

protected override void OnElementChanged (ElementChangedEventArgs<FilterControl> e)
{
	base.OnElementChanged (e);
 
	var segmentControl = new UISegmentedControl ();
        SetNativeControl (segmentControl);
 
	UpdateSegments ();
 
	segmentControl.SelectedSegment = Element.SelectedIndex;
	segmentControl.SizeToFit ();
 
	segmentControl.ValueChanged += (object sender, EventArgs args) => 
	{
		if(segmentControl.SelectedSegment != Element.SelectedIndex)
		{
		     Element.OnSelectedIndexChanged((int)segmentControl.SelectedSegment);
		}
	};
}
 
private void UpdateSegments()
{
	Control.RemoveAllSegments ();
 
	for (int i = 0; i < Element.Items.Count; i++) 
	{
		Control.InsertSegment (Element.Items [i],i,true);
	}
}
public void OnSelectedIndexChanged(int newValue)
{
        var args = new IndexChangedEventArgs () {
		NewValue = newValue,
		OldValue = SelectedIndex
	};
 
	SelectedIndex = newValue;
 
	if (SelectedIndexChanged != null) 
	{				
		SelectedIndexChanged (this, args);
	}
}

Of course we also need to update the native control if the value for selected index is changed. That code will be placed in the OnElementPropertyChanged method.

protected override void OnElementPropertyChanged (object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
        base.OnElementPropertyChanged (sender, e);
 
	if (e.PropertyName == FilterControl.SelectedIndexProperty.PropertyName) 
	{
		if (Control.SelectedSegment != Element.SelectedIndex) 
		{
		         Control.SelectedSegment = Element.SelectedIndex;
		}
	}

The complete code can be found on GitHub, https://github.com/dhindrik/XamarinFormsSamples/tree/master/SegmentedControl

If you want the control to be in the NavigationBar on iOS read this blog post.

April 27, 2015 2:29 GMT

San Francisco

It's a beautiful Monday morning in San Francisco today! Started the day with a morning run along the piers and ended up in the hotel lobby drinking cheap coffee while working on my new cool Xamarin Forms control.

The control is a simple to use, no hassle carousel view for images that works out of the box by simply setting a list. It also comes with a framework to lazy load images on demand while keeping the memory at a minimal.

Is it done, nope not yet! But it will be available at github real soon. And perhaps I'll add it to Xamarin Forms Labs though I'm not to fund of their choice of OS license.
April 27, 2015 12:00 GMT

Xamarin.Forms TableView Recipe – with Bacon

In my day job, I’m creating a mobile application with Xamarin and Xamarin.Forms for our university students. The app displays the student’s schedule, statement, grades, campus map, and food line cameras around campus. And the Xamarin.Forms TableView saved my bacon.

Let’s just say it looked like what a bear does in the woods!

I was having a bear of a time laying out the class detail screen. Let’s just say it looked like what a bear does in the woods! Nothing was working. I was getting a little frustrated, so I opened my iPhone and started looking around for design inspiration. I found the settings app.

The settings app is a perfect example of data display and navigation hierarchy. To get that same look, you need to look no further than the Xamarin.Forms TableView. Yes, the TableView and ViewCells.

Xamarin.Forms TableView

To be completely honest, this was the first time I worked with the Xamarin.Forms TableView. Sure, I’ve used the ListView and the ViewCells before, but not the TableView.

xamarin.forms tableview

I know this is not going to win any awards, but what it is going to do is present a familiar UI to the user. The bottom half of the screen uses the built in ImageCell. When you click on the row, it takes you to the map with a pin in the building where your class will be held. Neat! Freshman will love this. No excuse for being late to class.

Custom Xamarin.Forms ViewCell

The top half of this screen uses a custom ViewCell called KeyValueCell. No built in cell fit my needs so I just created one that looked familiar by extending the ViewCell class. Two labels and a StackLayout is all it took.

public KeyValueCell (string key, string value)
{
	View = new StackLayout () {
		Padding = new Thickness(15,10),
		Orientation = StackOrientation.Horizontal,
		VerticalOptions = LayoutOptions.Center,
		Children = {
			new Label () { 
				Text = key,
				TextColor = Color.Purple,
				HorizontalOptions = LayoutOptions.StartAndExpand
			},
			new Label () { 
				Text = value,
				TextColor = Color.Gray,
				HorizontalOptions = LayoutOptions.EndAndExpand
			}
		}
	};
}

This custom ViewCell is styled for my app. The university’s color is Purple, Go Lopes!

Armed with my custom ViewCell and the built in ImageCell, the only thing left to do was to put everything together. The Xamarin.Forms TableView is composed of aptly named sections called TableSection. Each section can have a name. In my example, I put the class name for the first section and the second was “Meeting Times”. Here is what the code looks like.

MainPage = new ContentPage {
	Content = new TableView { 
		Intent = TableIntent.Form,
		Root = new TableRoot () { 
			new TableSection ("General Physics I - Lab") {
				new KeyValueCell("Course","PHY-111L"),
				new KeyValueCell("Status","P"),
				new KeyValueCell("Credits","3.00"),
				new KeyValueCell("Delivery","ONGROUND"),
				new KeyValueCell("Start Date","8/25/2014"),
				new KeyValueCell("End Date","12/14/2014"),
			},
			new TableSection ("Meeting Times") {
				new ImageCell()	{
					Text = "Monday 3:20 PM - 4:15 PM",
					Detail = "Fleming 24-106",
					ImageSource = new FileImageSource() {File = "Location.png"}
				},
				new ImageCell()	{
					Text = "Monday 3:20 PM - 4:15 PM",
					Detail = "Fleming 24-106",
					ImageSource = new FileImageSource() {File = "Location.png"}
				},
				new ImageCell()	{
					Text = "Monday 3:20 PM - 4:15 PM",
					Detail = "Fleming 24-106",
					ImageSource = new FileImageSource() {File = "Location.png"}
				}
			}
		}
	}
};

I removed the Command and CommandParameter from the sample to make it less confusing. I want you to see the TableView and not all the plumbing for navigating to the map page.

I’ve just scratched the surface of the Xamarin.Forms TableView. In a future post, I’ll cover the other three built in ViewCells and custom ViewCells. Until next time, enjoy the recipe and keep your bacon away from the bears!

Download the TableView Sample Project

The Xamarin.Forms Cookbook Series

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

The post Xamarin.Forms TableView Recipe – with Bacon appeared first on Syntax is my UI.

April 27, 2015 7:48 GMT

Say Hello To Xamarin.Forms – APAC Webinar Recording

Thanks to everyone who attended my Webinar on Say Hello To Xamarin.Forms. This is the second webinar from us which is timed to fit the APAC region. As promised, find the recording and the presentation files below.

Slides

Code Samples

WeatherCheck

In this webinar, we looked at a simple WeatherCheck sample that uses the Yahoo Weather APIs to query the weather forecast of a specified city.

Download the samples from my GitHub repository.

Have a feedback? Find me on twitter.


April 27, 2015 7:12 GMT

WWDC 2015 for a Xamarin Developer n+1 Series

WWDC-2015-invitation

How much can happen in a week? … well a lot, last week I was honoured to be announced as a Xamarin MVP, I purchased my first Apple Watch and… I’ve been lucky enough to win a golden ticket for the Apple World Wide Developers conference (WWDC). When I say win I mean pay apple $1999 AUD for the privilege to attend the conference. The ‘winning’ part is that there’s 9 million apple developers and many thousands apply to attend, so apple have a lottery in which attendee’s are selected at random.

WWDC is on June 8th – June 12th 2015, in San Francisco and will take place at Moscone West. There’s likely to be some new software announcements for iOS and OSX, possibly some more watch features and maybe even a 4K Apple TV. There’s over 100 technical sessions, 1000′s of apple engineers, hands-on labs and the apple design awards.

As an engineer I’m really keen to attend the technical sessions and get my hands dirty with some hands-on labs, maybe a little swift to c# conversion will be in order.

Given that I’ve been lucky enough to win a ticket to WWDC this year I thought it would only be fair if I shared the journey with other Xamarin developers. I’ll be giving daily overviews of different announcements and if possible providing technical detail from the conference, converting the swift applications into C# and F#.

This series of posts will be named ‘WWDC for a Xamarin Developer n+1′… Stay tuned… I think we’ll have some fun!

Michael

The post WWDC 2015 for a Xamarin Developer n+1 Series appeared first on Michael Ridland.

April 27, 2015 3:05 GMT

CocosSharp Beginner Series : Setup your Machine

CocosSharp, as explained in my earlier post is a cross-platform library for building 2D games. CocosSharp is an open source library and is built on top of the MonoGame engine and the fine work from the Cocos2D, Cocos2D-x and Cocos2D-XNA communities.

Today, we will start our CocosSharp beginner series with an introduction on How to set up your machine for getting started with CocosSharp.

First of all, you can either use Xamarin studio or Visual studio as an IDE for your game development. The only difference is Xamarin studio can be installed on Windows and Mac. But visual studio can't be directly installed on a Mac, you need virtualization tools like parallels or VMWare etc. on top of which you should run windows OS.

So, zero on your IDE and install the same.

Using Xamarin Studio

Xamarin Studio

Once you have xamarin studio installed, navigate to Add-in Manager
CS-2

As it's already installed on my machine, you see a blue check mark on the top with Disable and Uninstall buttons on the right. If you have picked a fresh machine, with Xamarin Studio just installed, Click and install "CocosSharp Project Templates". Once installed successfully, click on the first tab (Installed) and you should see CocosSharp there.
Android CocosSharp Project on Windows

On a machine running windows with Xamarin Studio installed, You will see only Android CocosSharp project types.

  • CocosSharp showcase has boilerplate code with all required packages pre-installed to get started.
  • CocosSharp empty game is a template to start your game from scratch.

On a Mac

For installing CocosSharp project templates, follow the steps mentioned above. Once installed successfully, specifically within the list of C# solutions you should now have CocosSharp projects for

  • Android
  • iOS/Classic API/iPad or iPhone or Universal
  • Mac/Classic API
  • Mobile Apps

provided you have all the necessary dependencies.

Xamarin Studio on a Mac Xamarin Studio on a Mac

Using Visual Studio

The templates are being held in a custom Visual Studio Gallery held at Mobile Essentials.

In order to get the custom gallery into your Visual Studio, open Tools | Options and configure the page Environment > Extension Manager as follows, using the gallery url http://gallery.mobileessentials.org/feed.atom:

image

Once the Mobile Essential gallery is set up, you can go to Visual Studio’s Tools | Extensions and Updates... menu and a new Mobile Essentials node will appear under the Online category, where you can explore and install the tools:

CS-05This image has been resized to fit in the page. Click to enlarge.

Click the Download button to install the highlighted extension. Once the download is complete you will get a verification screen prompting you to install the template package. Click the Install button:

image

Once installation is complete you will then see the CocosSharp Templates package marked with a little green arrow showing that it is installed.

image
This image has been resized to fit in the page. Click to enlarge.

Creating a new project

Now when creating a new project you will see a new section called CocosSharp with subcategories for:
  • Android
  • iOS
  • Windows
image

If you have created an empty CocosSharp project, right-click on From Packages | Add packages and then select platform specific CocosSharp Nuget package to get started. After successful installation, your project hierarchy should look like the one showed below. Showcase project template will look like this by default as packages will be pre-installed.

Project hierarchy with packages

Note : Check for updates before installing/updating latest packages.


Huff!!! hope everything went well with the machine setup for you. If you can't wait for the next chapter in our beginner series, Start exploring and share your experience via twitter @IAmVMac
Game ON !!!!
April 26, 2015 4:15 GMT

Taming The Android Activity, Part 1

The Activity is a core building block in an Android application, but in some cases it can be a pain to work with. This article is part one of a series showing how to deal with some of the complexities of the Activity in a clean way using some of the capabilities of C# available to Xamarin.Android developers.

Typically each screen in an Android application is represented by an Activity, and moving from one screen to another is done by starting a new Activity. In fact, the Activity and its related class Intent are the keys to Android's ability to let applications reuse pieces of other applications. That cross-application use case was the motivation behind the design of the Activity, but that design has the unfortunate side effect of making some common in-process use cases surprisingly difficult to deal with.

This series will cover three common scenarios that Android developers face in which the design of the Activity class causes problems:

  1. Dealing with device rotation (and other configuration changes)
  2. Launching and waiting for the results of another Activity
  3. Communicating between (in-process) Activitys

Each of these is very common and yet is surprisingly difficult to do on Android, especially compared to the way that view controllers work in iOS.

Configuration Changes

The Android documentation has this to say about configuration changes (emphasis added):

If the configuration of the device (as defined by the Resources.Configuration class) changes, then anything displaying a user interface will need to update to match that configuration. Because Activity is the primary mechanism for interacting with the user, it includes special support for handling configuration changes.

Unless you specify otherwise, a configuration change (such as a change in screen orientation, language, input devices, etc) will cause your current activity to be destroyed, going through the normal activity lifecycle process of onPause(), onStop(), and onDestroy() as appropriate.

What this means is that any "configuration change" will cause your Activity object to be destroyed and then recreated. What's a "configuration change"? There are actually a lot of things that count (see the complete list), but one of the most common is an orientation change. As a result, if a user rotates his device from portrait to landscape (or vice versa) then your Activity will be destroyed and recreated.

The most obvious consequence of having your Activity get destroyed is that all of the views also have to be recreated, but the most serious consequence is that all state stored in the Activity (meaning your fields and properties) will be lost, and a brand new instance of your Activity class will be created from scratch instead.

Handling Configuration Changes

There are a few approaches to dealing with this problem:

  1. Disable the behavior
  2. Serialize and deserialize your state
  3. Use a retained Fragment

The first option is to disable this behavior, which can be done by setting the configChanges property of the Activity to the configuration changes that you don't want to cause the Activity to be destroyed. This seems like a great option, and you will find many people recommending it. However, Google discourages this approach:

This technique should be considered a last resort when you must avoid restarts due to a configuration change and is not recommended for most applications.

The second option was the best approach for a while, and many apps no doubt still use this approach. When an Activity is being destroyed for a configuration change it will receive a call to OnSaveInstanceState. This method has Bundle argument that can be used to stash data using a key/value system. Basic types are supported by default, but more complex data types are difficult to deal with. Once the new Activity is created it will receive a call to OnRestoreInstanceState, which is handed the same Bundle object in order to fetch the stashed data.

The downside of this approach is that it is tedious and error prone. If you forget any fields then your application will have subtle bugs any time a user rotates his device. Ideally we could just throw a whole object from the old Activity to the new one. In fact, there is a deprecated API for doing just this (see OnRetainNonConfigurationInstance and GetLastNonConfigurationInstance), but that mechanism has been replaced by a better one.

Since Android 3.0 the current recommended solution to dealing with configuration changes is with a retained Fragment.

Fragments

A Fragment is kind of like a miniature Activity. It has a lifecycle, state, and optionally a view hierarchy. A Fragment is attached to an Activity via the Activity's FragmentManager.

By default whenever an Activity is destroyed for a configuration change its associated Fragments are also destroyed. However, you can request that a Fragment be retained by setting the RetainInstance property to true, which allows the entire object and all of its fields (but not its views) to be reused.

Therefore, the best technique for dealing with configuration changes is to actually move most of your Activity's code into a Fragment instead. The Activity is then merely a dumb shell used to create the Fragment and deal with Activity-specific issues like Intents. Here is an overview of how this technique works:

  1. When the Activity is created it uses its FragmentManager to search for an existing instance of its Fragment (identified by a tag string).
  2. If an existing Fragment was not found then a new one is created and added to the Activity.

Other than dealing with things like Intents and results from other Activitys (both to be covered in future segments of this series) the Activity class doesn't have much else to do. As you can imagine, the code to perform these steps will end up looking fairly boilerplate. In fact, this is a great opportunity for some code reuse.

Example

As an example of how to deal with this problem in a generic way let's start with the Xamarin.Android stock template that you get when you create a new application. If you run this template without any modifications then you get a simple application with a button on it. When you click the button it shows you how many times it has been clicked. In order to demonstrate the problem click the button a few times and then rotate the device. The first thing you'll notice is that the button text reverts to the original "Hello World" text. If you click the button again you'll also notice that the count starts over. This is the bug we will be fixing.

In order to fix this we will introduce two new base classes: FragmentActivity and FragmentBase. These classes can be dropped in to any application, and we will build on them further throughout this series to add other useful capabilities. For this problem, though, the classes are pretty simple. Here is the code:

/// <summary>
/// An Activity that uses a retained Fragment for its implementation.
/// </summary>
public abstract class FragmentActivity<TFragment> : Activity where TFragment : FragmentBase, new()
{
/// <summary>
/// The top-level fragment which manages the view and state for this activity.
/// </summary>
public FragmentBase Fragment { get; protected set; }

/// <summary>
/// The tag string to use when finding or creating this activity's fragment. This will be contructed using the type of this generic instance.
/// </summary>
protected string FragmentTag
{
get
{
return GetType().Name;
}
}

/// <inheritdoc />
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);

LoadFragment();
}

/// <inheritdoc />
public override void OnAttachedToWindow()
{
base.OnAttachedToWindow();
Fragment.OnAttachedToWindow();
}

/// <inheritdoc />
protected override void OnNewIntent(Intent intent)
{
Fragment.OnNewIntent(intent);
}

/// <summary>
/// Loads the fragment for this activity and stores it in the Fragment property.
/// </summary>
protected virtual void LoadFragment()
{
Fragment = FragmentBase.FindOrCreateFragment<TFragment>(this, FragmentTag, global::Android.Resource.Id.Content);
}

/// <inheritdoc />
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
Fragment.OnActivityResult(requestCode, resultCode, data);
}
}

/// <summary>
/// The base class for top-level fragments in Android. These are the fragments which maintain the view hierarchy and state for each top-level
/// Activity. These fragments all use RetainInstance = true to allow them to maintain state across configuration changes (i.e.,
/// when the device rotates we reuse the fragments). Activity classes are basically just dumb containers for these fragments.
/// </summary>
public abstract class FragmentBase : Fragment
{
/// <summary>
/// Tries to locate an already created fragment with the given tag. If the fragment is not found then a new one will be created and inserted into
/// the given activity using the given containerId as the parent view.
/// </summary>
/// <typeparam name="TFragment">The type of fragment to create.</typeparam>
/// <param name="activity">The activity to search for or create the view in.</param>
/// <param name="fragmentTag">The tag which uniquely identifies the fragment.</param>
/// <param name="containerId">The resource ID of the parent view to use for a newly created fragment.</param>
/// <returns></returns>
public static TFragment FindOrCreateFragment<TFragment>(Activity activity, string fragmentTag, int containerId) where TFragment : FragmentBase, new()
{
var fragment = activity.FragmentManager.FindFragmentByTag(fragmentTag) as TFragment;
if (fragment == null)
{
fragment = new TFragment();
activity.FragmentManager.BeginTransaction().Add(containerId, fragment, fragmentTag).Commit();
}

return fragment;
}

/// <inheritdoc />
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);

RetainInstance = true;
}

/// <summary>
/// Called when this fragment's activity is given a new Intent.
/// </summary>
/// <remarks>The default implementation does nothing</remarks>
public virtual void OnNewIntent(Intent intent)
{
}

/// <summary>
/// Called when this fragment's activity is attached to a window.
/// </summary>
/// <remarks>The default implementation does nothing</remarks>
public virtual void OnAttachedToWindow()
{
}
}

As you can see, FragmentActivity is a generic abstract class with a type parameter to specify the type of the Fragment that it should use. This class creates and holds on to the Fragment and forwards a few useful messages to the Fragment that otherwise would be handled by the Activity. The FragmentBase class is an abstract class that is used as the base class for any Fragments used by a FragmentActivity. Its static FindOrCreateFragment method, as its name implies, is used to find an existing instance of a Fragment or create a new one if one is not found. Also note that RetainInstance is set to true when this Fragment is created, which is the key to allowing the instance to be reused. The other methods are just there to receive notifications from the Activity.

The way you use these classes is simple. For each Activity you will create a pair of classes: a Fragment that inherits from FragmentBase and an Activity that inherits from FragmentActivity. The generic type argument links them together. In many cases the Activity doesn't need any additional code (it will just be an empty class), and all of the important code goes in the Fragment. To see this in action this is how I adapted the Xamarin.Android template to use these new classes (complete code):

[Activity(Label = "FragmentActivityTest", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : FragmentActivity<MainActivityFragment>
{
}

public class MainActivityFragment : FragmentBase
{
private int _count = 0;
private Button _button;

public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = inflater.Inflate(Resource.Layout.Main, container, attachToRoot: false);

_button = view.FindViewById<Button>(Resource.Id.myButton);

if (_count != 0)
{
UpdateButtonText();
}

_button.Click += delegate
{
_count++;
UpdateButtonText();
};

return view;
}

private void UpdateButtonText()
{
_button.Text = string.Format("{0} clicks!", _count);
}
}

The first thing you'll notice is that, as I mentioned before, the Activity has no code in it. Looking at the Fragment you'll notice that it looks very similar to the original code, but with a few key tweaks. Let's look at what I had to change.

The first change was the loading of the layout file. The original code looked like this:

SetContentView(Resource.Layout.Main);

SetContentView is a method of Activity, but we're not in an Activity anymore. Instead, we just have to load the layout and return it. For this purpose we are given a LayoutInflater, and we use it like this:

var view = inflater.Inflate(Resource.Layout.Main, container, attachToRoot: false);

There are two additional arguments being used here, and both are important. The first is the container ViewGroup that is passed to us as an argument to OnCreateView. This is the container in which the view we return will be inserted. The second is a boolean that tells the LayoutInflater that we don't want it to insert the inflated view into that container.1

Moving on, we have an extra bit of initialization code:

if (_count != 0)
{
UpdateButtonText();
}

This code is necessary because while the Fragment is reused across configuration changes the view is not. That means this method will be called multiple times on the same Fragment instance2, and it is up to us to initialize the view with the current state3. In order to handle this I created a field for the button and refactored the code for updating the text into a method that I can call in multiple places. Since the initial text comes from the layout file and doesn't match the format used after clicking the button I check first to see if the button has ever been pressed.

Lastly, I return the view that was created since that is needed by the Activity in order to insert it into the view hierarchy.

Summary

As you can see, this approach makes it very easy to handle configuration changes by mostly just ignoring them. The only remaining wrinkle is that the views are still destroyed and recreated, which requires a bit of extra initialization. This is necessary because the views may actually adapt to the configuration change. The good news is that we no longer have to tediously save and restore every state field.

I use this technique in every Android application I write, and it works very well. I hope that this post and the example code will help you save time dealing with the same issue.

In the next part of this series I will explain how to deal with the problem of starting a new Activity and waiting for its results.


  1. This may seem strange. Why are we passing in the container if we aren't inserting the view into it? It turns out that there is a good reason for this, which is explained in detail by this article. If you leave off the last argument the default is true, and you will get an exception because the view is inserted twice. If you pass null as the second argument then you won't crash, but your top-level LayoutParams in your layout file will be ignored. Thus we pass in the container and we tell it not to attach. 

  2. There is a corresponding method OnDestroyView, which can be used to do any necessary cleanup when the old view is destroyed during a configuration change (or when the Fragment itself is going to be destroyed). 

  3. Some views do their own saving and restoring of temporary state during configuration changes. For instance, an EditText will save the text that has been entered, the cursor location, and the current selection. This is handled by OnSaveInstanceState and OnRestoreInstanceState in the View class

April 25, 2015 3:25 GMT

Song of the Day: Press the Buzzer

DarWilliamsPress the Buzzer is based on the infamous Milgram Experiment.  This brilliant song captures the entire essence of the experiment and the fall out from it, without ever losing its compelling folk rock rhythm.

Like nearly all her music, this one is highly recommended.

I’m feeling sorry for this guy that I press to shock
He gets the answers wrong, I have to up the watts

And he begged me to stop, but they told me to go
I press the buzzer, I press the buzzer…

 

April 25, 2015 3:12 GMT

Xamarin.Forms: Incremental Search

I recently posted about obtaining data for purposes of creating demonstration programs.  IncrementalSearchFinal

That actually was written in service to today’s post, which will use that data to create a list of “people” and then allow you to search incrementally, as shown in the illustration; I typed “Jaco” and any name that contained Jaco was brought up.

This post shows two meaningful techniques: it reviews grouping and it demonstrates incremental searches.

Continued here

April 24, 2015 1:54 GMT

Weekly Xamarin Newsletter Issue #37

Lollipop Support comes to the Xamarin Android Player
Miguel de Icaza, from Xamarin Inc., introduces Lollipop support for the Xamarin Android player.

Xamarin.Forms In Anger – Woofer
I (Adam) show my layer freak flag in this layer-a-paloza blog post on Xamarin.Forms.RelativeLayout.

Xamarin.iOS Under the Hood: Calling Objective-C from C#
Jon Peppers answers the question: How does C# code call into Objective-C?

Getting apps from new Xamarin Studio, to iTunes Connect by hand
Tim Sneed gets his builds to iTunes Connect the old fashion way, by hand.

Decoupling Views In Multi-Screen Sequences
Adam Kemp gets into more advance multi-screen sequences in this post.

Win a $10k Mobile Developer Rig from Xamarin at Build 2015
Joseph Hill, from Xamarin Inc., temps you to wear your C# shirt for some serious prizes.

Join Xamarin at Microsoft Ignite 2015
Gene Miguel, from Xamarin Inc., ask’s you to join Xamarin at this year’s Ignite conference.

Sara Silva Xamarin Workshop Guide

3. Create the SessionsView
4. Create the SessionDetailsView
5. Add ShareService
6. Add splash screen, name and version

Xamarin.Forms SearchBar Recipe
I (Adam) add another Xamarin.Forms recipe to the cookbook. This time it’s SearchBar.

Adding Login/Signup Capabilities
Ruben Macias shows you an effective way to add a login page to your app.

Xamarin IOS – Authentication Using Owin, Web Api2, Json and Web Tokens
Andrei Dragotoniu goes deep into the stack for authenticating your mobile app.

Implementing John Conway’s Game of Life in Xamarin Forms
Jeff Prosise, from Wintellect, shows off Conway’s Game of Life in Xamarin.Forms.

Material Design FAB in Xamarin.Forms
Chris Riesgo pulls the Floating Action Button into Xamarin.Forms.

Xamarin Tips and Tricks #2 – Beware of Linking and Reflection
Jeffryvu reflects on development issues and build options.

Xamarin: Rate this article!
Jesse Liberty gets into some advance techniques to get his 5 stars.

Supercharging Xamarin Forms with Custom Renderers, Part 4
Jeff Prosise, from Wintellect, shows you the keys that unlock the doors to Xamarin.Forms.

Animating the TabbedView
Jonathan Yates gives us an update on his animated TabbedView.

Xamarin.Forms Pages: TabbedPage and CarouselPage
Paulo Ortins shows two more Xamarin.Forms pages in this new post.

Xamarin.Forms Android CardView
Daniel Hindrikes adds a card view from Material Design to Xamarin.Forms.

New Xamarin MVP Posts

A Warm Welcome to the Newest Xamarin MVPs
Joseph Hill, from Xamarin Inc., announces the 7 new Xamarin MVP’s.

Xamarin MVP
I (Adam) am now an Xamarin MVP!

Yes, ….. I am Xamarin MVP
Sara Silva is now a Xamarin MVP and it’s well deserved.

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

April 23, 2015 10:00 GMT

Lollipop Support comes to the Xamarin Android Player

Waiting for an emulator to boot or deploy is one of the most frustrating things about Android development. We built the Xamarin Android Player to provide a high-performance, hassle-free Android simulator, and to make Android development smooth and pleasant.

Introducing Lollipop Support

Starting today, when you launch the Xamarin Android Player you will see a brand new device image for Android 5.1 Lollipop enabling you to test against all of the latest Lollipop APIs with Material Design.

Xamarin Android Player Lollipop

Help us improve

We released our first preview in October of last year and thousands of Xamarin developers have already used it to build and test Android apps. We’ve collected a lot of feedback, and the experience has already improved a lot.

But we’re not done! Our goal is to install the Xamarin Android Player by default with Xamarin, and to replace the stock Google Android emulator with it. And we need your help. Please download the Xamarin Android Player today and give it a try. Report any issues that you find so that we can keep improving.

To learn more about the Xamarin Android Player, be sure to read the full documentation on how to get started.

The post Lollipop Support comes to the Xamarin Android Player appeared first on Xamarin Blog.

April 23, 2015 7:05 GMT

This Post Has No Value

AngerI set out to write a post on Incremental Searching in Xamarin applications (which I will do next) but along the way I realized i need a goodly amount of data to search.

This is a  problem that arises fairly often, so I wrote a quick and dirty solution which is not terribly generalizable but was fun nonetheless.

More

April 23, 2015 4:47 GMT

Win a $10k Mobile Developer Rig from Xamarin at Build 2015

Wear the new Xamarin t-shirt from the Xamarin Build 2015 Kick Off Party to Build on April 29th for your chance to win one of three Mobile Developer Rigs worth over $10,000!

Xamarin Build 2015 Developer Rig Contest Prizes

How to Enter

Attend the Xamarin Build 2015 Kick Off Party on 4/28, where you’ll receive the newly designed Xamarin t-shirt. Wear the t-shirt from the Kick Off Party to Day One of Build on 4/29, and tweet a picture of yourself wearing it at the conference with @xamarinhq and #bldwin and/or #build2015 in the text. For example: “I’ve got @xamarinhq on my shirt and mobile development on my mind at #bldwin #build2015″. All entries must be received by 11:59 pm on 4/29.

A valid entry consists of a tweet with:

  • An image of yourself wearing the new Xamarin Build Kick Off Party t-shirt at Build on 4/29.
  • The hashtag(s) #bldwin and/or #build2015 and @xamarinhq.
  • You may enter multiple times, but each entry must contain a unique image and text.

If you haven’t registered for the Xamarin Build Kick Off Party yet, you can do so below:

 

The Prizes

Each of the three winners will receive a Xamarin Mobile Developer Rig, which will include the following:

Hardware

  • 15” Macbook Pro Laptop with Retina
    • 2.5 GHz i7 Processor
    • 16GB RAM
    • 512 GB SSD
    • Apple Magic Mouse
    • Apple wireless keyboard
  • Surface Pro 3
    • 1.7 GHz
    • 8 GB RAM
    • 512GB
    • Intel Core i7
  • Ultra high-resolution 4K Monitor

Phones

  • iPhone 6
  • The winner’s choice of an equivalent Android phone
  • Windows Phone

Tablets

  • iPad Air 2
  • The winner’s choice of an equivalent Android tablet

Smartwatches

  • Apple Watch
  • Microsoft Band
  • Moto 360

One-year Xamarin subscriptions

  • Xamarin.iOS Enterprise
  • Xamarin.Android Enterprise
  • Xamarin.Mac Enterprise
  • Xamarin Test Cloud Basic
  • Xamarin University

Rules and Regulations

All entries must be submitted by 11:59 pm PT on April 29, 2015. A valid entry is a tweet that contains an image of the submitter wearing the new Xamarin t-shirt from the Xamarin Build Kick Off Party on 4/28 at Build and includes both @xamarinhq and the hashtag(s) #bldwin and/or #build2015. We will select three winners at random from the submissions. Each entry must have a unique image and text. Contestants should follow @XamarinHQ to enable us to DM you for private follow-up if you win a prize. This contest is open to individuals and there is no purchase necessary to enter.

The post Win a $10k Mobile Developer Rig from Xamarin at Build 2015 appeared first on Xamarin Blog.

April 23, 2015 12:00 GMT

Xamarin.Forms In Anger – Woofer

You think you know how much I like layering but you don’t really know. This Xamarin.Forms RelativeLayout sample is going to show you how much of a layering addict I am. I might have a problem, but you can’t deny the results. This fictitious app called Woofer has a nice profile screen with 5 full layers all stacked on top of each other.

The Blueprint

The blueprint is a little busy and I wish my graphics design skills were a little better. I wanted to do a 3d render look but could not figure out how to get it right. So we’re stuck with 2d for now. I’ll work on that. Promise.

The blueprint has 5 layer callouts. These callouts show you the different pieces and in which order they were added to the RelativeLayout. One of the benefits of using the RelativeLayout is how you can layout everything using percentages of the whole screen. I will be writing up a RelativeLayout recipe soon.

WooferBlueprint

Layers

Let’s go through the 5 layers and see how this wedding cake is assembled.

  1. The bottom layer is a RelativeLayout with a white background.
  2. A background picture is added to the top half of the layout.
  3. A black BoxView with low opacity is added on top of the background picture.
  4. A dome shaped white image is placed at the bottom of the background image and BoxView giving you a nice arc in the center of the UI.
  5. Alabama’s face picture is then added to the layout covering part of the dome, BoxView, and background image.

The images of the chat and location icons could be considered a 6th layer that straddles the dome and the details StackLayout. Layer all the things!

Size Matters

Yes, size matters and using percentages of the screen to layout your UI keeps everything in its place and proportional. Take a look at these screen shots of the Woofer app on iOS. As you can see, the UI looks good on an iPhone4 all the way up to an iPhone6 Plus. Try that with a StackLayout, I dare you. Don’t get me wrong, I love StackLayouts, but RelativeLayout is my new hotness.

WooferSizes

In the case of the Woofer app, using proportions works but might not be appropriate for all UIs. Some times scrolling is necessary so use your best judgment to scroll or not to scroll.

Some Code

public WooferPage ()
{
	BackgroundColor = Color.White;

	var backgroundImage = new Image () {
		Source = new FileImageSource () { File = "southmountain.jpg" },
		Aspect = Aspect.AspectFill,
		IsOpaque = true,
		Opacity = 0.8,
	};

	var shader = new BoxView () {
		Color = Color.Black.MultiplyAlpha (.5),
	};

	var face = new Image () {
		Aspect = Aspect.AspectFill,
		Source = new FileImageSource () { File = "face.png" }
	};

	var dome = new Image () {
		Aspect = Aspect.AspectFill,
		Source = new FileImageSource () { File = "dome.png" }
	};

	var chatimage = new Image () {
		Source = new FileImageSource () { File = "chat.png" }
	};

	var pindropimage = new Image () {
		Source = new FileImageSource () { File = "pindrop.png" }
	};

	var details = new DetailsView ();
	var slideshow = new SlideShowView ();

	RelativeLayout relativeLayout = new RelativeLayout () {
		HeightRequest = 100,
	};

	relativeLayout.Children.Add (
		backgroundImage,
		Constraint.Constant (0),
		Constraint.Constant (0),
		Constraint.RelativeToParent ((parent) => {
			return parent.Width;
		}),
		Constraint.RelativeToParent ((parent) => {
			return parent.Height * .5;
		})
	);

	relativeLayout.Children.Add (
		shader,
		Constraint.Constant (0),
		Constraint.Constant (0),
		Constraint.RelativeToParent ((parent) => {
			return parent.Width;
		}),
		Constraint.RelativeToParent ((parent) => {
			return parent.Height * .5;
		})
	);

	relativeLayout.Children.Add (
		dome,
		Constraint.Constant (-10),
		Constraint.RelativeToParent ((parent) => {
			return (parent.Height * .5) - 50;
		}),
		Constraint.RelativeToParent ((parent) => {
			return parent.Width + 10;
		}),
		Constraint.Constant (75)
	);

	relativeLayout.Children.Add (
		chatimage,
		Constraint.RelativeToParent ((parent) => {
			return parent.Width * .05;
		}),
		Constraint.RelativeToParent ((parent) => {
			return (parent.Height * .5);
		}),
		Constraint.RelativeToParent ((parent) => {
			return parent.Width * .15;
		}),
		Constraint.RelativeToParent ((parent) => {
			return parent.Width * .15;
		})
	);

	relativeLayout.Children.Add (
		pindropimage,
		Constraint.RelativeToParent ((parent) => {
			return parent.Width * .95 - (parent.Width * .15);
		}),
		Constraint.RelativeToParent ((parent) => {
			return (parent.Height * .5);
		}),
		Constraint.RelativeToParent ((parent) => {
			return parent.Width * .15;
		}),
		Constraint.RelativeToParent ((parent) => {
			return parent.Width * .15;
		})
	);

	relativeLayout.Children.Add (
		face, 
		Constraint.RelativeToParent ((parent) => {
			return ((parent.Width / 2) - (face.Width / 2));
		}),
		Constraint.RelativeToParent ((parent) => {
			return parent.Height * .25;
		}),
		Constraint.RelativeToParent ((parent) => {
			return parent.Width * .5;
		}),
		Constraint.RelativeToParent ((parent) => {
			return parent.Width * .5;
		})
	);

	relativeLayout.Children.Add (
		details,
		Constraint.Constant (0),
		Constraint.RelativeToView (dome, (parent, view) => {
			return view.Y + view.Height + 10;
		}),
		Constraint.RelativeToParent ((parent) => {
			return parent.Width;
		}),
		Constraint.Constant (120)
	);

	relativeLayout.Children.Add (
		slideshow,
		Constraint.Constant (0),
		Constraint.RelativeToView (details, (parent, view) => {
			return view.Y + view.Height;
		}),
		Constraint.RelativeToParent ((parent) => {
			return parent.Width;
		}),
		Constraint.RelativeToView (details, (parent, view) => {
			var detailsbottomY = view.Y + view.Height;
			return parent.Height - detailsbottomY;
		})
	);

	face.SizeChanged += (sender, e) => {
		relativeLayout.ForceLayout ();
	};

	this.Content = relativeLayout;
}

Wow, that’s a lot of code. That’s everything except for the details and picture StackLayouts. The full source code for this and all the other “In Anger” posts are in the Xamarin.Forms In Anger GitHub repository. Go ahead and take a look.

As you might have guessed, Alabama Wolf is part of my family. He and his brother are pit mixes we adopted from the local pound a couple of months ago. They are usually good boys and don’t get into too much trouble. They will be making regular appearances in blog post in the future.

Xamarin.Forms in Anger Series

Can Xamarin.Forms produce good looking cross-platform UI from a single codebase? 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. InAnger-Strip-5

The post Xamarin.Forms In Anger – Woofer appeared first on Syntax is my UI.

April 23, 2015 3:51 GMT

Xamarin.iOS Apps: Adding Login/Signup Capabilities

In today’s modern mobile apps it is very common for apps to require a user account in order to function.  Apps like Twitter and Instagram require a user account in order to be used.  So a very common User Experience is to show a Login Page when the app first starts up.  The user should […]
April 22, 2015 2:21 GMT

IoT – Opportunity Knocks

This marks the first in a series of postings on the Internet of Things (IoT).  Come with me as I learn more about these emerging technologies which promise to revolutionize everything we do.

First, the obligatory introduction for those of you who have been living in a cave…

IoT

IoT is the use of web/network based everyday appliances and other, well, things. IoT represents vending machines that keep their own inventory, toasters that alert you when the toast is done, fire alarms that wake you while calling the fire fighters, and so much more.

Knockertunity Ops

IoT presents a significant opportunity for developers; a technology space that is growing rapidly, and in many directions at once.  While the market may not yet support a substantial investment, this is a sector you want to track closely.

Continued

April 22, 2015 12:00 GMT

Xamarin MVP

mvp-logoYesterday, I (Adam) was awarded the Xamarin MVP for my contributions to the Xamarin community. Wow! What an honor. The response from the community has been wonderful. Thank you. I count myself lucky to be one of the 31 Xamarin MVP’s.

A Funny Story

There’s a funny story about my MVP award. For a moment, I thought it might be an April Fool’s joke. I was contacted by Xamarin to see if I would accept the award. Accept? Who would turn it down? Well, not me. My response was an enthusiastic, yes, please.  Then I remembered the date, it was April 1. I thought, they wouldn’t do that, or would they?

The offer email said I would get some goodies but that they would only last 30 days and expire on April 30, 2015. Hey, MVP for a month is better than no MVP, right? Well, a few hours later, I got another email telling me that the date was wrong and it should have said 2016. I was ok with a month but a whole year is much better, don’t you think?

What’s Next

Well, now that I have the award, I’m going to go to Disney World! Ok, maybe not. How about I just write some more, make more courses and keep trying to help the awesome Xamarin community where I can? Sound good? Good!

Thank you, Adam

The post Xamarin MVP appeared first on Syntax is my UI.

April 22, 2015 10:31 GMT

Xamarin.Forms: Add content to TitleView in your iOS app

If you’re building an iOS app you maybe want to add content to the NavigationBar. This blog post will show you how to build a generic solution so you don’t have to write a custom renderer for each view that you want NavigationBar content for.

First of all I creating a new class that inherits from ContentPage and adding a property of type View. I use to name the property TitleView, because that’s the name in iOS.

public class ExtendedContentPage : Xamarin.Forms.ContentPage
{
    public View TitleView { get; set; }
}

Now If your views/pages inherits from your new class you can add content to TitleView.

<local:ExtendedContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:TitleViewSample"
             x:Class="TitleViewSample.MainView">
  <local:ExtendedContentPage.TitleView>
    <Button x:Name="TestButton" Text="Test" BackgroundColor="Green" />
  </local:ExtendedContentPage.TitleView>
</local:ExtendedContentPage>

To get it work you also have to write a custom page renderer for iOS. Override the WillMoveToParentViewController method in the renderer that will inherit PageRenderer and add the code below.

 base.WillMoveToParentViewController(parent);
 
 var page = (ExtendedContentPage)Element;
 
 var renderer = RendererFactory.GetRenderer(page.TitleView);
 var view = renderer.NativeView;
 view.SizeToFit();
 
 parent.NavigationItem.TitleView = view.Subviews[0];

It is important that you adding the first subview of the native view, otherwise it will be just blank.

The complete code can be found on GitHub, https://github.com/dhindrik/XamarinFormsSamples/tree/master/TitleView

April 22, 2015 2:30 GMT

Getting apps from new Xamarin Studio, to iTunes Connect by hand

There is a new Xamarin Studio update in the beta channel, and I thought I would take a moment to walk through getting an app to itunesconnect by hand. I have a build server that does most of the heavy lifting but sometimes I need to get something up to test and just get lazy (which strangely enough causes more manual work).

  • After incrementing the build number, set to AppStore and select Build > Archive for Publishing

image of step 1

  • When the archive process finishes, select the build to send to itunesconnect and then click Sign and Distribute on the tab that appears.

image of step 2

  • I choose AppStore because at this stage in the game I am looking to get my app into testflight. This will download a .ipa to a destination of your chosing.

image of step 3

-Choose which profile to sign with.

image of step 4

-Select Publish

image of step 5

-Great Success! Select Open Application Loader after the .ipa is created.

image of step 6

  • Select Deliver Your App in application and select the .ipa file from step 5.

image image 2

  • Click through the options, wait 15 minutes and ~tada~

image on iPhone

Why is this cool?

I never gave Xamarin the benefit of the doubt in the publishing process. It used to be a pain to locate my archive, then find the app loader, then submit it. Or whatever process Xamarin Studio used. Before I had a build server, and before this update came out, I would just remember to launch XCode and go through the "organizer"(whatever that means), to get my app to testflight/app store. This is much better with the wizard because I stay in friendly places much longer before venturing into the final stages, which requires an Apple made app (if you choose to do this by hand).

April 21, 2015 7:18 GMT

Join Xamarin at Microsoft Ignite 2015

Join Xamarin at Microsoft Ignite in Chicago, IL from May 4-7, 2015. Key members from the Xamarin team will be available to answer your questions, discuss your apps and projects, and show you what’s new across our products.

McCormick Sky Line

James Montemagno, Xamarin Developer Evangelist, will be delivering two talks this year:

  • Go Mobile with C#, Visual Studio, and Xamarin, Thursday, May 7th 10:45am-12:00pm: Learn how to leverage your existing Microsoft .NET and C# skills to create iOS and Android apps in Visual Studio with Xamarin and share your business logic across all platforms. During this session, James will cover several live coding samples and real-world mobile apps to look at the architecture and patterns that power them.
  • Building Multi-Device Applications with Xamarin and Office 365 APIs, Friday, May 8th 9:00-10:15am: This session will introduce the different approaches to building mobile apps that consume Office 365 platform services. The session will give an overview of both native Windows and Xamarin cross-platform development (Android, iOS, Windows Phone) using Visual Studio.

We’ll be at booth #216, so be sure to stop by and say hello if you’re at the conference — we look forward to seeing you in Chicago!

The post Join Xamarin at Microsoft Ignite 2015 appeared first on Xamarin Blog.

April 21, 2015 7:17 GMT

Material Design FAB in Xamarin.Forms

James Montemagno recently blogged about More Material Design for Your Android Apps. In the post, James discussed two controls that he has built around Material Design components. One of the components is the Floating Action Button (FAB).

Let's see how we can pull this control into use with Xamarin.Forms.

Pull in the Component

Start with a new Xamarin.Forms application. In your Droid project, pull in the Floating Action Button control. You can use the Xamarin Component Store or Nuget Package Manager.

Build a Custom Control

For the FAB's properties to be bindable in Xamarin.Forms, we need a custom control with bindable properties.

We will then map each property to a corresponding property on the native FAB control.

Attach a Renderer

If we want to use a native control in Xamarin.Forms, we need a renderer. For simplicity, lets use a ViewRenderer. This renderer will map our custom FloatingActionButtonView to an Android.Widget.FrameLayout.

Pull it all Together

OK! We've built the custom control, and mapped it to a renderer. The last step is laying out the control in our view.

You can pull the completed sample application from GitHub.

FAB demo

April 21, 2015 3:01 GMT

Data Binding with Xamarin and iOS (iPhone & iPad)

Url: http://visualstudiomagazine.com/articles/2015/04/01/a-simple-data-binding-trick.aspx

Applications and businesses live on data. Data is what makes a business a business, generates value for customers, and allows a company to generate income. Displaying data to a user is a common operation, especially in mobile. It might be immensely important for a salesperson to get the last bit of information before visiting a client or to display the location of a restaurant via a local consumer-oriented app. In this article, I'll look at the UITableViewController class that allows you to get at and display that data in an iOS app.

April 20, 2015 7:41 GMT

A Warm Welcome to the Newest Xamarin MVPs

Xamarin MVPJust a few months ago we announced the continued expansion of the Xamarin MVP program by welcoming the first round of Xamarin MVPs for 2015. These individuals have made significant contributions by sharing their passion and expertise in mobile app development with the expanding global Xamarin community. We honor these individuals with the Xamarin MVP title for these contributions, which include:

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

Today, we’re thrilled to recognize the following new Xamarin MVPs for their remarkable contributions to the community!

filip Filip Ekberg Adam Patridge adam
michael Michael Ridland Dan Rigby rigby
silva Sara Silva Sean Sparkman spakrman
wolf Adam Wolf

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

The post A Warm Welcome to the Newest Xamarin MVPs appeared first on Xamarin Blog.

April 20, 2015 4:34 GMT

tendulkar-uvāca : Episode 2

In previous episode of tendulkar-uvāca, we’ve seen how we can setup our development environment using Visual Studio and Xamarin.
In this episode, we’re going to see how we can use emulators to test and debug our applications.

iOS simulators will get installed with XCode is installed.
For Android emulator, install Xamarin Android Player from here
Windows Phone emulators can be installed while installing Visual Studio 2013 Update 3.

Do let me know your feedback and suggestions.

Namaste
Mayur Tendulkar

April 20, 2015 1:52 GMT

Think Ahead

Since the early days of MonoTouch, when it was just a few of us hanging out in IRC deep into the night, I’ve gravitated towards helping other developers. Initially through my blog and speaking events, and later through my MonoTouch book and training course, I was able to help lots of people get started with this fantastic technology.

Not too long after Xamarin was formed, I joined as their first technical writer. Then I moved into a role as the documentation lead, followed by developer evangelism. Being able to work in these roles at Xamarin was the privilege of my career. Not only did I get to work with a brilliant team, but I was able to help so many developers through my writing, speaking and code. After years writing scientific and engineering software behind the scenes, helping others has been refreshing and has become my passion.

Which leads me to an exciting next step. Today I am excited to announce I have joined up with the team at Think Ahead Software to create the best Xamarin consulting group in the world. I’m thrilled to have the opportunity to continue helping developers succeed with my favorite platform and am looking forward to the many amazing applications we’ll help bring to the world.

I’d love to talk to you about how I can help build your app. You can contact me here.


April 20, 2015 12:00 GMT

Xamarin.Forms SearchBar Recipe

The Xamarin.Forms SearchBar is so easy to implement, I don’t see why you wouldn’t add one to every ListView! I had to add a search bar to the Xamarin.Forms application I’m building during my day job and I was amazed at how easy it was.

Our sample app is a fictional Mall Map App. You know the ones that let you find the store you’re looking for without having to search for and then stare at the mall map looking for the “You are Here” sign. I took the sample data from the local mall’s website; I hope they don’t mind.

Xamarin.Forms SearchBar iOS
Xamarin.Forms SearchBar Android

Xamarin.Forms SearchBar

Here is the MainPage of the sample application. As you can see, the code to hook up the Xamarin.Forms SearchBar is minimal. When the SearchBar is used, the TextChanged and SearchButtonPress event executes my custom filter function on the Mall ListView class.

public class MapPage : ContentPage
{
	MallListView list;
	SearchBar searchbar;

	public MapPage ()
	{
		Title = "Chandler Mall";

		list = new MallListView ();

		searchbar = new SearchBar () {
			Placeholder = "Search",
		};

		searchbar.TextChanged += (sender, e) => list.FilterLocations (searchbar.Text);
		searchbar.SearchButtonPressed += (sender, e) => {
			list.FilterLocations (searchbar.Text);
		};

		var stack = new StackLayout () {
			Children = {
				searchbar,
				list
			}
		};

		Content = stack;
	}
}

 Search Bar Filter

The search bar filter method uses the begin and end refresh methods on the Xamarin.Forms ListView. The method will reset the lists ItemsSource if the search result is emptied or the cancel button was pressed. The simple LINQ where clause was all that was needed to filter down the list results.

public void FilterLocations (string filter)
{
	this.BeginRefresh ();

	if (string.IsNullOrWhiteSpace (filter)) {
		this.ItemsSource = locations;
	} else {
	    this.ItemsSource = locations
	        .Where (x => x.Title.ToLower ()
		    .Contains (filter.ToLower ()));
	}

	this.EndRefresh ();
}

Yes, that’s it! No, I am not kidding. Now do you see why I think the search bar should be added to every ListView! Ok, maybe not every ListView. Check out the sample project and see for yourself.

Download the Xamarin.Forms SearchBar Recipe Code

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

April 19, 2015 12:27 GMT

Xamarin Android Emulator update

In an earlier post, where I talked about configuring your environment for development, I mentioned that the Android Emulator gave me a bit of a headache.

On Planet Xamarin, a aggregator for multiple Xamarin minded blogs, I came across a post about making the Xamarin Android Player work.
After following the instructions in the blog it actually worked! And the best thing is, it isn’t even that hard! Just like Android itself, you have to dig a little deeper than on other platforms.

As mentioned in the blog itself I had to restart my Visual Studio to make the actual connection happen. If I’ hit the ‘play’ button in Visual Studio it would appear to do nothing and just come back after a second. Restarting fixed this problem and made deploying to Android work like a charm!

Now there just seems to be a problem with my code on Android..

Unhandled Exception Android

Unhandled Exception Android

So many thanks to Johan Karlsson! You can find the blogpost here.

April 17, 2015 2:44 GMT

Weekly Xamarin Newsletter Issue #36

Xamarin Dev Days is Coming to Your Town
James Montemagno, from Xamarin Inc., announces full day mobile development events.

Android ListViews Reinvented
Ruben Macias gets all horizontal with the RecyclerView on Android.

Autolayout and auto-expanding UILabel
Nic Wise finds his auto-expanding label with AutoLayout on iOS.

Dialing a number using DependencyService in Xamarin.Forms
Jesse Liberty, from Falafel Software, gets his phone app to ring someone using the dependency service.

More Material Design for Your Android Apps
James Montemagno, from Xamarin Inc., spices up his Android app with his love of Material Design.

Sara Silva – Xamarin Workshop Guide

Checkout Sara’s guide she put together for thePortuguese National Meeting of IT Students. The site and repo are on GitHub here.

  1. Create a Xamarin forms project
  2. Create the model and data source

 

Crédito Agrícola Banks on Xamarin Platform, Test Cloud, and Insights
Jo Ann Buckner, from Xamarin.Inc, shows off a new app built by one of the largest banks in Portugal.

Setting up Wormhole Sharp to Communicate with iOS Extensions
Tim Sneed uses Wormhole Sharp for Apple Watch to iPhone app communications.

Join Xamarin at Build 2015
Joseph Hill, from Xamarin Inc., is looking forward to //build with Xamarin’s sessions and kickoff party.

Adam’s corner. A busy week on the blog.

 

Advanced transitions with vector drawable
Jérémie Laval gets you up to speed with vector drawables and animations.

Beggin’ for a Beacon Xamarin Contest Winner!
Jayme Singleton, from Xamarin Inc., announces the winner to the Beacon contest.

Cold Hard Data Cache – Or Saving Our Users Money!
Matthew Soucoup is saving user’s money and time with caching.

Sitecore meet Xamarin
Jesse Liberty, from Falafel Software, is excited to announce the new Sitecore SDK for Xamarin.

New Xamarin.Forms control WaitingPage
Mitch Milam builds a new Xamarin.Forms page made for waiting.

Xamarin.Forms Pages: ContentPage and NavigationPage
Paulo Ortins goes over the most used pages in Xamarin.Forms.

Xamarin’s Got Game (Development)
Victor Chelaru, from Xamarin Inc., wants developers to know that you can build games with Xamarin.

Xamarin.iOS Memory Pitfalls
Thomas Bandt wants you to stay out of trouble with better coding practices.

 

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 #36 appeared first on Syntax is my UI.

April 17, 2015 11:49 GMT

Serial communication using Reactive Extensions

The main purpose of Reactive Extensions (Rx) is to enable processing event streams. I set out to use Reactive Extensions for receiving data on the serial port and learned some new things.

Here is the code that uses Observable.FromEventPattern<T>() to create an IObservable<T> from the .NET event SerialPort.DataReceivedEvent:

The event does not actually contain any information on the data received, it only indicates that there is data available. Reading the data is done inside the lambda expression. Reading serial data will return a list of bytes. This list may contain a complete message or just a part of a message or even multiple messages. To handle this, I want the observable to be an IObservable<byte>, i.e., it will produce a raw stream of bytes without any indication of where a message begins or ends. This is done through the extension method public static IObservable<TResult> SelectMany<TSource, TResult>(this IObservable<TSource> source, Func<TSource, IEnumerable<TResult>> selector) that is used to flatten the sequence returned by the lambda.

So I now have a stream of bytes. I want these bytes to be chunked into messages. For my particular protocol, messages are separated by a special byte. Separation can be done in two ways:

Here, a new observable is created using Observable.Create(). This observable subscribes to the byte stream, collects the data in a local collection and fires OnNext() whenever a message delimiter is encountered.

This version uses the Scan() operator to achieve the same thing. The output is an IObservable<IEnumerable<byte>> that fires an IEnumerable<byte> for every new message.

This code worked well up until the point I started attaching multiple observers to the message stream, one to process the messages and one to just dump received messages to a debug console. What happened then was that the code in the first code sample was called multiple times: once for each subscriber. This meant that each chunk of serial data was only received by one subscriber, not all subscribers. There are two possible solutions to this: Either introduce a Subject<IEnumerable<byte>> subscribing to serialPortSource and have consumers subscribe to the subject or use the Publish() operator that does the work for you.

Creating a new observable that produces deserialized messages from the observable producing lists of bytes is now trivial using a simple Select().

What remains is the question of how to use the received data in a typical workflow of sending out a message and receiving a response in return. Here is an example:

This example uses the Replay() operator. Replay will capture all events from the observable that are fired after the call to Connect(). After calling Connect() the call is sent to the device at the other end of the serial connection. The second await filters the incoming messages for the desired message (even using a filter criterion that was not known before the request was sent), adds a timeout, uses FirstAsync() to return an observable that only returns the first element followed by OnCompleted(), and waits for that OnCompleted() using await. Since Replay() is capturing all messages, the following await call on the observable should consider all answers from the target, whether they are received before or after the second call to await.

April 16, 2015 6:45 GMT

Dialing a number using DependencyService in Xamarin.Forms

OldPhone.stockAs you can probably tell from my previous posts, I love Xamarin.Forms; principally because of XAML and DataBinding.  It is just easier to create a cross-platform (iOS, Android and Windows Phone) with Xamarin.Forms than any other way.

Sometimes however, you do need to reach down to the native code to accomplish something that just isn’t wrapped in Xamarin.Forms.  One good example is dialing the phone. Let’s build an application that does just that.

Continued here

 

April 16, 2015 4:54 GMT

More Material Design for Your Android Apps

fab iconAndroid developers have been flocking to Material Design since its introduction with the release of Android Lollipop. With the recent update to the Support v7 AppCompat library it has never been easier to add Material Design to target older Android operating systems.

Material Design is much more than just the core theming and styling that you are able to add to your application — it’s animations, layouts, and of course controls. While many controls are available out of the box, there are many custom controls that can spice up your application with even more Material Design. Many of these controls are now available in the Xamarin Component store so you can instantly add them to your Xamarin.Android application. Let’s take a look at a few.

Floating Action Button

Floating Action ButtonWhen developing applications, you often have a main action that your users can perform on a page such as add, edit, delete. The floating action button (FAB) was introduced to enable you to promote your main action with a beautiful and distinguished circled icon floating on the user interface. The floating action button is great because it helps bring context and awareness to the action that you want your users to perform, and you can add it to your Android app with the new Floating Action Button component.

Once you have the component installed, you can add a FAB to any layout by referencing the custom control.

<com.refractored.fab.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|right"
            android:layout_margin="16dp"
            android:src="@drawable/ic_action_content_new" />

Now you can find the FAB and add a click handler just like any other button.

var fab = root.FindViewById<FloatingActionButton>(Resource.Id.fab);
fab.Click += (sender, args) =>
{
  Toast.MakeText(Activity, "FAB Clicked!", ToastLength.Short).Show();
};

Be sure to read through the getting started guide to see how you can show and hide the FAB with a few simple calls or even attach it to a ListView to have it automatically hide when the list is scrolled.

fab_demo

Pager Sliding Tab Strip

If you are an Android user, you may have noticed the beautiful Tabs that are part of the Google Play Store when browsing. The Material theme provides an updated look and feel to tabs, but it doesn’t introduce an updated View Pager Indicator. This is where the Material Pager Sliding Tab Strip component comes in to enable you to easily add highly customizable and beautiful tabs to your Android app.

After downloading the component, simply add the PagerSlidingTabStrip on top of your ViewPager in your layout.

<com.refractored.PagerSlidingTabStrip
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:pstsPaddingMiddle="true"/>
<!--Set pstsPaddingMiddle to false to start tabs on left-->
<android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        tools:context=".MainActivity" />

Then find your ViewPager and PagerSlidingTabStrip and connect them together with any FragmentPagerAdapter.

// Initialize the ViewPager and set an adapter
var pager =  FindViewById<ViewPager>(Resource.Id.pager);
pager.Adapter = new TestAdapter(SupportFragmentManager);
// Bind the tabs to the ViewPager
var tabs = FindViewById<PagerSlidingTabStrip>(Resource.Id.tabs);
tabs.SetViewPager(pager);

material_tabs demo

For a full sample and to see how to customize the pager sliding tab strip even further, be sure to dive through the documentation and getting started guide for the component.

More Material!

Material Design integration into your Android apps doesn’t stop here. Be sure to read through our Introduction to Material Design, Support v7 AppCompat Library, and the new Android Toolbar. Another great resource are the two presentations that Jérémie Laval and I gave at Xamarin Evolve 2014, Android Material Design from Concept to Implementation Part 1 and Part 2.

The post More Material Design for Your Android Apps appeared first on Xamarin Blog.

April 14, 2015 6:49 GMT

Xamarin.Forms: from zero to hero – part 2

In my previous post I have covered the basics of starting with Xamarin, more specific Xamarin.Forms. There I have described that my first app would be a business app for the company I work for.

In the meanwhile I have been working on this app to get it ready for the App Store, Market and/or Play Store. In this continuing post I will put things in perspective for you and describe how the app has taken shape, which decisions I’ve made (and why) and the sleepless nights I’ve had because of stuff that didn’t work.

First let’s refresh your memory a bit. No need? Just skip to the next heading then!

Previously on As The World Blogs…

In the post before this I have told you about the different project templates you get to choose from to build a Xamarin app.

With the little knowledge I had upfront I knew I wanted to use XAML for my markup, the app had to be as multi-platform as can be, the code base had to be shared as possible and because it was a first for me with Xamarin I didn’t want to do a lot of fancy stuff right away.

Wishlist for the first version:

  • General description of what we do how and why we do it at all;
  • Overview of the employees and some details about them;
  • Contact information.

After applying some common sense I figured that since I was creating a digital business card of sorts, the main goal – as a end-user –  would be to be able to contact us ASAP and – as a company – create possible sales opportunities.

The first ‘requirement’ would be easy to solve. Just incorporate a call and e-mail button on every page elegantly. The user would be able to contact us from anywhere within the app when they are (finally) convinced of our epic skills.

The second one wasn’t really a goal in itself, but by providing relevant and fun content in a sexy UI I would hope to persuade potential customers to choose for us.

So far for the outline. Make it so!

Buckle your seatbelt Dorothy, ‘cause Kansas is going bye-bye!

Because of my research I knew what project template to choose to satisfy my needs. So start Visual Studio, create a new project, give it a name and wait a while for all the projects to be generated.

The name of the company I work for is 4DotNet which, as it turns out, is a toughie while coding because you can’t start class names and variables etc. with a number. So as a solution name I choose FourDotNet to get around it.

On to my first screen. The first question arises: what layout to choose?
As we saw in my last post there are a number of different pages already provided by Xamarin.

Xamarin.Forms Pages

Xamarin.Forms Pages

The ContentPage seemed a little to marginal for the goals I wanted to achieve. The MasterDetailPage is a viable option, but since the app won’t have too much content, the ways to navigate within a MasterDetailPage seemed to devious.
NavigationPage manages a stack of pages, doesn’t fit for now.. TabbedPage.. Bingo! This looks like the thing I want!
Let’s check out the CarouselPage just in case. Also awesome but for me the CarouselPage feels too much like the native Panorama Windows Phone control.

So the TabbedPage it is.

First thing I did was create a XAML page, MainPage.xaml, in the shared project, FourDotNet, and change the App.cs to use is.
To keep things neat I’ve created a folder to contain my pages instead of just putting them in the root.
After I did this my FourDotNet project looks like this:

[SPOILER ALERT] I’ve already created some more pages in the screenshot underneath.

FourDotNet Project tree

FourDotNet Project tree

And the code in my App.cs looks like this:

public App()
{
   // The root page of your application
   MainPage = new MainPage();
}

Of course don’t forget to include the right namespaces and for your convenience I’ve omitted the rest of the methods in the class. We’ll leave them there for now.

The standard XAML page contains just a ContentPage with a centered label, what we are after is a TabbedPage with three tabs. So let’s open up the MainPage.xaml and start editing.

The start and end <ContentPage> tag we modify to <TabbedPage>, lose the label and replace it with Children of the ContentPage.
After we’re done with it, this is what is looks like:

<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:pages="clr-namespace:FourDotNet.Pages;assembly=FourDotNet" x:Class="FourDotNet.Pages.MainPage">
  <TabbedPage.Children>
  </TabbedPage.Children>
</TabbedPage>

The children of a TabbedPage, which will become the actual tabs, can be any type of other pages. So let’s create some.

As you may have noticed I already created a few in the screenshot above. For the tabs I will be using:

  • GeneralPage: a page with just a description;
  • EmployeesPage: a page with a list of our wonderful employees;
  • LocationPage: a page showing a map with our locations and some contact information.

We can create these pages like we did with the first one, and of course in our Pages folder.

GeneralPage.xaml

Let’s start off with the GeneralPage. As described before, this will contain just a text about the company. So probably a simple ContentPage will suffice here.

Not having worked with Xamarin before left a little clueless here. How am I going to show just a text which at the same time should contain markup to make it readable?

Let’s check the documentation page and walkthrough the most feasible options.

WebView

First I turned to a WebView. With this I could load a external URL, but I would have to create a single page with styling, etc. which only purpose would be to be shown in the app. Also I would have to think about some sort of caching mechanism so it would show whenever the user has no internet connection available. On the other hand I could update the text remotely without rebuilding and updating the app itself.
I could also create a local web page which is loaded into the WebView. I would still have to create a wellformed page, dito CSS styling, include it into each project separately (or do research on sharing resources).

Maybe later. There are probably other, maybe better, options.

Label

The association I have with a Label is that it contains only a small portion of text. A full sentence at most. But maybe I’m wrong. It could, of course, contain more text. And also, why would I limit myself to use just one label? I could have several and layout however I want them. Because let’s not forget that I also have the Layout controls at my disposal.

I’m gonna go with labels in a StackLayout for now. A StackLayout just stacks the controls vertically or horizontally. Also you can nest them, which enables you to create a ‘row’ with a number of horizontal controls and wrap it in a vertical StackLayout to stack things under it as well. Or the other way around.

With the StackLayout and labels I was able to create a text with some headers and a describing text underneath. This would fulfill my needs for now. The header labels will have another color and be slightly bigger. Underneath you can see the XAML and resulting page in the (iOS) emulator.
For TL;DR purposes I’ve replaced the actual texts with the word ‘Text’.

MainPage.xaml iOS screenshot

MainPage.xaml iOS screenshot


<?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="FourDotNet.Pages.GeneralPage">
  <ScrollView>
    <StackLayout>
      <Label FontSize="Large" TextColor="#0092DB">
        Wat doen we?
      </Label>
      <Label FontSize="Small">
        Text
      </Label>
      <Label FontSize="Large" TextColor="#0092DB">
        Hoe doen we het?
      </Label>
      <Label FontSize="Small">
        Text
      </Label>
      <Label FontSize="Large" TextColor="#0092DB">
        Waarom doen we het?
      </Label>
      <Label FontSize="Small">
        Text
      </Label>
      <Label FontSize="Large" TextColor="#0092DB">
        Wie zijn wij?
      </Label>
      <Label FontSize="Small">
        Text
      </Label>
    </StackLayout>
  </ScrollView>
</ContentPage>

One thing you can’t capture in an image, but was in fact a problem that presented itself, was the fact that this LabeledStackLayoutPage™ couldn’t scroll!

Luckily while going through the Xamarin documentation pages I came across the ScrollView. Wrapping this around the StackLayout made it work at the first try. Awesome!

Another thing that is noticeable is that the text runs behind the statusbar. If we look at the same screen in Windows Phone it looks fine.

MainPage.xaml Windows Phone screenshot

MainPage.xaml Windows Phone screenshot

So it seems that we have platform specific behaviour going on here. Windows Phone (and Android, take it from me) apparently see the statusbar as something you either hide or, when it is visible, a space that cannot be used. While iOS let’s you happily draw from top to bottom. So we have to define a padding, but just for iOS.

In XAML we can do it 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="FourDotNet.Pages.GeneralPage">
  <ContentPage.Padding>
    <OnPlatform x:TypeArguments="Thickness">
      <OnPlatform.iOS>
        20, 20, 20, 0
      </OnPlatform.iOS>
    </OnPlatform>
  </ContentPage.Padding>
...
</ContentPage>

When you want to have different values for another platform as well you can extend it like so:

<ContentPage.Padding>
    <OnPlatform x:TypeArguments="Thickness">
      <OnPlatform.iOS>
        0, 20, 0, 0
      </OnPlatform.iOS>
      <OnPlatform.Android>
        0, 0, 0, 0
      </OnPlatform.Android>
      <OnPlatform.WinPhone>
        0, 0, 0, 0
      </OnPlatform.WinPhone>
    </OnPlatform>
  </ContentPage.Padding>

If the value can be represented by a simple string (like the above) you can also define them like this:

<ContentPage.Padding>
    <OnPlatform x:TypeArguments="Thickness"
                iOS="0, 20, 0, 0"
                Android="0, 0, 0, 0"
                WinPhone="0, 0, 0, 0" />
</ContentPage.Padding>

It will look all the same, so this would just be a matter of taste.

With this you cannot just add some padding, also you can provide a custom background or platform specific icons.

Besides the OnPlatform tag we also have a OnIdiom tag with which you can specify the type of device (phone or tablet) rather than the actual platform.

For now that concludes my first screen. On to the next one, the list of employees!

EmployeesPage.xaml

Let’s create another clean page. Again, this gives is the centered label which I quickly and swiftly will replace with a ListView. Because I wanted to show a list of our employees, I have stopped searching for a better control when I came across a control that states ‘List’ in the name.

The rest seemed pretty straight forward: get a list of employees somewhere online, retrieve it, show it in the the list and when a employee is tapped (nasty..) show some details.

Here I ran into some problems, nothing we can’t handle but some things you should know about!

One does not simply get all the employees

Luckily we just got a new website which also lists all of our employees and the skills that comes with them, so that came in quite handy! From there I was able to create a JSON feed which I would be able to retrieve within the app.

Being able to use the standard .Net goods in Xamarin I downloaded the Json.Net NuGet package and created some code to get the employees to my app.

I ran into some trouble right then and there. Not even handling the JSON, but rather acquiring the JSON itself from the website. On projects before I have leveraged the WebClient to download a string and work from there.

But the project created by Xamarin is as much backwards compatible as possible, which means it also targets Windows Phone 8. The same Windows Phone 8 that doesn’t support this particular class.

So here you have to choose whether to drop support on Windows Phone 8 (which probably isn’t used very much anyway) or find some other way.

Because it is a simple app and has to reach as much audience as possible, I decided to take the hard way and find another solution.

This involves creating a WebRequest yourself and define a callback method to handle the response.
The WebRequest simply looks like this;

var req = WebRequest.CreateHttp("http://www.4dotnet.nl/medewerkers/");
//req.ContentType = "application/json";
req.Accept = "application/json";
req.Method = "GET";

req.BeginGetResponse(EmployeeResponseCallback, req);

Note that you have to define the request as a HTTP GET request and set the Accept header to ‘application/json’. At a first attempt I stated the WebRequest to have a Content-Type of ‘application/json’, commented out in the above snippet.
Oddly enough this works for iOS, but when I ran this on Windows Phone I got an exception which told me that a GET request cannot have a body.
This puzzled me at first. I didn’t have any body in my request, so why is it telling me I have?!
After a quick search I found that setting the Content-Type on the request implied that there is, in fact, a body even if it is empty. Like I said, weird enough it only seems to cause problems on Windows Phone. Besides that I should set the Accept and not the Content-Type.

Below is the code I have in my callback.

var request = (HttpWebRequest) result.AsyncState;
var response = request.EndGetResponse(result);

using (var stream = response.GetResponseStream())
{
  using (var reader = new StreamReader(stream))
  {
     var jsonDoc = JsonConvert.DeserializeObject<EmployeeContainer>(reader.ReadToEnd());

     _container.Employees.Clear();

     foreach (var employee in jsonDoc.Employees.OrderBy(e => e.Name))
     {
        _container.Employees.Add(employee);
     }
  }
}

Here you will notice something which doesn’t seem very performing. I clear out a collection and fill it again with a for-each loop.
For my list I decided to use data-binding. In my XAML that looks 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="FourDotNet.Pages.EmployeesPage"
             Title="Medewerkers">
  <StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand">
	<ListView IsPullToRefreshEnabled="True" Refreshing="EmployeeListView_OnRefreshing" ItemTapped="EmployeeListView_OnItemTapped" x:Name="EmployeeListView">
    <ListView.ItemTemplate>
      <DataTemplate>
        <ImageCell ImageSource="{Binding PhotoUrl}" Text="{Binding Name}" Detail="{Binding Function}">          
          <ImageCell.ContextActions>
            <MenuItem Text="Stuur e-mail" Clicked="EmployeeContextEmail_OnClicked"></MenuItem>
          </ImageCell.ContextActions>
        </ImageCell>
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>
  </StackLayout>
</ContentPage>

Notice that I didn’t have to do anything fancy and just use the standard data-binding thingies.

Also; as a bonus you can see I’ve added ContextActions. I won’t go explaining them here, make it a challenge for yourself!

Because of the data-binding I also use a ObservableCollection. If you have some experience with this you probably know that I cannot just exchange one collection for another, but I have to modify the existing collection in order to keep the binding working.

Eureka! It works! My list shows and fills and because of the built in ‘drag down to refresh’ support on the ListView it refreshes nicely when I pull the list all the way down. Again, something to explore on your own. It’s not hard!

But now I wanted more, when I choose an employee it should advance to another page and show that employee in more detail. Which led me to navigation.

Page navigation (EmployeePage.xaml)

For navigating through pages each platform has it’s own mechanism, but the final results are more or less the same.
Navigation is basically just a stack of pages that you can push a page onto (to show it) and pop pages off (to ‘close’ it). There are also some possibilities to show something modal, or remove pages from down the stack, but for now it seems that when I tap a employee I want to push his or her page onto the stack, and when the user goes back I would want to pop it and show the previous page.

Before continuing I will have you know that I have created yet another XAML page, the EmployeePage.xaml, which will serve as a detail page for showing one employee.

My first attempt was pretty straightforward:

private async void EmployeeListView_OnItemSelected(object sender, SelectedItemChangedEventArgs e)
{
   var selectedItem = (Employee)e.SelectedItem;

   var employeePage = new EmployeePage(selectedItem);
   await Navigation.PushAsync(employeePage, true);

   EmployeeListView.SelectedItem = null;
}

This involved wiring the ItemSelected on the ListView and within the event push a page onto the navigation stack. Running this code immediately gave me a run-time exception. Although it only seems to occur on iOS.

NavigationPage Exception

NavigationPage Exception

As it turns out, when you want to do navigation like this, you have to start pushing pages onto the stack right from the beginning. So what I had to do was go into my App.cs and wrap my MainPage in a NavigationPage like so:

public App()
{
   // The root page of your application
   MainPage = new NavigationPage(new MainPage());
}

When you now start the application, something has changed. Wrapping your page in a NavigationPage also gave you a free navigation bar at the top of the screen!

Now when we push the page onto the stack at the point where we choose are employee, it looks like this.

EmployeePage

EmployeePage

Ok, I already added some more information, but eventually it looks like this. You’ll notice that a back button is provided in the navigation bar as you push pages onto the stack.
Now, when you push that back button you will see that the employee you chose is still selected and can’t be selected again until you tapped another one, which then has the same problem.

Trying to fix this I tried to set the selected item on the list to null programmatically. As I already did in the above snippet.
This caused some unwanted behaviour. Setting the selected item to null from within the ItemSelected event caused the event to fire again (doh), but this time with no selected item and so an empty page was shown.

Luckily there is also a ItemTapped event which can do roughly the same. The final code which does what I wanted:

private async void EmployeeListView_OnItemTapped(object sender, ItemTappedEventArgs e)
{
   var selectedItem = (Employee)e.Item;

   var employeePage = new EmployeePage(selectedItem);
   await Navigation.PushAsync(employeePage, true);

   EmployeeListView.SelectedItem = null;
}

As you can see you still need to set the selected item to null. I won’t go in to designing the rest of the employee detail page, you should be able to do so yourself with the knowledge you have gained reading this post. Maybe some more specifics will be described in future articles, or you are of course free to ask me by mail, Twitter, etc.

LocationPage.xaml

Last but not least the page to show our locations. For now I’ll settle for just showing a map with markers on our locations. Later on I probably want to expand the page to show some more info, but I haven’t figured that out just yet.

The map control isn’t present by default, you have to install it as a separate NuGet package.

After installing it you have to add some initialization code to each app as well. The code you have to use is simple;

Xamarin.FormsMaps.Init();

Place this right after the

Xamarin.Forms.Forms.Init();

in each app. For each specific platform you can find it in the following files:

  • iOS – AppDelegate.cs file, in the FinishedLaunching method;
  • Android – MainActivity.cs file, in the OnCreate method;
  • Windows Phone – MainPage.xaml.cs file, in the MainPage constructor.

Furthermore don’t forget that privacy is a big issue these days, so don’t forget to specify that your app is using location services. Mainly you have to do two things: in the properties of your project enable some checkboxes which state that the app will use location services and add an API key of Bing/Google maps to your code.
I won’t get into detail about it here for now, but check the Xamarin documentation on how to do this.

Last but not least there are two pins to be added which point out our location.

public LocationPage()
{
   InitializeComponent();

   const int zoomLevel = 7; // between 1 and 18
   var latlongdegrees = 360 / (Math.Pow(2, zoomLevel));

   var meppelPin = new Pin
   {
      Position = new Position(52.70532069999999, 6.187675799999965),
      Address = "Paradijsweg 2, 7942 HB Meppel",
      Label = "Locatie Meppel",
      Type = PinType.Place
   };

   var nieuwegeinPin = new Pin
   {
      Position = new Position(52.027241, 5.064933300000007),
      Address = "Nevelgaarde 40, 3436 ZZ Nieuwegein",
      Label = "Locatie Nieuwegein",
      Type = PinType.Place
   };

   MainMap.Pins.Add(meppelPin);
   MainMap.Pins.Add(nieuwegeinPin);

   MainMap.MoveToRegion(new MapSpan(new Position(52.50, 5.45), latlongdegrees, latlongdegrees));
}

Declaring the pins and adding them to the map should be pretty straightforward. At the last line I set the center of the map to the center of Holland, hence the coordinates.

Of course, there is some graphic for this page as well;

LocationPage screenshot

LocationPage screenshot

Fin.

This concludes the basics of designing and developing my first Xamarin app. The description in this article isn’t complete. By following all the instructions you won’t have a publish-ready app, but it should give you the first clue on where to start and more important; show you that starting Xamarin doesn’t involve a lot of learning right away. Later on there will be problems challenges, I’m sure. But the basics doesn’t involve much more than you already know; C# and .Net! Awesome!

To finish this app, consider the following;

  • I still need to implement the e-mail and call actions;
  • There is a lot of ‘hidden’ work to find and implement platform specific icons and look-and-feel tweaks. Not in the least the icons and screenshots you need to provide in order for the app to pass the publishing committee and get it into the app store;
  • Testing! Testing! Testing! Not just in the emulator, also on a physical device. I have never designed an app that showed some unwanted behaviour that I didn’t catch in the emulators.

For now: thank you for reading, I’ll promise the future posts will be more bite-sized. Cheers!

April 14, 2015 8:31 GMT

FreeAgent releases their own iOS app - and a bit of an ode to an old app

FreeAgent have finally released their mobile app! It's been a (very) long time coming, and giving the importance of mobile these days, I'm surprised it's taken them this long.

To be honest, while they admit its a v1.0, it's a good looking, and well executed app. It fits with their branding, and covers the two main areas which people use mobileAgent - my FreeAgent app - for: expenses and invoices.

From a quick spelink around the .IPA, they are using Cordova and React (and jQuery and a load of other stuff), which given their background in web, isn't a surprise. To be honest, if I was writing (from scratch) a cross platform mobile app right right, I'd be seriously looking at React and ReactNative, especially if I had a load of web and JS people on staff. Using React and Cordova is a good stepping stone, especially (I expect) when they started this, ReactNative didn't exist.

There are a few bits which make it obvious that it's a web app in a container tho - I can't edge-swipe to get back from a list to the main screen (which I use all the time), and the NavBar scrolls off the top of the screen in funny ways from time to time.

But over all, it works well, and they will improve it over time. Well done Olly, Roan, Robbie and the rest - I raise a wee dram to you :)


So where does this leave mobileAgent, my (aging, decreped but still quite functional) FreeAgent client? For the moment, in a simlar position to where it was before.

(I dont have any shots of what v1.0 looked like, but rest assured, it was fugly. The shot below is v1.9)

(how it looks now, in v3.5. Better, but still not good)

mobileAgent was designed at the time when data was scarce and expensive (500mb data cap? LUXUARY! 3G? Only in the big cities!), so it was (poorly) designed to work offline first and foremost. Want to do your expenses on the tube on the way home? No problem.

Note that when I say poorly, ageing and decreped, it works fine for the user. I'm talking about the constraints I have to work in - the internal design of the app, the external design (functional, but now hugely inflexible), and other aspects which make it less than fun for me to work on.

I started the app in mid 2010. I'd started using FreeAgent to manage my business in the Uk, and I loved it. I still do to be honest. But I also had an iPhone (3G!) and Novell - now Xamarin - had just released the early betas of MonoTouch - now Xamarin.iOS.

So like any nail looking for a hammer, I wrote a client for it. v1.0 was released in October 2010. That first version only did timeslips, I think, and maybe a few other bits, but since then I added expenses, bills, invoices, timeslips, mileage, contact import and editing, project editing, bank info... its a long list of duct tape and spit.

6630 downloads, nearly 5 years, and 35 releases later, and it's at v3.5, which is likely to be the last. Why? Well, obviously FreeAgent releasing their own is a big one, but Apple recently required app updates to include a 64 bit variant, and I have to do a LOAD of work to get the app to that point, work which isn't worth it from a time vrs money point of view.

To be honest, the whole thing hasn't been worth it on a time vrs money point of view, but it's been fun enough, and I've learned a lot, so I'm not unhappy about it.

At a guess, I've sunk about £30-50,000 of development time (hours * my daily rate at the time), and about £200 of actual cash (the icon). The app has made around £13,500 over that time, with a peak month (Feb 2013) of £536.

It's paid for a few phones, and a few other bits, but mostly it's been a learning experience and a justification, if I needed it, to HMRC/IRD that I need to spend company money on "toys". That alone made it worth it.

6630 downloads; £13,500 revenue; 1400 monthly users (past 30 days); 30,000 user sessions (past 30 days); 3 competators announced; 1 launched (now closed) - other than the FreeAgent one


So whats next for mobileAgent? Nothing, really. Or rather, no change. It costs me nothing more to keep it in the store, and it is still useful to people as it does, and shows, some things which the FreeAgent one doesn't - bank info, mileage, timeslips, bills, etc. I might drop the price down a bit, but there again, I don't think thats a blocker for anyone.

I believe that FreeAgent needs to own the mobile part of their app. It's a critical channel these days, and something they need to own and apply their own style and skill to. Their new app is a great step in that direction.

So things are looking up for FreeAgent users, I think.

April 14, 2015 2:00 GMT

tendulkar-uvāca : Episode 1

Uvāca – simply means ‘says, explains, describes’ and ‘tendulkar-uvāca‘ means ‘tendulkar-explains’. Through this series, I want to share my experience and whatever knowledge I’ve about mobile, cross-platform and apps for gadget development. The idea is to help people understand these technologies in any possible way. Here are first two videos from this series.

Pilot Episode:

First Episdoe:

Hope you’ll like these videos. Do subscribe to the channel and blog to get updated contents and also let me know your feedback (be it positive or negative). Also let me know if you want me to cover any specific topics.

April 13, 2015 1:50 GMT

Yet Another Podcast – Reboot!

Yet Another Podcast (YAP) had quite a run in its first iteration.  We had (among many others), onair_istock_thumb.jpgScott Guthrie, Miguel de Icazza, Scott Hanselman, Charles Petzold, John Papa, Laurent Bugnion… the list is too long.

Reboot

The last show, however, was last year, show #135 with Miguel de Icazza.  It is time to restart, inviting industry leaders in the Xamarin and .NET world to come back and bring us up to date.  So…  our first new show will be May 13, and we’ll try for at least two shows per month.

I’m working on setting up a mailing list so that you can (optionally) be informed when a new show is available.  At a minimum, we’ll be available through iTunes and Stitcher as well as this site.

More soon….

 

April 13, 2015 12:57 GMT

50 Shades of Xamarin

One of my favourite parts of Xamarin is it’s flexibility. Using Xamarin and Xamarin.Forms you can actually jump between Native API’s, Forms APIs and Html5 (generated at locally or on the server). This flexibility has enabled me to develop a range of different solutions for clients based on their situation, I wasn’t sandboxed to Native or PhoneGap, I could mash up anything. The best part is that you can mix these up to with seamless experiences between them.

Here’s a graph showing the percentages of technologies I’ve used in my most recent Xamarin Apps, you’ll see some are Forms only, some are Native only, some are a mix of all.

Do you have some Html5 that’s already mobile friendly? Go ahead use Xamarin then you’ll also be able to add in a sexy Native Menu using Xamarin Traditional
Do you have a Xamarin traditional app but need some Crud forms? Go ahead add in Xamarin.Forms, it can be used in Micro Areas of your application.
Do you have a Xamarin.Forms app but need to add a little HTML? Go ahead with Xamarin you can easily show Html5.

With Xamarin the Mobile world is your oyster and your possibilities endless…

50 Shades of Xamarin

 

Thanks

Michael

The post 50 Shades of Xamarin appeared first on Michael Ridland.

April 13, 2015 11:00 GMT

Android ListViews Reinvented

I learned something new last week that I felt I probably should have learned a long time ago.  As I know from my previous experience in Android development, ListViews only scroll vertically.  In the past, there was no out of the box support for horizontal ListViews in Android.  Developers had to create them manually or use 3rd party […]
April 11, 2015 6:38 GMT

Setting up Wormhole Sharp to Communicate with iOS Extensions

I am adding an Apple Watch app to my latest project and needed a way to communicate with the parent app on the phone. I looked at Wormhole for this type of communication, and I was happy to see that there is a port, appropriately named Wormhole Sharp. Wormhole and Wormhole Sharp use App Groups to create a way for apps to shared data via the iOS file system.

Download and build Wormhole Sharp from here and add a reference to both the parent and extension app projects.

Open the Entitlements.plist in the parent app project and select Enable App Groups. Add a new entry in the App Group section.
Do the same in the extension project and make sure to name the group the same

image of group

Apple requires naming groups by starting with 'group' and then using their common reverse naming style

image from apple dev site

After setting the group in both the extension, and the parent app, go and set the "Custom Entitlements" to the Entitlements.plist for both the parent and extension respectively. Do this by double clicking on the project in the solution pane.

image of entitlements

This is the most critical part, without this it will not work and you will spend a day trying to figure out what is going on.

That's it.

Next we will learn about communicating between App Extensions and the Parent App using Wormhole Sharp. I spent way more time getting this configured to work than I did with setting up back and forth communication.

April 11, 2015 2:48 GMT

Autolayout and auto-expanding UILabel

One thing I miss in iOS, which Android has, is auto expanding labels (and other views). Android has the wrap_content layout option, which works really well to flow a view.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/currency_symbol"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textColor="@android:color/darker_gray"/>

iOS was lacking that - or so I thought. In the past, I'd had to use code to measure the size of a block of text, then set the frame and adjust other things.

var size = new NSString("Text here").StringSize(font, 9999, UILineBreakMode.CharacterWrap);
label.Frame = new CGRect(label.Frame.Origin, size);

Autolayout changes things a bit. It's all declarative-y and designer-y, so I prefer to keep things like that inside the storyboard designer as much as possible. I recently learned how to do this, tho: the >= (or <=) constraint.

Storyboard Editor

In this case, I want the stop identifier (WW) to resize based on it's content. It could be blank, or it could have one or 2 letters. I'm using the size of WW - about the maximum width - as the largest size, and allowing it to resize as needed. All the other constraints which are dependant on it flow from there.

The only constraint I need to manually adjust is the space between the WW and the following label ("7" in the image - "75m North West"), as I want to remove it - set it to zero - if the stop id is blank.

This works for vertical height too. Set it to be greater than or equal to the minimum height - usually one line of text, which is around 21 points - and set the number of lines to zero. The label will now take as much vertical space as needed.


This is not something which is obvious, at least it wasn't to me, but it solves one of the big blockers I had with both Autolayout, and iOS in general - dynamic layout, especially of text.

April 10, 2015 2:42 GMT

Cold Hard Data Cache – Or Saving Our Users Money!

After that last post on SQLite, let’s explore one of the best things we can do with persisted data for the users of our mobile applications … provide a cache of data. And even better … the data cache that we’re going to give them is going to save them hard earned money!

Alright – not even I can really extend the metaphor of data caching to saving money, at least not without really stretching, so let’s just dive right into data caching, shall we?

What Is Caching & Why Is It Important?

This probably goes without saying, but when I talk about caching data within a mobile application, I am talking about saving data downloaded from the internet to the mobile device for later use. This data is not necessarily meant to be kept around forever, but having it on the device will make the user experience much more enjoyable.

There are two situations where this “more than fleeting, but not permanent data” comes in very useful.

1) Perceived performance. If we know what data our users will want to see next, we can download it before they want it. Our app will then seem much faster because the data is already there; loading it from a local cache is obviously much faster than downloading it from the internet.

2) Offline resilience. Users never stay within network reach. They’re out there climbing mountains, sitting on the beach, or hurtling through the air in an aluminum tube. But no matter what, they have come to expect that the app should still work, even when they’re offline. Providing a cache of data will at least all the app to maintain its state the last time it was connected to the internet.

What Data Should We Cache?

Of course, some types of data are tailored made for caching, while other types make no sense at all. Any data which does not change very often, or is not very time sensitive is a good candidate for caching. Data which changes often, stock prices or the weather, do not fit well into a caching model.

Any data which is not overly time sensitive is a good candidate to be cached

Examples of good data to cache:
  • Twitter stream
  • Product data from a retailer
  • RSS feed
  • News stories
  • Plane or concert tickets
  • Anything of historical nature

How Do We Cache In Xamarin Apps?

I thought you’d never ask! There a couple of ways we can go about this, but in this post we’ll create our own caching logic with SQLite as the backend. In a future post, we’ll refactor the project to use Akavache, a library created by Paul Betts that does a lot of the work (and I do mean a lot) for us. But before we run, we have to walk, and it’s best to understand how everything fits together first.

The Project

We’re going to build an application that downloads questions and answers from StackOverflow that are tagged with “Xamarin”. The app will then be able to scroll through a list of all the questions. It will allow a user to tap on a question’s row, and then view an answer for that question. A simple navigation page Xamarin Forms app.

The data caching part comes in to play that we’ll be saving both the questions and answers to a SQLite database, so they will be available for offline use. (That way when we’re doing development in the deepest, darkest reaches of a coffee shop where no wifi signal has ever been encountered … we’ll still able to get our StackOverflow questions & answers)!

The way the StackOverflow API works (or at least the way we’re using it here), we first have to download questions, then download the answers. So, to increase perceived performance with data caching, we’ll grab the answers in the background after the questions have been downloaded. This will give the user the impression of a fast load time – because we know what they want to view even before they do!

So that’s how we’ll use data caching in this app. But first, let’s take a look at the pre-cache version…

Before Caching

Loading the StackOverflow questions into the ListView looks something like this:

protected async Task LoadQuestions() {
    _displayQuestions.Clear ();

    var questionAPI = new QuestionService ();

    var downloadedQuestions = await questionAPI.GetQuestions ();

    foreach (var question in downloadedQuestions) {
        _displayQuestions.Add (question);
    }                
}

Pretty simple and straight forward. All we’re doing is calling out to a class which encapsulates a web service and adding the return to an ObservableCollection named _displayQuestions.

In the same way, when we load up the answer to be shown, we do the following:

protected async Task LoadAnswers (int questionId)
{                
    var answerAPI = new StackOverflowService ();
            
    var downloadedAnswer = await answerAPI.GetAnswerForQuestion (questionId);

    if (downloadedAnswer != null) {                
        _theAnswer.AnswerID = downloadedAnswer.AnswerID;
        _theAnswer.QuestionID = downloadedAnswer.QuestionID;
        _theAnswer.AnswerBody = downloadedAnswer.AnswerBody;
    } else {
        _theAnswer.AnswerBody = "No answer found";
    }        
}

Adding The Cache

Now let’s add some cache to the app! The entire project can be found on GitHub here.

At a high level, caching involves the following:

  • Downloading data from the network
  • Saving the downloaded data to the cache
  • Deleting any data no longer needed from the cache
  • Displaying a combination of data downloaded and loaded from the cache

The biggest thing to remember here is that there is no one correct way to implement the points above. The business logic of your application will decide that for you.

Downloading the data

This really isn’t any different than what we looked at above when we didn’t have caching in place. However, one thing to note is that we should check for network connectivity and be explicit in communicating the results back to the user. This way the user is fully informed as to whether the data coming back is “fresh” from the internet, or “stale” from our cache.

James Montemagno has a great cross platform plugin to check connectivity called, of all things, Connectivity Plugin it’s really worth checking out, and is on NuGet as well.

Saving, deleting and displaying the data

The next 3 points from above will all get smooshed together for illustration purposes.

But this is where we get to use some of the techniques we learned last week in the SQLite post!

The first thing I want to look at is our data persistence. Below are 3 functions which perform the basic CRUD operations on our models. Nothing special going on here at all. If anything – the only fun thing is that we’re considering anything older than 2 days too old to be in the cache … technology! It moves at the speed of light!

public async Task<IList<QuestionInfo>>GetQuestions() 
{
    return await Table<QuestionInfo> ().ToListAsync ().ConfigureAwait (false);
} 

public async Task SaveQuestions(IList<QuestionInfo> questions)
{
    foreach (var item in questions) {
        int questionId = item.QuestionID;

        var dbRecord = await Table<QuestionInfo> ()
            .Where (qi => qi.QuestionID == questionId)
            .FirstOrDefaultAsync ().ConfigureAwait (false);

        if (dbRecord == null)
            await InsertAsync (item).ConfigureAwait (false);
        else
            await UpdateAsync (item).ConfigureAwait (false);
    }
} 

public async Task DeleteQuestionsAndAnswers()
{
    DateTime cutOff = DateTime.Now.AddDays (-2);

    var oldQuestions = await Table<QuestionInfo> ().Where (qi => qi.InsertDate < cutOff).ToListAsync ().ConfigureAwait (false);

    foreach (var item in oldQuestions) {
        var questionId = item.QuestionID;

        var oldAnswers = await Table<AnswerInfo> ().Where (ai => ai.QuestionID == questionId).ToListAsync ().ConfigureAwait (false);

        foreach (var oa in oldAnswers) {
            var answerId = oa.AnswerID;
            await DeleteAsync<AnswerInfo> (answerId);
        }

        await DeleteAsync<QuestionInfo> (questionId);
    }
}

Where the fun starts to happen in the next section below, this is where we tie everything together.

  1. Delete anything in the cache that’s too old to display
  2. Load up the remaining cached items from the database
  3. Download any new questions from StackOverflow
  4. Populate the user interface with those questions
  5. In the background, save the downloaded questions to the cache (for offline resilience)
  6. In the background, download any answers to the questions (for perceived performance)

And that’s exactly what’s happening in the code below:

protected async Task LoadQuestions ()
{
    _displayQuestions.Clear ();

    // 1. Get rid of anything too old for the cache
    await App.StackDataManager.Database.DeleteQuestionsAndAnswers();

    // 2. Load up cached questions from the database
    var databaseQuestions = await App.StackDataManager.Database.GetQuestions ();

    foreach (var item in databaseQuestions) {
        _displayQuestions.Add (item);
    }

    try {
        // 4. Load up new questions from web
        var questionAPI = new StackOverflowService ();
        var downloadedQuestions = await questionAPI.GetQuestions ();
        var newQuestionIDs = new List<int>();

        foreach (var question in downloadedQuestions) {
            if (_displayQuestions.Contains (question) == false) {
                _displayQuestions.Insert (0, question);
                newQuestionIDs.Add(question.QuestionID);
            }
        }

        await App.StackDataManager.Database.SaveQuestions (downloadedQuestions);

        if (newQuestionIDs.Count > 0)
            await GrabAnswers(newQuestionIDs);

    } catch (NoInternetException) {
        await HandleException ();
    }
}

// 5. Proactively grab the answer for the questions
protected async Task GrabAnswers(List<int> questionIDs)
{           
    var soAPI = new StackOverflowService ();

    var lotsOfAnswers = await soAPI.GetAnswersForManyQuestions (questionIDs);

    await App.StackDataManager.Database.SaveAnswers (lotsOfAnswers);
}

To indicate whether a question was loaded from the database or grabbed from the web, I’m prefixing the title of the question with a “D” (for database) or “W” (for web) to indicate to the user where it came from in the model class. Not pretty, not elegant – but it gets the point across.

public string TitleWithLoadFrom {
    get {
        if (LoadedFromWeb)
            return "W - " + this.Title;
        else
            return "D - " + this.Title;
    }
}

Then for the sake of completeness, here is what the LoadAnswer function turned into when caching was added. It first checks the database, then the web, then it gives up and says it can’t find anything.

You may be wondering why we’re checking the database first and not going out to the web and seeing if there are any new answers to display. And why are we only displaying one answer?

That gets back to the point I made above, there is no one correct way to implement data caching, the business requirements for your app will decide that for you. And the business requirements for this app were to get it out the door ASAP and to make this point while doing it!

protected async Task LoadAnswers (int questionId)
{   
    AnswerInfo currentAnswer = null;

    // 1. Load from the database
    currentAnswer = await App.StackDataManager.Database.GetAnswerForQuestion (questionId);

    if (currentAnswer != null) {
        _theAnswer.AnswerID = currentAnswer.AnswerID;
        _theAnswer.QuestionID = currentAnswer.QuestionID;
        _theAnswer.AnswerBody = currentAnswer.AnswerBody;
    } else {
        // 2. No database record... Load answer from the web            
        var answerAPI = new StackOverflowService ();

        var downloadedAnswer = await answerAPI.GetAnswerForQuestion (questionId);

        if (downloadedAnswer != null) {             
            _theAnswer.AnswerID = downloadedAnswer.AnswerID;
            _theAnswer.QuestionID = downloadedAnswer.QuestionID;
            _theAnswer.AnswerBody = downloadedAnswer.AnswerBody;

            // 3. Save the answer for next time
            await App.StackDataManager.Database.SaveAnswer (_theAnswer);

        } else {                    
            _theAnswer.AnswerBody = "No answer found";
        }
    }
}

To indicate to the user whether the answer came from the cache or the web, I have a label on the screen which says database or web on the page. It is data bound to a property whose change event fires when AnswerBody gets changed. Again, not elegant, but it gets the point across.

public string AnswerBody {
    get { return answerBody; }
    set{
        if(answerBody != value) {
            answerBody = value;
            OnPropertyChanged ("AnswerBody");
            OnPropertyChanged ("LoadedFromText");
        }
    }
}

[Ignore]
public string LoadedFromText {
    get {
        return LoadedFromWeb ? "Loaded From Web" : "Loaded From Database";
    }
}

You can view the full code on GitHub.

Summing It Up

Really, when you think about it, providing a data cache for your users, whether it be to enable offline access of the app, or to provide a perceived performance increase, is just plain nice to do! In fact, it really should be expected for any app that downloads any sort of data from the internet.

The big things that you’re going to want to remember about caching are:
1. Caching offers both perceived performance gains and offline resiliency to your application.
2. Only certain types of data are ideal for caching, data that’s not very time sensitive.
3. The specifics of how you implement the caching will vary greatly from situation to situation.

April 09, 2015 11:46 GMT

Advanced transitions with vector drawable

As I described in a previous serie of post, vector drawables (and their animated counterparts) are one of the most powerful new visual elements introduced with Lollipop (and soon as a support lib it seems).

In this post, I’m gonna show you how we can achieve the following transition animation by solely using vector drawables and Android’s built-in widget state tracking mechanism:

Staging

To build an animation like this, you have to prepare the adequate stage. Afterwards, it’s just a matter of moving each individual pieces of that stage when needed.

In the above video, we can split the final visual in a couple of different parts.

Some like the center dot and the upper-half donut are static pieces, they never move. The two white thin rectangles, symbolizing the hands on a watch, are individual moving parts. The sun, moon and exclamation mark symbols are the varying state of the visual depending on the input.

Now, that’s only the visible part of the puzzle. If you look closely at the animation you can notice that everytime there is a state transition the right hand seems to be erasing the visible time symbol before the new one fade in.

This is where things get interesting because to be able to achieve this effect you have to get creative with the Z-ordering of your stage.

To understand this better, below is a rendering of all the layers of the visual:

The rectangle you see covering the half-bottom part of the picture is not an artifact. It’s painted with the same color than the overall window background thus acting as a cheap but effective hiding mask.

If I conceal this rectangle, here is what’s lurking behind: the other half of the visible top donut

To create the aformentioned effect, we will be moving that half-bottom donut to cover the top one, synchronizing it with the right clock hand. When not in use, it will be safely tucked behind our hiding rectangle.

Because vector drawables have a simple bottom to top drawing hierarchy, for this to work correctly we have declare pieces in a specific order:

  • top half donut
  • the 3 time symbols
  • bottom half donut
  • hiding rectangle
  • the 2 hands white rectangle

Based on our animation needs, we then split this further into actual vector drawable <group /> elements to arrive at the following shape (path data removed for brevity, you can download all the XML pack at the end of the article):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?xml version="1.0" encoding="UTF-8" ?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
	android:height="385dp"
	android:width="416dp"
	android:viewportHeight="385"
	android:viewportWidth="416">
	<group android:name="background">
		<path
			android:name="topPie"
			android:fillColor="#454D58"
			android:pathData="..." />
	</group>
	<group android:name="timeItems">
		<path
			android:name="moon"
			android:fillColor="#DAE2ED"
			android:fillAlpha="0"
			android:pathData="..." />
		<path
			android:name="sun"
			android:fillColor="#E39300"
			android:fillAlpha="0"
			android:pathData="..." />
		<path
			android:name="now"
			android:fillColor="#C52E26"
			android:fillAlpha="1"
			android:pathData="..." />
	</group>
	<group
		android:name="hidingPie"
		android:pivotX="208"
		android:pivotY="192.5">
		<path
			android:name="hidingPiePath"
			android:fillColor="#454D58"
			android:pathData="..." />
	</group>
	<group android:name="coverBackground">
		<path
			android:name="blueCover"
			android:fillColor="#343A42"
			android:pathData="..." />
		<path
			android:name="middleRing"
			android:fillColor="#D8D8D8"
			android:pathData="..." />
	</group>
	<group
		android:name="leftHand"
		android:pivotX="208"
		android:pivotY="192.5">
		<path
			android:fillColor="#D8D8D8"
			android:pathData="..." />
	</group>
	<group
		android:name="rightHand"
		android:pivotX="208"
		android:pivotY="192.5">
		<path
			android:fillColor="#D8D8D8"
			android:pathData="..." />
	</group>
</vector>

State tracking widget

Before we dwelve into some more animation tricks, we first need to investigate how to make widget to represent our triple state because there is nothing in the default framework that allow this.

The good news is that, as I showed in a previous blog, it’s very easy to create a custom, state-aware widget which is what we are going to do with this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class TriStateView : View
{
	int selectedIndex;

	public int SelectedIndex {
		get {
			return selectedIndex;
		}
		set {
			if (value < 0 || value > 2)
				throw new ArgumentOutOfRangeException ("value");
			JumpDrawablesToCurrentState ();
			selectedIndex = value;
			RefreshDrawableState ();
			Invalidate ();
		}
	}

	protected override int[] OnCreateDrawableState (int extraSpace)
	{
		switch (selectedIndex) {
		case 0:
			return new int[0];
		case 1:
			return new int[] { Android.Resource.Attribute.StateFirst };
		case 2:
			return new int[] { Android.Resource.Attribute.StateLast };
		default:
			return base.OnCreateDrawableState (extraSpace);
		}
	}
}

By setting our state transition drawable as the background of this view, it will automatically react to state changes and animate accordingly. Using the normal state tracking mechanism also means that interruption mid-animations are gracefully handled for us.

One more trick

At this stage, I won’t go over every details of the individual animation definitions, they all tweak standard things like alpha and rotation on each piece of our stage. Nonetheless, you can read my animated vector drawable entry for more details on how they work.

I will only show a little trick that is useful when setting up more complex stages like this: zero-duration animators.

Take the following example that animates the bottom-half donut (to create the progressive hiding effect):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="UTF-8" ?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
	android:ordering="sequentially">
	<objectAnimator
		android:duration="850"
		android:propertyName="rotation"
		android:valueFrom="0"
		android:valueTo="180"
		android:valueType="floatType"
		android:interpolator="@android:interpolator/decelerate_quad" />
	<objectAnimator
		android:duration="0"
		android:propertyName="rotation"
		android:valueFrom="-180"
		android:valueTo="0"
		android:valueType="floatType" />
</set>

The idea is that right after we have covered the entire upper-half, we want to immediately tuck it back under our hiding rectangle. This is because we then fade-in the new time symbol which would be hidden too otherwise.

Using zero-duration animators allow you to do just that by applying direct values to animated properties. The fact that there is a from attribute doesn’t matter much but since those properties are write only it will prevent object animator from complaining about missing accessors.

I use this in a couple of places to reset the stage state (since vector drawable instances are reused across transitions), quickly move away elements or hide them from view when they are not useful anymore.

Source

You can download the XML definitions and widget source here.

Bug alert: there is currently a parsing bug where the animated vector drawable inflater will greedily read the entire document given to it. This causes an issue if you declare them inline in your animated state transition XML file because it will corrupt your entire state by reading everything instead of stopping at its corresponding end tag. The workaround is to always declare them in their own XML files like I did.

April 07, 2015 1:11 GMT

The $20,000 Xamarin Programmer

If Xamarin programing is going to be how you make your living,  then I highly recommend this list of hardware and software.

iOS, OSX, Android, Windows Phone, Windows

 

ParallelsIf you are going to develop on both Mac and Windows, it is painful to switch back and forth between machines.

Ideally, you’ll run Windows on a Mac, using Parallels or something similar. Parallels is the right thing, but you need hardware that will fully support dual operating systems.

MacPro

MacProBut even a fully tricked out MacBookPro is not quite powerful enough to make this entirely painless.  When compiling in Windows, I find that the Mac slows to a crawl.

The solution is to get serious and buy a MacPro (desktop) with enough memory (32GB) and enough Cores (6) to never experience a slow down.  You’ll also want to get a lot of storage, I recommend at least a Terrabyte of Flash storage.  This configuration will set you back just over $5,000.

 

Continued here

 

 

April 07, 2015 8:34 GMT

iOS WebView insets

I have been battling some UI constraints on iOS and I have finally found a solution to how to solve this specific problem and just wanted to share.

My problem was that I had a UIWebView, which kept laying itself out underneath the NavigationBar in my controller. A quick fix would be to just set edges for the extended layout to none like so:



However, this will make you lose the nice effect of views scrolling behind the NavigationBar, for instance if the web page you are displaying scrolls.
Enter insets. As the name kind of indicates you add some spacing into your view. There is a property called AutomaticallyAdjustsScrollViewInsets. However, for some reason it does not do anything in my case, so I had to manually adjust the inset, which I did in ViewWillLayoutSubviews as in ViewDidLoad the TopLayoutGuide is not ready yet and will give you 0 for its Length. Basically this is what I had to do:



This tells both the UIWebView's internal ScrollView and the scroll bar that you want some space in the top equals to the height of the NavigationBar.
April 07, 2015 6:52 GMT

Xamarin.Forms Android CardView

When Google introduced Material Design for Android they introduced a new view called CardView. Xamarin.Forms doesn’t have support for CardView by default but you can easily create your own view that renderers a CardView on Android.

First step is to create a Xamarin.Forms control in your shared project.

public class CardContentView : ContentView
{
 
 
		public static readonly BindableProperty CornerRadiusProperty = 
			BindableProperty.Create<CardContentView,float> 
		( p => p.CornderRadius, 3.0F);   
 
 
 
        public new static readonly BindableProperty BackgroundColorProperty =
            BindableProperty.Create<CardContentView, Color>
        (p => p.BackgroundColor, Color.White);
 
        public float CornderRadius
        {
            get { return (float)GetValue(CornerRadiusProperty); }
            set { SetValue(CornerRadiusProperty, value); }
        }
 
        public new Color BackgroundColor
        {
            get { return (Color)GetValue(BackgroundColorProperty); }
            set { SetValue(BackgroundColorProperty, value); }
        }
 
		protected override SizeRequest OnSizeRequest (double widthConstraint, double heightConstraint)
		{
			if (Content == null)
				return new SizeRequest(new Size(100, 100));
 
			return Content.GetSizeRequest (widthConstraint, heightConstraint);
		}
	}

Next step is to create a custom renderer for Android, on iOS and Windows it will be rendered as a regular ContentView.
You need to add a NuGet package named Xamarin.Android.Support.v7.CardView to get the Android CardView. The renderer will inherit form CardView and implement the IVisaulElementRenderer interface. To get card shadow on both Android KitKat and Android Lollipop you have to set UseCompatPadding to true. You have to remove all view from the ViewGroup, if you don’t do that you will get problems when you using the control in a ListView. The Load method on the VisualElementPackager will load content in to the Card.

[assembly:ExportRendererAttribute(typeof(CardContentView), typeof(CardViewRenderer))]
namespace CardViewFormsAndroid
{
	public class CardViewRenderer : CardView, 
		IVisualElementRenderer
	{
		public CardViewRenderer () : base (Forms.Context)
		{
		}
 
		public event EventHandler<VisualElementChangedEventArgs> ElementChanged;
 
		bool init;
		ViewGroup packed;
		public void SetElement (VisualElement element)
		{
			var oldElement = this.Element;
 
			if (oldElement != null)
				oldElement.PropertyChanged -= HandlePropertyChanged;
 
			this.Element = element;
			if (this.Element != null) {
 
				this.Element.PropertyChanged += HandlePropertyChanged;
			}
 
            ViewGroup.RemoveAllViews();
				//sizes to match the forms view
				//updates properties, handles visual element properties
				Tracker = new VisualElementTracker (this);
 
            Packager = new VisualElementPackager(this);
            Packager.Load();
 
            UseCompatPadding = true;
 
            SetContentPadding((int)TheView.Padding.Left, (int)TheView.Padding.Top,
                   (int)TheView.Padding.Right, (int)TheView.Padding.Bottom);
 
                Radius = TheView.CornderRadius;
                SetCardBackgroundColor(TheView.BackgroundColor.ToAndroid());
 
			if(ElementChanged != null)
				ElementChanged (this, new VisualElementChangedEventArgs (oldElement, this.Element));
		}
 
 
 
 
		public CardContentView TheView
		{
			get { return this.Element == null ? null : (CardContentView)Element; }
		}
 
 
		void HandlePropertyChanged (object sender, System.ComponentModel.PropertyChangedEventArgs e)
		{
			if (e.PropertyName == "Content") {
 
                //Packager.Load();
 
                Tracker.UpdateLayout();
            } else if (e.PropertyName == CardContentView.PaddingProperty.PropertyName) {
				SetContentPadding ((int)TheView.Padding.Left, (int)TheView.Padding.Top,
					(int)TheView.Padding.Right, (int)TheView.Padding.Bottom);
			} else if (e.PropertyName == CardContentView.CornerRadiusProperty.PropertyName) {
				this.Radius = TheView.CornderRadius;
			} else if (e.PropertyName == CardContentView.BackgroundColorProperty.PropertyName) {
				if(TheView.BackgroundColor != null)
				SetCardBackgroundColor (TheView.BackgroundColor.ToAndroid ());
 
			}
		}
 
		public SizeRequest GetDesiredSize (int widthConstraint, int heightConstraint)
		{
			packed.Measure (widthConstraint, heightConstraint);
 
			//Measure child here and determine size
			return new SizeRequest (new Size (packed.MeasuredWidth, packed.MeasuredHeight));
		}
 
		public void UpdateLayout ()
		{
			if (Tracker == null)
				return;
 
			Tracker.UpdateLayout ();
		}
 
		public VisualElementTracker Tracker {
			get;
			private set;
		}
 
        public VisualElementPackager Packager
        {
            get;
            private set;
        }
 
        public Android.Views.ViewGroup ViewGroup {
			get{ return this; }
		}
 
		public VisualElement Element {
			get;
			private set;
		}
 
 
    }
}

You can browse the complete code with a working example on GitHub, https://github.com/dhindrik/Xamarin.Forms-Awesome-Controls
The repository is a fork from James Montemagno’s repository for awesome Xamarin.Forms controls. What I have done is that I have changed a few things so can have layouts as content, a StackLayout for example.