July 27, 2015 8:18 GMT

Join Xamarin at AnDevCon 2015 in Boston

Join Xamarin in Boston, MA from July 30-31 for AnDevCon 2015, the technical conference for software developers and engineers building Android apps. Key members from the Xamarin team will be available to discuss your apps and projects and show you what’s new across our products.

AnDevCon 2015 Boston Banner

We’re excited to give AnDevCon 2015 attendees a close up look at Xamarin Test Cloud, which we recently announced will be getting support for Appium and its multiple language bindings, including Java, JavaScript, Python, and PHP. You’re invited to join our early access program, and we’ll have members from our Xamarin Test Cloud team onsite at the conference to answer any of your questions.

Come visit us at booth #803 and say hello if you’re at the conference — we look forward to seeing you in Boston!

The post Join Xamarin at AnDevCon 2015 in Boston appeared first on Xamarin Blog.

July 27, 2015 6:16 GMT

Data Binding a Custom Cell in Xamarin.Forms ListView

Data Binding a Custom Cell in Xamarin.Forms ListView

The ListView in Xamarin.Forms has a lot of options, and the ability to use a custom cell is one of the more useful features.

Data is the lifeblood of every business. Displaying that data is incredibly important. It doesn't matter if the company is a brick-n-mortar or an online business -- data is important. Here's how to create a custom cell to display data within a table using Xamarin.Forms.Cell.

July 26, 2015 3:35 GMT

Solved with a Facepalm: Small Resolution Screenshots with Calabash

As I've mentioned on my blog before, I like to use Xamarin's UITest library (and Calabash, by extension) to help automate the generation of app screenshots. This allows me to reuse my existing UI testing code as well, making it incredibly easy to create the generation scripts.

Earlier this year I ran into an issue where the screenshots being generated for the iPhone 6 and 6 Plus were coming out at a lower resolution than expected, which meant they couldn't actually be used since Apple validates their dimensions. I subsequently opened this issue on Calabash for it. I spent a little time digging through the Calabash code and didn't find anything that stood out as being particularly problematic. In fact, the code around screenshot generation was very straightforward and by the books.

Fast forward six months (side note: crap, where did 2015 go?), and in revisiting this code for the first time since then it quickly hit me what was actually happening there. It's like the old medical diagnostic saying goes:

When you hear hoofbeats, think of horses not zebras.

What was actually happening here is that this particular app wasn't set up for proper support of the iPhone 6 and 6 Plus sizes, meaning that iOS was actually running them in a scaled mode on those devices. This wasn't the end of the world, and the app actually didn't look particularly bad in that mode, but this meant that the resolution of the app wasn't truly the full resolution of the screen. Saving a screenshot directly from the simulator would be at full resolution, however, which is what caused the initial confusion.

Facepalm City, Population: Me.

To solve this, all I needed to do was switch to using the proper launch screens to enable proper support of these devices. With that in place, screenshots captured through Calabash came out with the expected resolutions. Ultimately this was a pretty silly mistake on my part, but I wanted to share in case someone else runs into this as well.

July 25, 2015 5:20 GMT

The end of NRefactory 6

I've been developing for NRefactory several years now after the roslyn release I made a new 6.0 version. For the 6.0 version there are bad and good news.
The bad news is that it's no longer in development.

The good news is that the successor of the refactoring part is (RefactoringEssentials). The rest of the code has been moved to the monodevelop source code and is still available and in active development as open source.

So the 5.0 version will remain - and will be still maintained a bit by Daniel Grundwald and me.

Why was this decision made ?

Mostly because most NRefactory6 code was just wrappers around internal roslyn classes (and making them public). I don't think that it's worth as a stand alone library.
Since #Develop was discontinued the 2nd big NRefactory user is no longer around and it's more time effective to move that code to monodevelop and split the refactorings so they can be used in VS.NET 2015 as well.

So I deleted the NRefactory6 today. Bye NRefactory we had a nice time - and hello RefactoringEssentials :)
July 24, 2015 6:29 GMT

More Awesome Content from Our Community

Xamarin developers not only build amazing iOS and Android apps in C#, but love contributing to the Xamarin community through blog posts, components, plugins, and podcasts. The links below will take you to some of favorites over the past few weeks:

Podcasts

Yet Another Podcast with Jesse Liberty

James Montemagno and Jesse Liberty discuss all things Xamarin.

  • Yet Another Podcast – James Montemagno joins Jesse Liberty discuss all things Xamarin, including My Shoppe, Moments, and Xamarin Dev Days.

Great Blog Posts

Awesome Xamarin.Forms Blog Posts

Adam Wolf’s card UI with a drop shadow using Xamarin.Forms.

Thanks to these developers for sharing their Xamarin knowledge with the rest of the developer community. If you have an article or blog post related to Xamarin development that you would like to share, please let us know by tweeting @XamarinHQ and it may be featured in an upcoming community content roundup.

The post More Awesome Content from Our Community appeared first on Xamarin Blog.

July 24, 2015 1:30 GMT

Weekly Xamarin Newsletter Issue #50

Xamarin’s Newest MVPs!
Joseph Hill, from Xamarin Inc., add 9 more awesome people to the Xamarin MVP program. Congrats!

Same Day Xamarin Support for Visual Studio 2015
Miguel de Icaza, from Xamarin Inc., announces same day support for Visual Studio!

Xamarin with James Montemagno
Jesse Liberty has James Montemagno on the “Yet Another Podcast” podcast.

Xamarin.Forms Nugget – Card Shadows
I (Adam) give my reads what they needed. Card UI with shadows.

Line spacing label in Xamarin Forms
Rob Waggott, from The Technology Studio, extends Xamarin.Forms Labels to get more space.

Build Your Own Messaging App in XAML
Pierce Boggan, from Xamarin Inc., announces the Moments Xamarin.Forms app now comes in Xaml and code.

Xamarin.Forms Typographic Scale
I (Adam) reminisce about the days of H1, H2, H3, H4 and H5 in web apps.

Implementing custom navigation in FreshMvvm for Xamarin.Forms
Michael Ridland gets fresh with his FreshMvvm library when navigating.

Xamarin Dev Days Recap and Expansion
James Montemagno, from Xamarin Inc., wraps up and extends Xamarin Dev Days.

Uploading your iOS DYSM to Xamarin Insights using Grunt
Rob Waggott, from The Technology Studio, does all the dirty work to get you better app insights.

A Comprehensive Guide to Creating a Xamarin.Forms App with MvvmCross (Part 5 of 5)
Brent Edwards, from Magenic, adds part 5 to his Xamarin.Forms and MvvmCross series.

First thoughts on Amazon Device farm (From a Xamarin perspective)
George Cook, from Twin Technologies, whips up a back of the napkin comparison of Xamarin Test Cloud and Amazon Device.

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

July 24, 2015 11:33 GMT

Updating Mobile Development Environment

On 20th July, Microsoft released Visual Studio 2015. This release of Visual Studio includes improvements in terms of IDE features, Language features and even changes in underlying .NET framework. Along with this, Microsoft is also releasing Windows 10 on 29th July, which will add Universal Windows Platform (UWP) development capabilities to Visual Studio. In this blog post, I’m going to cover the features that are most important for us i.e. mobile developers. Having said that, if you want to build UWP apps on RTM, hold on till July 29th, as the SDK and tooling for UWP will be released on the same day. You can find that information here.

Install Selection

You can think Visual Studio 2015 as the most complete mobile development IDE. You can build any kind of mobile applications which can run on Android, iOS and Windows devices. To setup your environment for mobile development, while installing itself, make sure you select your required tools. For example, here I’ve selected Xamarin tools to build native mobile applications. In this case, Visual Studio will install the necessary SDKs and libraries e.g. Android SDKs & NDKs with different API levels, Java SDK, etc…

VS 2015 Install

If you’re already a Xamarin developer, you may want to install Xamarin Studio, which needs to be installed separately by downloading Xamarin Installer from the site. With open sourcing of .NET and Roslyn, even Xamarin Studio is using some of its benefits. You can read more about it from Miguel’s blog.

Xamarin Integration & Project Template

Previously (VS 2013 or prior), you had to install Xamarin to get Xamarin specific project templates. With VS2015, if you select above option during install, you’ll have Xamarin project templates in File > New Project Dialog.

VS 2015 Project TemplatesNote: The difference between Blank App (Native Portable) & Blank App (Xamarin.Forms Portable) is literal. That means, later one has Xamarin.Forms NuGet and integration in all projects. First one, just creates 4 separate projects without Xamarin.Forms dependencies.

When you create a Xamarin project, Visual Studio will ask you to sign into your Xamarin account to use different features according to license.

VS 2015 Xamarin

Developer (aka God) Mode

As I mentioned above, if you want to build UWP apps on RTM, you’ll need to wait till 29th July. And to enable Windows Store apps development and debugging on your machine, you’ll need to enable a ‘Developer Mode’. When you create a new project you’ll get following dialog which can take you to next dialog, where you need to select ‘Developer Mode’ and you should be able to test your apps. Do the same thing in your Windows 10 mobile device, if you want to debug apps directly on mobile.

VS 2015 - Developer Mode

VS 2015 - Developer Mode Enabled

Accessing Tools

This is not new as such to Visual Studio 2015, but I want to add it here for your reference. You can find all the tools and setting related to Xamarin and mobility under Tools menu. So, if you want to download new API Level (for example Android M Preview) or monitor your Android app’s performance on device using Android Device Monitor, you know where to look for. We’ll cover tools and features exclusive for Windows 10 in next post.

VS 2015 ToolsBy the way, if you ever face any issues with Xamarin and need to contact support, Xamarin logs can help you to share more information about your issues with Support guys. Even, you can go through them and find issues/reasons. You can find them easily under Help > Xamarin

If you want to check where exactly platform SDKs are installed, you can find in Tools > Options and at two different selections

VS 2015 - SDK Location - 1

VS 2015 - SDK Location - 2

More Resources

Now, if you want to know more about Visual Studio 2015 and .NET Framework, Microsoft Channel 9 has Connect On-Demand series on it. Some of the most important videos are here

What’s new in C# 6
New Coding Experiences for C# and Visual Basic
What’s New for .NET 2015
Developing iOS and Android Apps in C# with Visual Studio
Xamarin.Forms: Leaveraging XAML to Build iOS, Android, and Windows Apps
Wearables in C#: Highlighting Apple Watch, Android Wear, and Microsoft Band
GitHub Extensions for Visual Studio

I’ll update tendulkar-uvāca series with new tools and technologies once they are released i.e. after 29th July. Till then, download the Visual Studio 2015 and enjoy the new IDE & tooling.

By the way, have I told you: You get Visual Studio 2015 Community Edition free for specific use cases and along with it, you get Xamarin Starter for free. If you’re a student, you can get more benefit through Microsoft DreamSpark program.

Namaste
Mayur Tendulkar

 

July 24, 2015 12:42 GMT

Best practices for using Xamarin Plugins

I’m sure by now you’re aware of the great amount of Plugins available for Xamarin. There’s plugins for almost everything, connectivity, localstorage, settings etc etc.

Generally these plugins are very easy to use, you can download from nuget and start using in a few single lines. Most of the documentation/blogs will show the single liners. Which sounds good to begin with but calling a dependency/API directly isn’t good as it tightly couples your business logic and makes unit testing very difficult.

Fortunately most of the plugins are interface based which means they support Inversion of Control, even if they don’t have interfaces you can supply your own interfaces.

Let’s take a look at an example using the Acr UserDialogs plugin.

You’ll notice that even examples call the API directly.

1
await UserDialogs.Instance.AlertAsync("Test alert", "Alert Title");

No, no, no, don’t do this. Highly coupled code will end you in bad places.

The correct way, well one of the correct ways, to implement a service like this is to use a IOC container and have the dependencies injected into your PageModels. Any good Mvvm Framework will support this. In this example I’m going to show you how to implement using FreshMvvm.

Below I add the UserDialogs Instance into the IOC container during my application startup.

It’s a single line: FreshIOC.Container.Register<IUserDialogs> (UserDialogs.Instance);

Screen Shot 2015-07-23 at 10.46.14 am

Because I’m using the Mvvm Framework to push between PageModels I can easily have the plugin dependency injected into the object. In the sample below I’m using my QuotePageModel that shows the dialog when a quote is being saved. NB* Those dependencies are injected into the Model automatically.

Screen Shot 2015-07-23 at 10.56.10 am

The dependencies can now be used from within the Commands.

Screen Shot 2015-07-23 at 10.59.22 am

Now that we’ve setup dependencies correctly we can easily unit test our PageModel methods. In the sample below I’m using the Moq framework to Mock out our dependancies and Verify the Update Quote method gets called.

Screen Shot 2015-07-24 at 10.34.39 am

It’s a very small change and it’s very easy to implement, the tradeoff of using Plugins in this manner is well worth the effort.

All this code is taken from a sample app that I’ve uploaded to github.

Thanks

Michael

 

The post Best practices for using Xamarin Plugins appeared first on Michael Ridland.

July 23, 2015 5:33 GMT

Build Your Own Messaging App in XAML

One of the most popular features of Xamarin.Forms is the ability to use your existing XAML experience to build UIs for iOS, Android and Windows Phone. Moments, a Snapchat clone built with Xamarin.Forms and Microsoft Azure, originally made use of the C# API for creating user interfaces. Today, I’m happy to announce that Moments has been expanded to include a XAML implementation as well, so you can build your own Snapchat clone in XAML today!

Moments, a Snapchat clone built with Xamarin.Forms and Azure.

Build Cross Platform UIs in XAML

If you are coming from a Windows background, Xamarin.Forms XAML will feel right at home! If you aren’t, there are still plenty of great reasons to build your user interface using XAML.

Readability

XAML is often more succinct and readable than the equivalent code in C#. This is especially true when building complex view hierarchies with multiple layouts. Additionally, the parent-child hierarchy inherent in XML allows XAML to mimic the hierarchy of user interface objects with greater visual clarity.

Separation of Concerns

Rather than having an entire page represented in one file, XAML allows you to clearly separate views from the accompanying logic associated with the view, thus making your application more modular.

MVVM Data Binding & Commands

The Model-View-ViewModel (MVVM) architectural pattern is very common in mobile development today – and for good reason. Traditionally, MVVM allows you to further enforce separation of concerns by separating the user interface from the data, with a bridge called a view model. Typically, mobile developers can share the model and view model with all target platforms, while writing the view for each individual platform. With Xamarin.Forms, everything can be shared, including the view. XAML makes using the MVVM pattern easy through data binding and commands, which allow your view and view model to communicate with ease.

Build Your Own Snapchat Clone Today

Moments is a great sample app for seeing everything Xamarin.Forms has to offer. If you’ve ever wondered how to use custom controls from XAML, use markup extensions, implement styling, or enforce the MVVM architectural pattern through data binding and commands, Moments is the sample app for you. Moments is completely open-source and freely available under the MIT license, so building your own Snapchat clone based on Moments is easy. Follow the steps listed here, and you’ll be sending selfies to all your buddies in a matter of minutes!

The post Build Your Own Messaging App in XAML appeared first on Xamarin Blog.

July 22, 2015 6:46 GMT

Xamarin Dev Days Recap and Expansion

When we announced Xamarin Dev Days, free weekend community events filled with intense and hands-on mobile C# learning, we knew that it would be popular – but we didn’t expect every location to sell out so quickly! Each Dev Days event has been packed full of awesome Xamarin content and fun hacking, and the feedback has been absolutely outstanding.

Head Logo

Dev Days Expansion!

Since we’ve seen such an incredible response to user groups requesting Dev Days in their city, we are excited to announce the next round of Xamarin Dev Days locations. We are not only rolling out more dates and locations in the United States, but we’re also hosting our first official Dev Days event in Europe, and have many more locations in the works!

Make sure to keep an eye on the official Xamarin Dev Days website for future announcements!

Totes2

Here is a sneak peak into what a Dev Days event looks like:

Amazing Presentations

Every Dev Days start off with several presentations introducing every developer to the entire world of the Xamarin Platform, including Xamarin.Forms, Xamarin Test Cloud, and Xamarin Insights. However, it doesn’t stop there as each Dev Days event has special guest speakers from the community present on the topic they’re most passionate about. We’ve see some fantastic presentations covering all aspects of mobile development, including Wearables, MVVM, Azure Mobile Services, and Amazon Web Services, as well as plenty of Xamarin.Forms deep dives.

Sessions Green

Hands-on Learning

After lunch we hold an “Ask the Experts” session where attendees are free to ask anything and everything to get their questions answered from industry experts, and then the Xamarin Team ensures that everyone has their machines fully configured for mobile development. Next, it is on to our interactive labs, code help, and File->New App!, where attendees go through line by line to build their very own Xamarin.Forms mobile application completely from scratch with Xamarin experts guiding them along the way.

Sessions Monkey

Community, Community, Community

Xamarin Dev Days are much more than just an amazing day of hands-on mobile development learning. It’s also the perfect opportunity to connect with other developers in your local community doing amazing things. We have worked closely with local user group leaders to organize Dev Days with us, and they are there to act as your local expert not only during the Dev Days event, but long after it is over.

Amazing Sponsors

Xamarin Dev Days wouldn’t be made possible without our amazing sponsors who not only provide breakfast, lunch, and venues, but also enable Dev Days attendees with the best tools and controls in the industry.

Food Sponsor + James Sponsor3

Don’t see your city on the list yet? Don’t worry as we have plans for even more Dev Days events in the future, so be sure to head to the official Xamarin Dev Days website and request your city!

The post Xamarin Dev Days Recap and Expansion appeared first on Xamarin Blog.

July 22, 2015 12:00 GMT

Xamarin.Forms Nugget – Card Shadows

Card ShadowsIn one of my latest post for the Xamarin.Forms in Anger series, I created a Google Material Design inspired card view. One of the comments asked about shadows.

Great article! Is there a way to add shadow (like in Google’s Material Design) to the complete Card (Grid) ?

Many thanks! Marcel

The answer, is of course, YES! I wish it was as easy as setting a Shadow property to true like in the Frame control but it’s not. It’s not rocket surgery either, so let’s do this.

Shadows

To add a shadow to the CardView all you have to do is add a shadow image underneath the Grid used in the original CardView. To do that, we need to use a RelativeLayout and layer our background image and our original CardView.

I used this same technique when writing the Hot Sauce Xamarin.Forms in Anger post. If you haven’t seen it, check it out. It’s smoking hot.

Shadow Card View

I did not rewrite the CardView sample for this demonstration. I do have a life and the original CardView doesn’t look all that bad with a shadow. So I kept it.

Here is the code that changed in the CardView sample.

var layout = new RelativeLayout () {
	HorizontalOptions = LayoutOptions.FillAndExpand,
	HeightRequest = 125,
	Padding = new Thickness(0)
};

var cardBackground = new Image () { 
	Source = StyleKit.Icons.Shadow0240,
	Aspect = Aspect.Fill
};

layout.Children.Add (
	cardBackground,
	Constraint.Constant (0),
	Constraint.Constant (0),
	Constraint.RelativeToParent ((parent) => {
		return (parent.Width);
	}),
	Constraint.RelativeToParent ((parent) => {
		return (parent.Height);
	})
);

layout.Children.Add (
	grid,
	Constraint.Constant (10),
	Constraint.Constant (10),
	Constraint.RelativeToParent ((parent) => {
		return (parent.Width - 15);
	}),
	Constraint.RelativeToParent ((parent) => {
		return (parent.Height - 0);
	})
);

Content = layout;

As you can see, all I did was insert a RelativeLayout that has an Image and Grid stacked on top of each other with some margins. In this example, the image has been added to the bottom unlike the Hot Sauce sample.

Card Shadow Image

Shadow-0-2-4-0The image could not be simpler. I just opened Sketch, put a rectangle on the canvas, set the fill to be white, removed the border, then added a shadow.

The shadow settings are 2px on the Y axis and a 4px blur. Color for the shadow is a standard black with a 50% opacity. This setup makes the card have a shadow that looks like the light source is above the card.

Modifying the X axis will make the card shadow more to the right and left of the card. The Material Design standards do use a little X axis to make the light source appear above and to the right.

Top or Bottom

When you use this technique of layering, you have two choices. You can either put the image on top of the Grid or you can put it on the bottom. When you place the image on top, you have to modify the center of your shadow image. You basically have to cut a hole inside your shadow image to let the Grid below come through.

In this Nugget, we used the bottom technique. If you want to see the other, check out Xamarin.Forms in Anger – Hot Sauce.

The post Xamarin.Forms Nugget – Card Shadows appeared first on Syntax is my UI.

July 21, 2015 10:12 GMT

Xamarin’s Newest MVPs!

Xamarin MVPAs the Xamarin developer community continues to expand, it consistently provides stand out members that we are excited to include in the Xamarin MVP program. These individuals have made significant contributions by sharing their passion and expertise in mobile app development with Xamarin’s growing global 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 our latest round of Xamarin MVPs in 2015 for their remarkable contributions to the community!

chaseflorell Chase Florell Roy Cornelissen roy
mikeB Mike Bluestein Dave Evans dave
les Les Brown Adam Kemp adam
tom Tom Walker Fabian G. Williams fabian
dan Dan Hermes

A big thank you for all of your time, effort, and hard work you have dedicated to the growth of mobile development! If you know an outstanding developer who would make a great Xamarin MVP, please nominate him or her here.

The post Xamarin’s Newest MVPs! appeared first on Xamarin Blog.

July 21, 2015 11:22 GMT

Implementing custom navigation in FreshMvvm for Xamarin.Forms

In past posts I’ve already introduced the FreshMvvm framework for Xamarin.Forms. If you haven’t taken a look I suggest this post to give you an overview of FreshMvvm.

I use FreshMvvm in the majority of my projects. I love it’s simplicity but most of all it’s flexibility. The Framework is Interface based and designed to be flexible. One of the most important areas of an app is the Navigation, while FreshMvvm has some great built in Navigation abilities sometimes we might need to extend this and create our own Navigation Service.

FreshMvvm comes with an interface named IFreshNavigationService which allows any type of custom Navigation. The steps to implement a custom navigation service in FreshMvvm are as follows:

1) Implement the IFreshNavigationService interface

2) Register the implementation in the FreshMvvm IOC container

Let’s start by taking a look at the interface.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System;
using Xamarin.Forms;
using System.Threading.Tasks;
 
namespace FreshMvvm
{
    public interface IFreshNavigationService
    {
        Task PopToRoot(bool animate = true);
 
        Task PushPage (Page page, FreshBasePageModel model, bool modal = false, bool animate = true);
 
        Task PopPage (bool modal = false, bool animate = true);
    }
}

Let’s begin with a simple NavigationService using a basic NavigationPage. We can name this class SimpleCustomNavigationService, inherit from NavigationPage and implement the IFreshNavigationService interface.

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
public class SimpleCustomNavigationService : NavigationPage, IFreshNavigationService
{
    public SimpleCustomNavigationService (Page page) : base (page)
    {
    }
 
    public async Task PopToRoot (bool animate = true)
    {
        await Navigation.PopToRootAsync (animate);
    }
 
    public async Task PushPage (Page page, FreshMvvm.FreshBasePageModel model, bool modal = false, bool animate = true)
    {
        if (modal)
            await Navigation.PushModalAsync (page, animate);
        else
            await Navigation.PushAsync (page, animate);
    }
 
    public async Task PopPage (bool modal = false, bool animate = true)
    {
        if (modal)
            await Navigation.PopModalAsync (animate);
        else
            await Navigation.PopAsync (animate);
    }
}

Now that we have our Navigation service we just need 1) create the navigation service 2) register the navigation service in the IOC container 3) display the navigation service in the main page.

1
2
3
4
5
6
7
8
9
10
11
//Get the first page to be displayed
var page = FreshPageModelResolver.ResolvePageModel<MainMenuPageModel> ();
 
//create our navigation service
var customNavigationService = new SimpleCustomNavigationService (page);
 
//register the Navigation service in the app, this enables us to push model to model
FreshIOC.Container.Register<IFreshNavigationService> (customNavigationService);
 
//display navigation service in main page
MainPage = customNavigationService;

So now that we’ve correctly implemented the Navigation Service, we can achieve the holy grail, with PageModel to PageModel navigation.From any of our PageModels we can now push the PageModel by using the PushPageModel<T>.  As you would expect the ‘CoreMethods’ property is also interface based making it perfect for unit testing.

1
2
3
4
5
6
7
public Command AddContact {
    get {
        return new Command (async () => {
            await CoreMethods.PushPageModel<ContactPageModel> ();
        });
    }
}

Some more complex examples

What I find people fail to understand is that using this interface you can implement any type of advanced Navigation you like. There’s a few things to understand.

1) You can use custom logic to register a Navigation Service, an example of this would be to use to different types of Navigation Services per platform or based on screensize. In this example I’m using a MasterDetail for the Phone and a TabbedNavigation for the Tablet. You can do anything you like in this case.

1
2
3
4
5
6
7
8
9
10
11
12
if (Device.Idiom == TargetIdiom.Phone) {
    var masterDetailNav = new FreshMasterDetailNavigationContainer ();
    masterDetailNav.Init ("Menu");
    masterDetailNav.AddPage<ContactListPageModel> ("Contacts", null);
    masterDetailNav.AddPage<QuoteListPageModel> ("Quotes", null);
    MainPage = masterDetailNav;
} else {
    var tabbedNavigation = new FreshTabbedNavigationContainer ();
    tabbedNavigation.AddTab<ContactListPageModel> ("Contacts", "contacts.png", null);
    tabbedNavigation.AddTab<QuoteListPageModel> ("Quotes", "document.png", null);
    MainPage = tabbedNavigation;
}

2) The Framework doesn’t care what you put into the Push and Pop methods, you can put any type of UI logic that’s required for your interface. In this example below I’m combining a MasterDetail and a TabbedPage.

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/// <summary>
/// This is a sample custom implemented Navigation. It combines a MasterDetail and a TabbedPage.
/// </summary>
public class MasterTabbedNavigationService : MasterDetailPage, IFreshNavigationService
{
    FreshTabbedNavigationContainer _tabbedNavigationPage;
    Page _contactsPage, _quotesPage;
 
    public MasterTabbedNavigationService ()
    {   
        SetupTabbedPage ();
        CreateMenuPage ("Menu");
        RegisterNavigation ();
    }
 
    void SetupTabbedPage()
    {
        _tabbedNavigationPage = new FreshTabbedNavigationContainer ();
        _contactsPage = _tabbedNavigationPage.AddTab<ContactListPageModel> ("Contacts", "contacts.png");
        _quotesPage = _tabbedNavigationPage.AddTab<QuoteListPageModel> ("Quotes", "document.png");
        this.Detail = _tabbedNavigationPage;
    }
 
    protected void RegisterNavigation()
    {
        FreshIOC.Container.Register<IFreshNavigationService> (this);
    }
 
    protected void CreateMenuPage(string menuPageTitle)
    {
        var _menuPage = new ContentPage ();
        _menuPage.Title = menuPageTitle;
        var listView = new ListView();
 
        listView.ItemsSource = new string[] { "Contacts", "Quotes", "Modal Demo" };
 
        listView.ItemSelected += async (sender, args) =>
        {
 
            switch ((string)args.SelectedItem) {
            case "Contacts":
                _tabbedNavigationPage.CurrentPage = _contactsPage;
                break;
            case "Quotes":
                _tabbedNavigationPage.CurrentPage = _quotesPage;
                break;
            case "Modal Demo":
                var modalPage = FreshPageModelResolver.ResolvePageModel<ModalPageModel>();
                await PushPage(modalPage, null, true);
                break;
            default:
                break;
            }
 
            IsPresented = false;
        };
 
        _menuPage.Content = listView;
 
        Master = new NavigationPage(_menuPage) { Title = "Menu" };
    }
 
    public virtual async Task PushPage (Xamarin.Forms.Page page, FreshBasePageModel model, bool modal = false, bool animated = true)
    {
        if (modal)
            await Navigation.PushModalAsync (new NavigationPage(page), animated);
        else
            await ((NavigationPage)_tabbedNavigationPage.CurrentPage).PushAsync (page, animated); 
    }
 
    public virtual async Task PopPage (bool modal = false, bool animate = true)
    {
        if (modal)
            await Navigation.PopModalAsync ();
        else
            await ((NavigationPage)_tabbedNavigationPage.CurrentPage).PopAsync (); 
    }
 
    public virtual async Task PopToRoot (bool animate = true)
    {
        await ((NavigationPage)_tabbedNavigationPage.CurrentPage).PopToRootAsync (animate);
    }
}

The best part about all of these NavigationService’s is that you can swap them out and never have to change your PageModels.

I’ve uploaded a sample app to github here.

If you have any question please feel free to contact me. 

PS, if you find any parts that need improvements or you have a better options please email me, I’m always trying to improve this Framework and all feedback is welcome.

Thanks

Michael

 

The post Implementing custom navigation in FreshMvvm for Xamarin.Forms appeared first on Michael Ridland.

July 20, 2015 2:56 GMT

Same Day Xamarin Support for Visual Studio 2015

Today, Microsoft is unveiling the final release of Visual Studio 2015 in a global webcast, and we are joining the celebration! Visual Studio Logo Now Released to Market (RTM) for full use in production, Visual Studio 2015 includes many new features and improvements that make it easier to build apps quickly, including diagnostics, new C# 6 language features, and tighter integrations with TFS for streamlined DevOps.

We’re excited to announce same-day Xamarin support for Visual Studio 2015, including Visual Studio 2015 Community Edition, MSFT’s free IDE for non-enterprise apps. Xamarin and Visual Studio help you go mobile quickly, whether you’re building small projects, amazing consumer games, or employee-facing productivity apps. This combination of Xamarin and Visual Studio 2015 is our most integrated release ever – featuring a Visual Studio 2015 installation process that allows you to choose to install Xamarin with a single click, giving you everything you need to start building native cross-platform apps, all in C#.

Watch Storyboard in Visual Studio 2015

Be sure to check out the Visual Studio 2015 launch webcast today at 8:30am PDT, where MSFT product management teams will demonstrate Visual Studio 2015 product enhancements, including the latest from Xamarin.

It’s never been easier to start building iOS and Android apps — all from VS, all in C#. To learn more about developing native iOS and Android apps with Visual Studio and Xamarin, visit xamarin.com/visual-studio.

The post Same Day Xamarin Support for Visual Studio 2015 appeared first on Xamarin Blog.

July 20, 2015 12:00 GMT

Xamarin.Forms Typographic Scale

FontScaleIn my recent series on “5 Days to a Beautiful Xamarin.Forms User Interface” I wrote about fonts and font types. What I didn’t talk about was font sizes, or more importantly, typographic scales.

Typographic scales primary job is to limit you to a set number of font sizes and helps you keep your content density and reading comfort balanced. I know that sounds impressive, but in reality, it’s simple.

Too many type sizes and styles can turn a nice app into a train wreck in a hurry. As a developer and not a designer, I need all the help and structure I can get. As a former web developer, I like the scale because it reminds me of the H1 to H6 scales for headers in HTML.

The Typographic Scale

The styles that you see on the right are based on a typographic scale of 12, 14, 16, 20, and 34.

In my scale, I have a display #4 but it’s obscenely large and makes the screenshot look terrible. I would only use it to display a dates day number or something like that. Any text larger than 2 to 3 characters would take up the whole width of the screen.

The Code

Here is the helper class that you can use in your own styles. The class takes a light and dark text color to complete the scales styles. The class also uses a light, regular, and medium font. For the sample app, I used HelveticaNeue-Light, Helvetica and Helvetica-Medium on iOS and on Android, I used the Sans-Serif fonts.

public class LabelStyles
{

	private readonly Style display4, display3, display2, display, headline,
	title, subhead, body2, body, caption;

	public LabelStyles (Color firstColor, Color secondColor)
	{
		display4 = CreateStyle (firstColor, 76, StyleKit.LightFont);
		display3 = CreateStyle (firstColor, 50, StyleKit.RegularFont);
		display2 = CreateStyle (firstColor, 42, StyleKit.RegularFont);
		display = CreateStyle (firstColor, 30, StyleKit.RegularFont);
		headline = CreateStyle (secondColor, 20, StyleKit.RegularFont, LineBreakMode.WordWrap);
		title = CreateStyle (firstColor, 16, StyleKit.MediumFont);
		subhead = CreateStyle (secondColor, 14, StyleKit.RegularFont, LineBreakMode.WordWrap);
		body2 = CreateStyle (firstColor, 12, StyleKit.MediumFont, LineBreakMode.WordWrap);
		body = CreateStyle (firstColor, 12, StyleKit.RegularFont, LineBreakMode.WordWrap);
		caption = CreateStyle (secondColor, 9, StyleKit.RegularFont, LineBreakMode.WordWrap);
	}

	#region StyleProperties

	public Style Display4 {
		get {
			return display4;
		}
	}

	public Style Display3 {
		get {
			return display3;
		}
	}

	public Style Display2 {
		get {
			return display2;
		}
	}

	public Style Display {
		get {
			return display;
		}
	}

	public Style Headline {
		get {
			return headline;
		}
	}

	public Style Title {
		get {
			return title;
		}
	}

	public Style Subhead {
		get {
			return subhead;
		}
	}

	public Style Body2 {
		get {
			return body2;
		}
	}

	public Style Body {
		get {
			return body;
		}
	}

	public Style Caption {
		get {
			return caption;
		}
	}

	#endregion

	private Style CreateStyle (
			Color textColor, 
			double fontSize, 
			string fontFamily, 
			LineBreakMode breakmode = LineBreakMode.TailTruncation)
	{
		return new Style (typeof(Label))
			.Set (Label.TextColorProperty, textColor)
			.Set (Label.FontSizeProperty, fontSize)
			.Set (Label.FontFamilyProperty, fontFamily)
			.Set (Label.LineBreakModeProperty, breakmode);
	}
}

StyleKit

Here is the code from the StyleKit.cs for my sample app.

public static class StyleKit
{
	public static string LightFont = Device.OnPlatform ("HelveticaNeue-Light", "sans-serif-light", "");
	public static string RegularFont = Device.OnPlatform ("HelveticaNeue", "sans-serif", "");
	public static string MediumFont = Device.OnPlatform ("HelveticaNeue-Medium", "sans-serif-medium", "");

	public static LabelStyles DarkLableStyles = new LabelStyles (Color.Black, Color.Gray);
	public static LabelStyles LightLableStyles = new LabelStyles (Color.White, Color.Gray);
}

I hope you like the scale. I know I’ll be using it in every app. Changes to the scale will be made depending on the app, of course, but it’s a good place to start. Just like CSS and HTML, it’s nice to have a starting point for your Xamarin.Forms application.

The post Xamarin.Forms Typographic Scale appeared first on Syntax is my UI.

July 18, 2015 12:00 GMT

Bite-sized reusable MSBuild targets, properties and tasks

I’m a long-time MSBuild fan. Now that it’s open source, I’ve even played with bootstrapping it with xbuild to use it even on Mac. It works like a charm, for the most part :)

I’ve always wished I could just reuse fragments of MSBuild targets that are generic enough to fit in lots of projects. Things like determining whether we’re being built with XBuild or MSBuild, determining the location of Git, or the particular assembly location for a CodeTaskAssembly (which isn’t exactly trivial). Those kinds of things are probably a few lines of XML that could even be distributed via NuGet.

And so I started doing just that for my own stuff, and thus MSBuilder was born. It is sort of like NetFx but for MSBuild rather than .NET code. It may still suffer from that project’s Achilles heel though, namely, discoverability. But with any luck, the extremely low barrier of entry for contributors, plus the almost real-time pull-request building and subsequent nuget publishing, thanks to a paid super-responsive AppVeyor-based CI system, will make it useful enough to gain traction. Time will tell.

In the meantime, I’ve already added a few very useful MSBuilder blocks already:

Package Stats
MSBuilder.CodeTaskAssembly NuGet downloads Version
MSBuilder.DownloadFile NuGet downloads Version
MSBuilder.DumpItems NuGet downloads Version
MSBuilder.Git NuGet downloads Version
MSBuilder.Introspect NuGet downloads Version
MSBuilder.IsXBuild NuGet downloads Version
MSBuilder.NuGet.GetLatestVersion NuGet downloads Version
MSBuilder.RegexReplace NuGet downloads Version
MSBuilder.Run NuGet downloads Version
MSBuilder.TaskInliner NuGet downloads Version
MSBuilder.ThisAssembly.Project NuGet downloads Version

MSBuilder.DumpItems

One of my most frequently used ones is surely MSBuilder.DumpItems. Whenever I’m tweaking MSBuild targets, especially if they are the built-in ones in either MSBuild/CSharp itself, or WiX, I more often than not want to inspect what various item groups contain at certain points, as well as potentially useful item metadata I might want to use for my task at hand.

For example, say you want to do something interesting with project references that requires you to know precisely what’s going on in the built-in targets after project and assembly references are resolved. You can just create a console app, install the package

install-package MSBuilder.DumpItems

and edit the .csproj to dump items on AfterBuild for inspection of the items built by one of the many targets involving ResolveReferences, such as the _ResolvedProjectReferencePaths which looks kinda interesting:

<Target Name="AfterBuild">
  <DumpItems Items="@(_ResolvedProjectReferencePaths)" />
</Target>

And you get a full dump of all those items and their metadata, right in the Visual Studio output window, such as:

2>AfterBuild:
2>  Item: C:\Delete\ConsoleApplication13\src\ConsoleApplication1\ClassLibrary1\bin\Debug\ClassLibrary1.dll
2>      AccessedTime=2015-07-19 01:18:52.2170776
2>      BuildReference=true
2>      Configuration=Debug
2>      CreatedTime=2015-07-19 01:16:15.3999053
2>      DefiningProjectDirectory=C:\Program Files (x86)\MSBuild\12.0\bin\
2>      DefiningProjectExtension=.targets
2>      DefiningProjectFullPath=C:\Program Files (x86)\MSBuild\12.0\bin\Microsoft.Common.CurrentVersion.targets
2>      DefiningProjectName=Microsoft.Common.CurrentVersion
2>      Directory=Delete\ConsoleApplication13\src\ConsoleApplication1\ClassLibrary1\bin\Debug\
2>      Extension=.dll
2>      Filename=ClassLibrary1
2>      FullConfiguration=Debug|AnyCPU
2>      FullPath=C:\Delete\ConsoleApplication13\src\ConsoleApplication1\ClassLibrary1\bin\Debug\ClassLibrary1.dll
2>      Identity=C:\Delete\ConsoleApplication13\src\ConsoleApplication1\ClassLibrary1\bin\Debug\ClassLibrary1.dll
2>      ModifiedTime=2015-07-19 01:18:52.2070760
2>      MSBuildSourceProjectFile=C:\Delete\ConsoleApplication13\src\ConsoleApplication1\ClassLibrary1\ClassLibrary1.csproj
2>      MSBuildSourceTargetName=GetTargetPath
2>      Name=ClassLibrary1
2>      OriginalItemSpec=..\ClassLibrary1\ClassLibrary1.csproj
2>      OriginalProjectReferenceItemSpec=..\ClassLibrary1\ClassLibrary1.csproj
2>      OutputItemType=
2>      Platform=AnyCPU
2>      Project={e9288a56-aa1b-4127-97c5-7b3a6d487d63}
2>      RecursiveDir=
2>      ReferenceOutputAssembly=true
2>      ReferenceSourceTarget=ProjectReference
2>      RelativeDir=C:\Delete\ConsoleApplication13\src\ConsoleApplication1\ClassLibrary1\bin\Debug\
2>      RootDir=C:\
2>      SetConfiguration=Configuration=Debug
2>      SetPlatform=Platform=AnyCPU
2>      Targets=
2>
2>Build succeeded.

As I come across more useful bits of MSBuild that are generic enough that deserve becoming MSBuilder blocks, I’ll surely publish them, so stay tunned.

Enjoy!

July 18, 2015 12:00 GMT

How to access project reference metadata from WiX project in MSBuild

I’ve been doing quite a bit of WiX work lately. One thing that is very convenient in WiX is the ability to reference metadata about project references directly from your WiX files (i.e. fragments or includes). You could, for example, include a file from a project reference easily with:

<File Id="MyFile" Source="$(var.MyReference.TargetDir)\MyFile.dll" />

WiX has a task that automatically fetches metadata about project references and turns them into those vars you can use, which are then passed to the rest of the WiX compile process (candle, light, what-not). The resulting command-line for those tools end up looking something like:

candle.exe ... 
    -dMyReference.Configuration=Debug
    -d"MyReference.FullConfiguration=Debug|x86" 
    -dMyReference.Platform=x86 
    -dMyReference.ProjectExt=.csproj 
    -dMyReference.ProjectFileName=MyReference.csproj 
    -dMyReference.ProjectName=MyReference 
    -dMyReference.TargetDir=[FULL_PATH_HERE]\MyReference\bin\Debug\ 
    -dMyReference.TargetExt=.dll 
    -dMyReference.TargetFileName=MyReference.dll
    -dMyReference.TargetName=MyReference
    ...

If you’re doing some pre-processing of the project reference, including some of its output as compile contents or what-not, it would be very useful to access those values from MSBuild. This is one of those cases where you wish WiX’s MSBuild integration went a bit further, but fortunately it’s all just plain MSBuild in the end so we can do whatever we want to make it better. In this case, the target that adds those project reference vars is called AddCompilerDefineConstants and has a convenient AddCompilerDefineConstantsDependsOn property which we can extend as follows:

<PropertyGroup>
  <AddCompilerDefineConstantsDependsOn>
    $(AddCompilerDefineConstantsDependsOn);
    AddProjectReferenceMetadata
  </AddCompilerDefineConstantsDependsOn>
</PropertyGroup>

And the new AddProjectReferenceMetadata will create an item (“group” of just one item) named MyReference that I can then use as:

<ItemGroup>
    <Compile Include="%(MyReference.TargetDir)*.wxs" />
</ItemGroup>

That would bring in all the .wxs files that are in the output directory of the referenced project, for example.

Here’s the AddProjectReferenceMetadata target:

<Target Name="AddProjectReferenceMetadata">
  <!-- Fist invoke the built-in task, but retrieve the outputs as items
         rather than a single property, which is what the built-in targets do -->
  <CreateProjectReferenceDefineConstants
    ProjectReferencePaths="@(_ResolvedProjectReferencePaths)"
    ProjectConfigurations="$(VSProjectConfigurations)">
    <Output TaskParameter="DefineConstants" ItemName="_ProjectReferenceConstants" />
  </CreateProjectReferenceDefineConstants>

  <ItemGroup>
    <!-- Via a cascading item metadata process, we determine the index of the first '.' in the project constants 
         retrieved by the task, since we want to use that as the grouping 'ReferenceName' item name instead. -->
    <_ProjectReferenceConstants>
      <!-- Note how we create a new string with static method syntax, to be able to use property function syntax with item metadata -->
      <ReferenceName>$([System.String]::new('%(Identity)').Substring(0, $([System.String]::new('%(Identity)').IndexOf('.'))))</ReferenceName>
      <ReferenceStart>$([System.String]::new('%(Identity)').IndexOf('.'))</ReferenceStart>
    </_ProjectReferenceConstants>
    <_ProjectReferenceConstants>
      <!-- The we actually need to add 1 to the index of the dot for the substring. 
           For better readability, we do it in two steps, saving the value above, and then calling the built-in Add function here, which 
           updates the metadata value. -->
      <ReferenceStart>$([MSBuild]::Add(%(ReferenceStart), 1))</ReferenceStart>
    </_ProjectReferenceConstants>

    <!-- Here we change the item name on purpose, to drop all the items that have the
         reference name prefix intentionally. Note that since we're creating a new item
         group, we need to reference the original ones by their full item.metadata name. -->
    <ProjectReferenceMetadata Include="@(_ProjectReferenceConstants -> '$([System.String]::new('%(_ProjectReferenceConstants.Identity)').Substring(%(_ProjectReferenceConstants.ReferenceStart)))')">
      <ReferenceName>%(_ProjectReferenceConstants.ReferenceName)</ReferenceName>
    </ProjectReferenceMetadata>
  </ItemGroup>

  <!-- Finally, create a new item group with the name of the reference, which leverages task batching and automatically 
       groups the ProjectReferenceMetadata group by their reference name -->
  <CreateItem Include="%(ProjectReferenceMetadata.ReferenceName)" AdditionalMetadata="@(ProjectReferenceMetadata)">
    <Output TaskParameter="Include" ItemName="%(ProjectReferenceMetadata.ReferenceName)"/>
  </CreateItem>
</Target>
July 17, 2015 6:23 GMT

Can’t Miss Community Content

Xamarin developers not only build amazing iOS and Android apps in C#, but love contributing to the Xamarin community through blog posts, components, plugins, and podcasts. The links below will take you to some of favorites over the past few weeks:

Podcasts

    Xamarin Podcast Special Edition: Google IO

    Explore mobile backend options with the Xamarin Podcast.

  • Xamarin Podcast — Exploring Backend Options: Mike James and Pierce Boggan discuss mobile backend options for Xamarin developers, including Oracle MCS, Microsoft Azure, and Facebook’s Parse.
  • Gone Mobile — Automated App Testing with eBay’s Niels Frydenholm: eBay’s Niels Frydenholm joins Greg Shackles and Jon Dick to discuss automatic app testing.

Great Blog Posts

Xamarin.Forms

Add bindable maps with the Maps behavior from Jonathan Yates.

Adam Wolf’s card UI using Xamarin.Forms.

Thanks to these developers for sharing their Xamarin knowledge with the rest of the developer community. If you have an article or blog post related to Xamarin development that you would like to share, please let us know by tweeting @XamarinHQ and it may be featured in an upcoming community content roundup.

The post Can’t Miss Community Content appeared first on Xamarin Blog.

July 17, 2015 1:30 GMT

WeeklyXamarin Newsletter Issue #49

Save the Date for Xamarin Evolve 2016
Joseph Hill, from Xamarin Inc. announced today that the Evolve Conference is back in April 2016.

Xamarin.Forms in Anger – Cards
I (adam) use my epiphany fries to make a card UI with Xamarin.Forms.

Beautiful Material Design with the Android Support Design Library
James Montemagno, from Xamarin Inc., helps smooth the road to Google Material Design.

Why Can’t We Be Friends? Conflict Resolution in Azure Mobile Services
Matthew Soucoup, from Codemill Technologies, gets into conflict resolution mode between Azure and his mobile app.

Explore Backend Options with the Xamarin Podcast
Mike James, from Xamarin Inc., puts up another podcast. This time it’s all about the backend.

TaskCompletionSource + Xamarin = Beautiful Async
Michael Ridland adds another tool to the Xamarin developers toolbox.

Xinions – Xamarin.Forms style minions that do the dirty work for you
I (adam) make some Minions to do my dirty work for me.

Share Even More Code with Plugins for Xamarin
Pierce Boggan, from Xamarin Inc., shows off some reusable plugins for Xamarin.Forms.

A Comprehensive Guide to Creating a Xamarin.Forms App with MvvmCross (Part 4 of 5)
Brent Edwards, from Magenic, adds another post to his 5 part series covering MvvmCross.

Custom Interactions with the Design Support Library
Jérémie Laval bridges the gap between Material Design theory and reality.

Novarum DX Transforms Global Health Initiatives with Xamarin
Jo Ann Buckner, from Xamarin Inc., shows off a customer success with using Xamarin.

Continuous delivery for Xamarin.iOS projects with TeamCity, FAKE and HockeyApp
Juan Antonio Cano gets his ducks in a row with continuos delivery.

 

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 WeeklyXamarin Newsletter Issue #49 appeared first on Syntax is my UI.

July 16, 2015 8:27 GMT

Why Can’t We Be Friends? Conflict Resolution in Azure Mobile Services

The story is always the same… we develop this brand new app, introduce it to Azure, and they get along like gangbusters… constantly sending data back and forth. Then they have a little squabble, the lights go out and the internet is down, but Azure & the app survive with some offline data sync’ing.

But then it happens… a major conflict rears its ugly head testing the friendship between our app and Azure! Well, we’re not going to let a little road bump ruin a good thing! We’re going to show these two a little Conflict Resolution!

What Kind of Conflicts Can Occur?

It’s a rough world out there, lots of different ways to have a misunderstanding and get into a conflict, especially when our app can travel all over the place, go offline and then sync data back up later… so let’s walk through some of the scenarios that lead to conflicts so we can help our app and Azure before their spat turns into an all out fight!

While offline, a user updates a record and saves it locally. Upon regaining network access, the app pushes the changed record to Azure, only to find out the record has already been changed by some one else!

Pow!

Bang
A user deletes a record, while offline of course (why does it seem that bad things always happen offline?). When the app tries to push the delete to Azure, again somebody has already updated it! What’s going to happen here?!?

While online (whoa, something bad happened while connected?) the app submits a record which conflicts with a constraint setup in the backing database. Oh no! Not another reason to argue!

Boom!

And there are many, many more different ways conflicts can arise. I also already know what you’re thinking … wow, this is really going to be a pain to write all the code to detect the various conflicts that arise, much less handle them all.

The good news is that we can handle them all – and the even better news is that a lot of the time we don’t even need to detect them on our own!

In the next sections we’ll cover how Azure automatically detects conflicts. We’ll talk about how to handle these conflicts in our Xamarin Forms (or classic Xamarin) apps when using a regular, always-on Azure connection, as well as the offline sync connection. We’ll also talk about some design considerations of where the conflict exception handling should take place.

Azure Auto-Conflict Detection

Azure provides automatic conflict detection in cases where a record within the backing Azure data store has been modified in some way (including being deleted) before the modified record from our app is received.

Going back the Cheesed app that we’re slowing building along with these Azure series of posts, an example would be if somebody updated the address of a dairy while offline, but found that particular dairy was already updated when the offline data was pushed.

The Azure Mobile Services component will throw an exception when this happens.

The way Azure accomplishes this is called Optimistic Concurrency Control. Essentially what that means is Azure assumes every transaction it receives can be committed, so it does not lock any record at any time. Rather, it updates and changes the _version column upon every write operation. (The _version column is more or less a timestamp column).

If the _version column of the incoming record does not match that of what is stored on the server, Azure determines the incoming record is in conflict with what is on the server and returns an HTTP error – which renders itself as an exception within the Azure Mobile Services component in our app.

So what do we need to do in order to enable Optimistic Concurrency Control within Azure and our app? We just need to make sure our model class has the _version column mapped … that’s it – everything else will be taken care of for us!

public class Dairy
{
    public string Id {
        get;
        set;
    }

    [JsonProperty("address")]
    public string Address {
        get;
        set;
    }

    [JsonProperty("dairyname")]
    public string DairyName {
        get;
        set;
    }

    [JsonProperty("affineur")]
    public string CheeseMaker {
        get;
        set;
    }

    // Being explicit that this is our version column
    [Microsoft.WindowsAzure.MobileServices.Version]
    public byte[] Version {
        get;
        set;
    }
}

To handle any conflicts that come back we need to handle one of two exceptions, depending on whether we’re using offline sync or just pushing to Azure without offline capabilities.

  • MobileServicePushFailedException
    needs to be handled when the app is performing pushes during offline syncs AND a custom
    IMobileServiceSyncHandler
    is NOT implemented on the SyncContext (more on this below).
  • MobileServicePreconditionFailedException
    needs to be handled when the app is not offline enabled or when a custom
    IMobileServiceSyncHandler
    is implemented on the SyncContext.

Handling The Conflict In The App

OK … Azure has done its part and told the app that there’s a problem. But conflict resolution is a two way street, and we’re going to have to handle the conflict within the app in order to resolve this.

What To Do When a Conflict Is Detected?

That’s the million dollar question isn’t it? There are multiple things that can be done, and they’re all dictated by the business rules of your application.

For example…

  • Last update always wins.
  • Give the user a screen & have them select either the local version or the server version to win.
  • Have the user perform a merge, picking and choosing fields from each version and creating a new hybrid record to update.
  • Just cancel the modification altogether.
  • Don’t handle the exception and let the app crash. Err … wait, that’s not really acceptable!

Regardless of how the business rules dictate the resolution to the conflict, you first have to handle the conflict exception efficiently within the app, invoke the resolution mechanism, then try the push operation again.

Handling Push Conflicts

Here we’re talking about pushing data to Azure without offline sync services being involved. We’ll have to handle the conflict inline with the code when we invoke the push up to Azure.

Azure Mobile Services will throw the

MobileServicePreconditionFailedException
when the _version column of the incoming record does not match what is on the server. Here’s a simple implementation of catching, handling and resolving this conflict:

private async Task UpdateDairy (Dairy updatedDairy)
{
    MobileServicePreconditionFailedException<Dairy> preconditionFailure = null;

    try {
        var onlineDairyTable = App.MobileService.GetTable<Dairy> ();

        await onlineDairyTable.UpdateAsync (updatedDairy);

    } catch (MobileServicePreconditionFailedException<Dairy> ex) {
        preconditionFailure = ex;
    }

    // Oh no - a conflict!
    if (preconditionFailure != null) {
        // Note that the "Item" property is a copy of the dairy row from the server that's trying to be updated
        await ResolveConflict (updatedDairy, preconditionFailure.Item); 
    }
}

private async Task ResolveConflict (Dairy localVersionOfDairy, Dairy azuresVersionOfDairy)
{
    // Here we're just deciding to use our app's version of the dairy by 
    // giving it the same _version column value of what is in the server - (last in wins)
    localVersionOfDairy.Version = azuresVersionOfDairy.Version;

    await UpdateDairy (localVersionOfDairy);
}

There is a property in

MobileServicePreconditionFailedException
called
Item
which has the server’s version of the record that is trying to be updated. By using that along with the local copy, we should be able to resolve the conflict in whatever way our business rules dictate. (In the example above, the last update always wins).

The one thing to make sure you do is set the _version column in the “resolved” object that will be pushed to Azure to be the same as what the server’s copy is. That way Azure will not mark it as a conflict again (unless another update happened during our resolution!)

Handling Offline Sync Push Conflicts – Inline

While you can handle conflicts that arise from sync’ing data from an offline data store inline as illustrated above, it comes with several downsides, and I would say it’s, in general, not the greatest idea.

To get a handle on why – just think about how pushing works in Azure – all of the pending changes go at once. That means the error(s), and there could be more than one, come back at once. Kind of a pain to implement a handler, because most likely you’re going to have more than one place where Pushes, Pulls and Purges happen from.

If you insist to handle them inline from a Push, Pull or Purge operation on your SyncContext, you can catch the

MobileServicePushFailedException
.

So … instead of handling all of the conflicts sent by the offline sync context at once, in a big jumbled mess, wouldn’t it be better if we could handle them one by one, in single spot, as they get returned by Azure?

Handling Offline Sync Push Conflicts – Centralized

Alright, now that we’re convinced that catching possible conflicts after each time we invoke a Push, Pull or Purge operation in our code isn’t the greatest idea in the world, where would a good place be?

If you remember back to the previous post on offline editing and syncing, when we setup our SyncContext, we have to pass it an implementation of the

IMobileServiceLocalStore
– or something to hold the data locally. And optionally we can also pass it an implementation of
IMobileServiceSyncHandler
.

That interface allows us to define 2 functions, one to “intercept” the outgoing requests

ExecuteTableOperationAsync
to Azure and the other handle the reply from Azure
OnPushCompleteAsync
.

The first instinct would be to handle the conflict errors in the

OnPushCompleteAsync
function – but that’s only invoked after all of the push operations are finished – thus all of the conflicts that occur will be included. So we’re not much better off than we were in the inline exception handling.

Rather, we want to check for conflicts in the

ExecuteTableOperationAsync
function. This function will get invoked for each and every pending table operation queued up in local data store.

A very simple implementation of this function may look like this:

public async Task<JObject> ExecuteTableOperationAsync (IMobileServiceTableOperation operation)
{
    JObject result = null;
    MobileServicePreconditionFailedException<Dairy> dairyConflict = null;
    MobileServicePreconditionFailedException<Cheese> cheeseConflict = null;

    try {               
        operation.AbortPush();
        result = await operation.ExecuteAsync ();           
    } catch (MobileServicePreconditionFailedException<Dairy> ex) {
        // Azure's version of the Dairy - Strongly typed
        var serverDairyItem = ex.Item;

        // App's version of the Dairy - in conflict with what is in Azure
        var localDairyItem = operation.Item.ToObject<Dairy> ();


        // Do something to handle the dairy conflict

    } catch (MobileServicePreconditionFailedException<Cheese> ex) {
        // Azure's version of the Cheese - strongly typed
        var serverCheeseItem = ex.Item;

        // App's version of the Cheese - in conflict with what is in Azure
        var localCheeseItem = operation.Item.ToObject<Cheese>();

        // Do something to handle the cheese conflict
    }

    return result;
}

It’s also within this function that we can decide to cancel the table operation for some reason by invoking the

AbortPush()
function on the
IMobileServiceTableOperation
variable being passed in.

One thing worth noting here is that invoking

AbortPush()
will not remove the pending operation from the overall queue, it will just remove it from the current push. You can make any changes to that record you’d like, and that updated record will be in the next push.

To totally remove a record from the pending operations, you need to invoke one of the various overloads for

PurgeAsync()
on the sync context table and pass
true
in for the “force” parameter. That will remove the record without invoking a push.

Summary

Like just about all conflicts in life, Azure conflict resolution really just comes down to communication. And we can help with the communication by the following:

  • First Azure needs to have its Optimistic Concurrency Control turned on by having our model objects implement the _version column.
  • Then we need to efficiently and properly handle the conflict exception when Azure throws one.
  • Finally, we need to implement some business logic which resolves the conflict and eventually retry the Azure data operation.
All seems pretty easy when we put it that way… makes you wonder why Azure & our app got in a fight in the first place?
Best Friends!
July 16, 2015 3:31 GMT

Save the Date for Xamarin Evolve 2016

Mark your calendars for Xamarin Evolve 2016, taking place April 24-28 in Orlando, Florida! Join the Xamarin team and fellow developers for the largest cross-platform mobile development event in the world.

Xamarin Evolve 2016

Last year, Xamarin Evolve hosted a sell-out crowd of over 1,200 attendees. Speakers from leading companies including Microsoft, Dropbox, Github, Google, Accenture, and IBM led over 90 conference and training sessions covering everything from the Xamarin platform and the latest in iOS and Android development, to the future of C#, mobile security, and cross-platform best practices. Xamarin Evolve attendees were also the first to know about groundbreaking new Xamarin products and capabilities for mobile development.

These are the top five things that Xamarin Evolve attendees told us that they left the conference with:

  • Deeper mobile technical knowledge and skills
  • The ability to go faster with their mobile projects
  • Greater confidence in the success of their mobile strategy
  • Amazing new connections
  • An unforgettable experience

Photos from Xamarin Evolve 2014

Xamarin Evolve 2016 is going to be even more unforgettable! With so much happening in mobile development, and an even bigger venue, you’re going to want to take part in everything Xamarin Evolve has to offer.

Sign up below to be notified when tickets go on sale!

Sign up

 

The post Save the Date for Xamarin Evolve 2016 appeared first on Xamarin Blog.

July 16, 2015 12:00 GMT

Xamarin.Forms in Anger – Cards

Screen Shot 2015-07-15 at 12.08.48 PM

The #1 request I get for the Xamarin.Forms in Anger is for a Google or Facebook like card view. Today is the day that I fulfill those requests.

To be completely honest, I’ve been thinking about how to do a card view for a while and let me tell you, it’s not easy. Especially when you try to stick with the “in the box” components of Xamarin.Forms. My first attempt at it was hideous.

Hideous Forms

Hideous would be the most polite way of saying it was crap. I started off using BoxViews to draw the lines and contain the whole thing in a Xamarin.Forms Grid. Ouch, yes hideous.

The Grid was becoming a nightmare with all the extra rows and columns needed for lines. What I wouldn’t do for some HTML Tables with a borders = 1 in Xamarin.Forms. I thought of putting in a feature request to the team, but didn’t. I don’t want them to laugh at me.

Waffle Fries to the Rescue

With the BoxViews not working out, I went to lunch to clear my head and to think. I love lunch and I don’t miss a meal. That day, I decided to go to Chick Fil A and get a chicken sandwich with a side of epiphany fries.

There I was, eating my chicken and dunking my fries in ketchup (Sauce de American). When I dipped a waffle fry into the ketchup, the ketchup squeezed through the holes and made a red checkerboard on top of the fry. Then it hit me. Bam!

I was going about the card UI backwards or forwards. Either way, it was the wrong way. I had to do an about face and approach it in another way. The way the ketchup came up through the fry not by putting ketchup onto the fry.

A Grid of Lines

As soon as I got home, I worked up a Xamarin.Forms Grid with some padding, row and column spacing. In addition to those settings, I also set the background color of the grid to a medium dark grey. Then added ContentViews with white backgrounds into each cell of the Grid. This is what it looked like when I finished.

GridLines

The white panels acted like the ketchup on my waffle fries and the borders are the potato. Yes, I know, it’s strange to describe Xamarin.Forms design techniques using food, but stay with me; it gets better. Now that I knew the technique worked and was a heck of a lot less messy, I pushed on.

Content View Panels

Each CardView is made up of 5 ContentViews with a background color set to the designed color. Here are some of the background colors for each panel.

Panels

The CardView.cs file would have been gigantic if I kept all the code in the same file so I broke it up into different ContentViews. Here are the names for each ContentView that makes up the CardView.

CardViews

The CardDetailsView has a column span of three to horizontally bridge the two IconLableViews and the ConfigIconView. The CardStatusView has a row span of two to complete the vertical lefthand status bar.

The CardView Code

For the demo, I put a couple of CardViews in a vertical StackLayout. If I had a lot of cards, I would prefer to use a ListView. Hopefully a reader will let me know how well this design works in a ListView. It should be ok, especially while using the Grid and not a bunch of nested StackLayouts. I’ve learned my lesson.

public class CardView : ContentView
{
	public CardView (Card card)
	{
		Grid grid = new Grid {
			Padding = new Thickness (0, 1, 1, 1),
			RowSpacing = 1,
			ColumnSpacing = 1,		
			BackgroundColor = StyleKit.CardBorderColor,
			VerticalOptions = LayoutOptions.FillAndExpand,
			RowDefinitions = {
				new RowDefinition { Height = new GridLength (70, GridUnitType.Absolute) },
				new RowDefinition { Height = new GridLength (30, GridUnitType.Absolute) }
			},
			ColumnDefinitions = {
				new ColumnDefinition { Width = new GridLength (4, GridUnitType.Absolute) },
				new ColumnDefinition { Width = new GridLength (1, GridUnitType.Star) },
				new ColumnDefinition { Width = new GridLength (100, GridUnitType.Absolute) },
				new ColumnDefinition { Width = new GridLength (50, GridUnitType.Absolute) }
			}
		};

		grid.Children.Add (
			new CardStatusView (card)
		, 0, 1, 0, 2);

		grid.Children.Add (new CardDetailsView (card), 1, 4, 0, 1);

		grid.Children.Add (
			new IconLabelView (
				card.StatusMessageFileSource,
				card.StatusMessage
			)
		, 1, 1);

		grid.Children.Add (
			new IconLabelView (
				card.ActionMessageFileSource,
				card.ActionMessage
			)
		, 2, 1);

		grid.Children.Add (new ConfigIconView (), 3, 1);

		Content = grid;
	}
}

With all the refactoring; the CardView looks small and plain but the devil is in the ContentViews.

Solution

The code for this sample is up on GitHub in the “In Anger” repository. For this post, I broke the code out into a separate directory and solution to make it easier for you to reuse the CardView without getting confused with all the other code and resources from other posts.

Moar Epiphany Fires

Who knew that a humble waffle fry would be the answer to the Xamarin.Forms CardView? Not me; I go for the chicken. Don’t you worry dear read, I will continue to go to “Chick Fil a” to get more Xamarin.Forms design inspiration in the future. Stay tuned to this blog and, if you have a design challenge, just put it in the comments below or email me at adam [at] adamjwolf dot com.

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

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

July 15, 2015 6:37 GMT

Share Even More Code with Plugins for Xamarin

One of my top priorities for Moments, a Snapchat clone built with Xamarin.Forms and Microsoft Azure, was to maximize the amount of code shared between my target platforms. I was already achieving a significant amount of shared code with Xamarin.Forms, but I noticed that many things, such as checking for device connectivity or showing a dialog, had to be done on a per-platform basis. Plugins for Xamarin helped fill in those gaps and allowed me to share even more code.

Plugins for Xamarin NuGet Icon

A Plugin for Xamarin is a special kind of NuGet that adds cross-platform functionality or abstracts platform-specific functionality to a common API. These are extremely lightweight and completely cross-platform, so they can be accessed via a Portable Class Library (PCL) or Shared Project. Below, I’ve shared a few of my favorite Plugins for Xamarin that I used to build Moments.

Connectivity

In today’s world, it’s vital that apps maintain connectivity when interacting with web services and other network-dependent logic. With the Connectivity Plugin for Xamarin and Windows, it’s never been easier to check the connection status of a mobile device, gather connection types and bandwidths, and more.

Testing network connectivity from shared code is literally as easy as writing one line of code:

var connected = CrossConnectivity.Current.IsConnected;

The Connectivity Plugin for Xamarin and Windows can also test the reachability of specific hosts using the IsReachable and IsRemoteReachable methods. Finally, you can subscribe to the ConnectivityChanged event to ensure that your app always knows if the device is connected to the internet:

CrossConnectivity.Current.ConnectivityChanged += (sender, args) =>
{
    // Connectivity changed! Check args.IsConnected!
};

Settings

Another common use case among mobile apps is the ability to store user settings. Each platform exposes its own way of storing settings, such as NSUserDefaults on iOS and SharedPreferences on Android. The Settings Plugin for Xamarin and Windows takes the ability to create and access settings cross-platform!

Rather than dealing with the various platform-specific implementations, the Settings Plugin for Xamarin and Windows makes it easy to implement user settings, as seen below:

public class Settings
{
    public bool NotificationsEnabled
    {
        get { CrossSettings.Current.GetValueOrDefault<bool> ("notificationsEnabled"); }
        set { CrossSettings.Current.AddOrUpdateValue<bool> ("notificationsEnabled", value); }
    }
}

Not only is the Settings Plugin for Xamarin and Windows great for managing settings from shared code, but it can also act as a simple cross-platform key-value store with support for many different data types, such as strings, integers, doubles, booleans, DateTimes, and more!

Dialogs

From alert popups to loading spinners, dialogs are a staple of mobile app development. The User Dialogs Plugin for Xamarin and Windows allows you to show almost any type of dialog you can think of from shared code, including loading spinners, alerts, confirmations, and error dialogs.

Loading Indicators
For performing potentially lengthy tasks, such as logging in a user, use the ShowLoading method:

UserDialogs.Instance.ShowLoading ("Loading");

When the task ends, you can hide the dialog using the following method call:

UserDialogs.Instance.HideLoading ();

Success & Failure
If a dialog needs to reflect success or failure, such as the the result of a user log in, you can use the success and failure APIs available within the User Dialogs Plugin for Xamarin and Windows:

// Success
UserDialogs.Instance.ShowSuccess ("Success");
// Failure
UserDialogs.Instance.ShowError ("Error");

Download a Plugin for Xamarin Today

All of the Plugins for Xamarin listed above helped me significantly increase productivity by achieving over 87% shared code in Moments. Check out Plugins for Xamarin on GitHub to find a plugin for your next project, or find out how easy it is to build your own Plugin for Xamarin.

The post Share Even More Code with Plugins for Xamarin appeared first on Xamarin Blog.

July 15, 2015 11:52 GMT

TaskCompletionSource + Xamarin = Beautiful Async

If you’ve been using Xamarin for a while you probably already know of this functionality.

Just in case you haven’t I just want to give shout out to the TaskCompletionSource class. In short the completion source allows you to create a Task and return it to the caller without having to set the result or use an lambda.

It’s great for working with event based API’s like Native Bluetooth, NSSession and Native mapping engines. All of which provide results via events. The Native Bluetooth API in iOS is a great example of this, so let’s take a look.

TaskCompletionSource and Native API Sample

The function we want to build is below, it returns an awaitable task of float which is the Bluetooth Signal strength.

1
2
3
4
5
/// <summary>
/// Gets the Signal strength of Bluetooth Device
/// </summary>
/// <returns>The signal strength.</returns>
public Task<float> GetSignalStrength ()
The problem is that the Bluetooth API is based on events, so there’s no real easy way to support this Async. That’s where TaskCompletionSource comes in.
Let’s start by creating our TCS and returning the Task.
1
2
3
4
5
6
7
8
public Task<float> GetSignalStrength ()
{
    var bluetoothCompletion = new TaskCompletionSource<float> ();
 
    //do bluetooth work
 
    return bluetoothCompletion.Task; 
}

Now that we have the TaskCompletionSource there’s a few things we can set:

1
2
3
bluetoothCompletion.SetCanceled (); //Set the task as Canceled 
bluetoothCompletion.SetResult (888); //Sets the result as successful
bluetoothCompletion.SetException (new Exception ()); //Sets an exception

Great the caller has a Task that they can await. Now let’s do the Bluetooth work.

1
2
3
4
5
6
7
8
9
var centralManager = new CBCentralManager(DispatchQueue.CurrentQueue);
 
centralManager.DiscoveredPeripheral += (object sender, CBDiscoveredPeripheralEventArgs e) => {
    bluetoothCompletion.SetResult(e.RSSI.FloatValue);
  };
 
centralManager.FailedToConnectPeripheral += (object sender, CBPeripheralErrorEventArgs e) => {
    bluetoothCompletion.TrySetException(new Exception("Failed to connect to device"));
  };

Now let’s put them all together.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/// <summary>
/// Gets the Signal strength of Bluetooth Device
/// </summary>
/// <returns>The signal strength.</returns>
public Task<float> GetSignalStrength ()
{
    var bluetoothCompletion = new TaskCompletionSource<float> ();
 
    var centralManager = new CBCentralManager(DispatchQueue.CurrentQueue);
 
    centralManager.DiscoveredPeripheral += (object sender, CBDiscoveredPeripheralEventArgs e) => {
        bluetoothCompletion.SetResult(e.RSSI.FloatValue);
    };
 
    centralManager.FailedToConnectPeripheral += (object sender, CBPeripheralErrorEventArgs e) => {
        bluetoothCompletion.TrySetException(new Exception("Failed to connect to device"));
    };
 
    return bluetoothCompletion.Task;
}

Great, so now the caller can easily consumer this API in a async way.

1
var bluetoothStrength = await bluetoothService.GetSignalStrength();

This was a very simple example but the TaskCompletionSource can be used in many scenarios, it can be passed into functions and kept as member variables until you need it. So if it’s not already in your Toolkit, add it and use it, your code will be cleaner.

If you want to know more feel free to drop me a email.

Thanks

Michael

The post TaskCompletionSource + Xamarin = Beautiful Async appeared first on Michael Ridland.

July 14, 2015 6:47 GMT

Novarum DX Transforms Global Health Initiatives with Xamarin

Novarum DX logoLateral flow tests indicate the presence of specific substances in a fluid by showing one or more lines on a testing substrate. Familiar to many people in one of their simplest forms as home pregnancy tests, as the tests become more sophisticated and complex, reading them accurately becomes more challenging and time-consuming. Today, there are thousands of these tests on the market for a variety of applications, from enabling physicians to monitor the health of HIV/AIDS patients and detecting harmful chemicals in water supplies, to providing near-instant tests for deadly diseases such as Ebola.

While the tests provide a high degree of portability and rapid results for field and point-of-care use, interpreting them often requires laboratory expertise. Novarum DX, based in Edinburgh, Scotland, aims to change that and unlock the full potential of lateral flow tests. “We started Novarum DX three years ago based on the idea that we could make the reading of lateral flow tests easy by using smartphones and their built-in cameras,” says Neil Polwart, Managing Director at Novarum DX. The Novarum Reader can provide pass/fail test results as well as quantitative outputs, providing foolproof performance for virtually any user with minimal training.

Novarum DX app on iPhon 6When Novarum DX first started developing their technology, they looked at the full breadth of cross-platform development tools with a focus on minimizing UI development. They soon realized, however, that the most important thing for the Novarum Reader was native access to the camera, native computational performance, and the ability to reuse business logic. “In other write-once-run-anywhere solutions, you don’t get powerful enough access to the device hardware, nor do you get native performance. We’re doing computationally expensive image processing, so we need the native performance Xamarin provides,” Polwart explains.
 
Xamarin has streamlined the development process for Novarum DX. “We’ve used Xamarin from the beginning. Using native development, we’d have to have two separate teams, so essentially Xamarin enables us to use half the resources we would otherwise,” says Polwart. “We aim for 80% code reuse between platforms.”

The Novarum DX team has grown from two team members to eleven in just three years, including five mobile developers who work across Android, iOS, and Windows Phone. “Since that first app, we’ve undertaken about 20 different projects for a variety of customers, including medical device companies with strict quality and regulatory requirements. We’ve developed a platform approach based on Xamarin that allows us to speed up development for our customers. For a basic app, we expect to be able to build something in four to six weeks, and we’ve generated about 1.5 million US dollars in revenue with Xamarin as our platform.” reports Polwart.
 

View the Case Study
 

The post Novarum DX Transforms Global Health Initiatives with Xamarin appeared first on Xamarin Blog.

July 13, 2015 12:00 GMT

Xinions – Xamarin.Forms style minions that do the dirty work for you.

XinionsThis weekend, besides seeing a movie, I played around with creating a library that makes styling a Xamarin.Forms app less painful.

The goal of the library was to come as close to CSS as I could without loosing type checking, style composability and simplicity. After about 45 minutes and a lot of generics later I gave up.

Yep, I threw in the towel. Generics was not the answer. C# Extension methods were and the Xinions.cs file was born. Long live the Xinions!

Creating a Style

Here is how you create and use a Xamarin.Forms style. This example code comes straight from the Xamarin.Forms documentation.

var buttonStyle = new Style (typeof(Button)) {
    Setters = {
        new Setter {Property = Button.BackgroundColorProperty, Value = Color.Yellow},
        new Setter {Property = Button.BorderRadiusProperty, Value = 0},
        new Setter {Property = Button.HeightRequestProperty, Value = 42}
    }
}
// apply directly to a single control
var mybutton = new Button {
    Text = "Style Me",
    Style = buttonStyle
};

That code is not exactly a stick in the eye, but writing it over and over again is painful, especially when creating styles for your whole app. See, I like to create a StyleKit.cs static class that holds all the styles for my Xamarin.Forms application. I got the idea from the smart peeps at PaintCode. If you’re making Xamarin.iOS apps, I suggest you take a look at their website and tools.

Xinions in Action

Let’s create the same style but this time we’ll use our Xinion extension methods.

var myStyle = new Style (typeof(Button))
	.Set (Button.BorderColorProperty, Color.Yellow)
	.Set (Button.BorderRadiusProperty, 0)
	.Set (Button.HeightRequestProperty, 42);

// apply directly to a single control
var mybutton = new Button {
	Text = "Style Me",
	Style = myStyle
};

As you can see, it’s a little shorter and more compact. It’s not exactly CSS but it’s closer than the original. The extension methods use the Builder pattern to allow method chaining just like Linq in the .Net framework.

Style Building

With the Xinions, you can create new styles from existing styles in two ways. The first way is to “Extend” the original style to a new variable and then alter it with the “Set” methods. The second way is to base a new style on an existing style and then use the “Set” methods.

var firstStyle = new Style (typeof(Button))
	.Set (Button.BorderColorProperty, Color.Yellow)
	.Set (Button.BorderRadiusProperty, 0)
	.Set (Button.HeightRequestProperty, 42);

var derivedStyle = firstStyle.Extend ().Set (Button.BackgroundColorProperty, Color.Red);

var secondStyle = new Style (typeof(Button)) {
	BasedOn = firstStyle,
};
secondStyle.Set (Button.BackgroundColorProperty, Color.Red);

I’m not sure if I like the method name clone. For the sake of this blog post I’ll keep it that way. David B posted a comment and suggested “Extend” as a better method name and I agree. David also pointed out that Clone would indicate a completely new style but its not. If you updated the base style, your style will be updated as well. That could have been a bit surprising and confusing. Thanks David B.

Meet the Xinions

Now that we’ve seen what they can do, let’s get our first look at the Xinions.

public static class Xinions
{
	public static Style Extend (this Style _style)
	{
		var newStyle = new Style (_style.TargetType) {
			BasedOn = _style
		}; 
		return newStyle;
	}

	public static Style Set<T> (this Style _style, BindableProperty property, T value)
	{
		_style.Setters.Add (new Setter () { Property = property, Value = value });
		return _style;
	}
}

I know what you’re thinking and it goes something like this:

I thought you said Generics didn’t work? Despicable!

That’s it! That can’t be the whole library. It’s so small and cute.

With a little bit of Generics trickery, I was able to handle almost every case of styling with just a single method. Don’t take my word for it, try it out yourself and tell me how it went. Especially if you’re missing something.

With this single file, you will have an easier time writing Xamarin.Forms style. For now, I am going to use the Xinions to style a few applications and see how well they do. If I survive, then I’ll write another blog post on how well or badly it went. Till next time, I’ll see you later.

The post Xinions – Xamarin.Forms style minions that do the dirty work for you. appeared first on Syntax is my UI.

July 12, 2015 10:32 GMT

Custom Interactions with the Design Support Library

During this year Google I/O, a new entry in the support library family was added in the form of support-design.

The goal of this new library is to brige the gap between the theory of the Material Design specification and having actual available code to implement it.

The new library sits on top of the existing support-v7-appcompat package (which provides the base Material theming ability) and offers a bunch of new UI components and interactions from the specification.

Today I want to focus on two of those new elements that we will be using together: the infamous FAB (Floating Action Button) and CoordinatorLayout.

The FAB strikes back

If I had to pick one of the most iconic aspect of material design it would be the floating action button (henceforth known as FAB). It’s actually deemed important enough that the specification was expanded recently to have a dedicated section for it.

FAB are circular buttons containing a single icon (usually white or black) with a bright background (the color accent of your app for instance) and generally elevated above content (thus casting a shadow).

These FABs showcase the main actions that your app has to offer. As such, they are ones of the most important part of your UI and you should always pay special attention to get their interactions right.

Because FABs are so proeminent visually, they also offer a good opportunity to add pleasant touches to your app. In the word of the specification: “Take advantage of [FAB’s] visibility to create delightful transitions for a primary UI element.”

The support design library offers a default implementation of that UI widget that’s backward compatible with older versions of Android that don’t have elevation/shadow support or round clipping in the form of the FloatingActionButton widget which is a subclass of the classic ImageView.

Here I want to focus on one of the documented FAB transition: morphing. This transition is used to alternate between two main actions for a single FAB depending on the context:

To implement this, you can create a simple subclass of the default FAB that let you also specify a secondary set of icon and background and then create a custom animation to alternate between the two:

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
public class SwitchableFab : FloatingActionButton
{
	AnimatorSet switchAnimation;
	bool state;
	Drawable srcFirst, srcSecond;
	ColorStateList backgroundTintFirst, backgroundTintSecond;

	// ctors.

	void Initialize (Context context, IAttributeSet attrs)
	{
		srcFirst = this.Drawable;
		backgroundTintFirst = this.BackgroundTintList;

		if (attrs == null)
			return;
		var array = context.ObtainStyledAttributes (attrs, Resource.Styleable.SwitchableFab);
		srcSecond = array.GetDrawable (Resource.Styleable.SwitchableFab_srcSecond);
		backgroundTintSecond = array.GetColorStateList (Resource.Styleable.SwitchableFab_backgroundTintSecond);
		array.Recycle ();
	}

	public void Switch ()
	{
		if (state)
			Switch (srcFirst, backgroundTintFirst);
		else
			Switch (srcSecond, backgroundTintSecond);
		state = !state;
	}

	void Switch (Drawable src, ColorStateList tint)
	{
		const int ScaleDuration = 200;
		const int AlphaDuration = 150;
		const int AlphaInDelay = 50;
		const int InitialDelay = 100;

		if (switchAnimation != null) {
			switchAnimation.Cancel ();
			switchAnimation = null;
		}

		var currentSrc = this.Drawable;

		// Scaling down animation
		var circleAnimOutX = ObjectAnimator.OfFloat (this, "scaleX", 1, 0.1f);
		var circleAnimOutY = ObjectAnimator.OfFloat (this, "scaleY", 1, 0.1f);
		circleAnimOutX.SetDuration (ScaleDuration);
		circleAnimOutY.SetDuration (ScaleDuration);

		// Alpha out of the icon
		var iconAnimOut = ObjectAnimator.OfInt (currentSrc, "alpha", 255, 0);
		iconAnimOut.SetDuration (AlphaDuration);

		var outSet = new AnimatorSet ();
		outSet.PlayTogether (circleAnimOutX, circleAnimOutY, iconAnimOut);
		outSet.SetInterpolator (AnimationUtils.LoadInterpolator (Context,
		                                                         Android.Resource.Animation.AccelerateInterpolator));
		outSet.StartDelay = InitialDelay;
		outSet.AnimationEnd += (sender, e) => {
			BackgroundTintList = tint;
			SetImageDrawable (src);
			JumpDrawablesToCurrentState ();
			((Animator)sender).RemoveAllListeners ();
		};

		// Scaling up animation
		var circleAnimInX = ObjectAnimator.OfFloat (this, "scaleX", 0.1f, 1);
		var circleAnimInY = ObjectAnimator.OfFloat (this, "scaleY", 0.1f, 1);
		circleAnimInX.SetDuration (ScaleDuration);
		circleAnimInY.SetDuration (ScaleDuration);

		// Alpha in of the icon
		src.Alpha = 0;
		var iconAnimIn = ObjectAnimator.OfInt (src, "alpha", 0, 255);
		iconAnimIn.SetDuration (AlphaDuration);
		iconAnimIn.StartDelay = AlphaInDelay;

		var inSet = new AnimatorSet ();
		inSet.PlayTogether (circleAnimInX, circleAnimInY, iconAnimIn);
		inSet.SetInterpolator (AnimationUtils.LoadInterpolator (Context,
		                                                        Android.Resource.Animation.DecelerateInterpolator));

		switchAnimation = new AnimatorSet ();
		switchAnimation.PlaySequentially (outSet, inSet);
		switchAnimation.Start ();
	}
}

You can then instantiate this new class directly in your XML layout:

1
2
3
4
5
6
7
8
9
10
<myApp.SwitchableFab
    android:id="@+id/fabButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_marginRight="16dp"
    android:layout_marginBottom="16dp"
    android:src="@drawable/ic_action_mylocation"
    app:srcSecond="@drawable/ic_favorite_selector"
    app:backgroundTintSecond="@color/favorite_background" />

For that interaction, the icon itself is normally not supposed to scale but since the widget is based on ImageView it’s impractical right now to separate the two layers to animate a counter-scale for the icon.

I imagine that a default implementation of the documented FAB interactions will likely find its way into the library at some stage but in the meantime it’s very easy to cook them up yourself like above.

You may also have noticed in the video that the second state of my FAB uses an animated selector. This is done by augmenting the SwitchableFab class to track the checkable state (as I have already demonstrated).

In any case, you can find the full implementation of that selector and checkable changes in Moyeu repository.

CoordinatorLayout, the missing orchestra conductor

Another interesting type that support-design brings is CoordinatorLayout.

On the surface it doesn’t seem to do much, it’s intended as a wrapper around your existing UI that behaves like a FrameLayout from a layout perspective. The true value of CoordinatorLayout is found on its child views.

Just like its name imply, CoordinatorLayout serves as a central conductor for more complex transitions that your app UI may be doing especially when involving several floating views like the aformentioned FAB or snackbars.

The core working of the class relies on so-called Behaviors that can be set on any child views of the CoordinatorLayout. In a behavior implementation, views can define if they want to be dependent on some other views and get a callback when that other view state (position, size, etc…) changes.

Behaviors can be attached to views in a multitude of ways but here is how you can declare it directly in your layout XML:

1
2
3
<!-- Based on the same FAB definition than above -->
<moyeu.SwitchableFab
    app:layout_behavior="md55d31ab91effba0f9ed7ec79c59c38391.InfoPaneFabBehavior" />

Here I made a custom behavior that allows me to automatically track the state of my application bottom pane as it appears/disappears and is dragged by the user so that the FAB automatically stick to it and change its state when the pane is initially expanded (using the transition animation we saw earlier):

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 InfoPaneFabBehavior : CoordinatorLayout.Behavior
{
	int minMarginBottom;
	bool wasOpened = false;

	public InfoPaneFabBehavior (Context context, IAttributeSet attrs) : base (context, attrs)
	{
		minMarginBottom = (int)TypedValue.ApplyDimension (ComplexUnitType.Dip, 16, context.Resources.DisplayMetrics);
	}

	public override bool LayoutDependsOn (CoordinatorLayout parent, Java.Lang.Object child, View dependency)
	{
		return dependency is InfoPane;
	}

	public override bool OnDependentViewChanged (CoordinatorLayout parent, Java.Lang.Object child, View dependency)
	{
		// Move the fab vertically to place correctly wrt the info pane
		var fab = child.JavaCast<SwitchableFab> ();
		var currentInfoPaneY = ViewCompat.GetTranslationY (dependency);
		var newTransY = (int)Math.Max (0, dependency.Height - currentInfoPaneY - minMarginBottom - fab.Height / 2);
		ViewCompat.SetTranslationY (fab, -newTransY);

		// If alternating between open/closed state, change the FAB face
		if (wasOpened ^ ((InfoPane)dependency).Opened) {
			fab.Switch ();
			wasOpened = !wasOpened;
		}

		return true;
	}
}

Dead simple right?

CoordinatorLayout can also be used to implement other user interactions like swipe-to-dismiss or other scrolling techniques (like collapsing toolbars). Checkout the provided SwipeDismissBehavior and AppBarLayout.Behavior for more information on those scenarios.

July 10, 2015 1:30 GMT

Weekly Xamarin Newsletter Issue #48

Xamarin and Oracle Join Forces to Build Better Enterprise Apps
Nat Friedman, from Xamarin Inc., announces the new partnership with Oracle.

From Zero to Hero in Xamarin Forms in 53 Minutes
Jeff Prosise, from Wintellect Inc., will get you started with Xamarin.Forms in under an hour.

Adding a Bindable Map with the Map Behavior
Jonathan Yates adds a behavior to Xamarin.Forms Maps so he can ski down a mountain.

Xamarin: Customize Your Xamarin.Forms App With Pages For Each Platform
Pierce Boggan, from Xamarin Inc., shows how he added the camera page to his Xamarin.Forms app.

5 Days to a Beautiful Xamarin.Forms User Interface

I (adam) count down what it takes to build a beautiful Xamarin.Forms app.

 

Connect to Customers with My Shoppe
James Montemagno, from Xamairn Inc., releases another Xamarin.Forms template app.

Bibbidi-Bobbidi-Boo – Using Custom Renderers to enchant your UI
Gerald Versluis, add some circle magic to his Xamarin.Forms.

Xamarin Test Cloud to Support Appium Framework
Steven Yi, from Xamarin Inc., tells us we have more choices for testing our apps.

The slides from my iBeacon mini-hack are now available
Jim Bennett has put up his slides from a recent mini-hack.

A Comprehensive Guide to Creating a Xamarin.Forms App with MvvmCross (Part 3 of 5)
Brent Edwards, from Magenic Inc., add another part on his MVVMCross series.

Gone Mobile 27: Automated App Testing with Niels Frydenholm
Greg Shackles and Jon Dick talk with Niels Frydenholm from eBay about testing.

 

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

July 10, 2015 12:00 GMT

5 Days to a Beautiful Xamarin.Forms User Interface – Styles

5Days-Day5Wow, we made it to the finish line. This series has been fun to write because it’s not my normal post or series. See, I like to leave you with something that’s actionable and a lot of these posts have been more thought provoking and educational.

In this post, we are going to concentrate on how to tie everything together. How do you use your color, fonts, icons, and backgrounds in your Xamarin.Forms app? To be completely honest, I’m not sure I know.

In my current app at work, we use all code and no XAML. I know, you can’t believe it! In addition to using all code, we also style our app using code as well. We do use a little XML on Android to style the BarTextColor and BarBackgroundColor for the entire app.

Code Styles

Here is a little sample of how we use code to style our app. This sample set of styles comes directly from the Xamarin website.

var buttonStyle = new Style (typeof(Button)) {
    Setters = {
        new Setter {Property = Button.BackgroundColorProperty, Value = Color.Yellow},
        new Setter {Property = Button.BorderRadiusProperty, Value = 0},
        new Setter {Property = Button.HeightRequestProperty, Value = 42}
    }
}
// apply directly to a single control
var mybutton = new Button {
    Text = "Style Me",
    Style = buttonStyle
};

Code styles work pretty well and we reuse styles by building them up from a base of colors, fonts and background colors that have been selected for our application. Besides reusability, almost every style is centrally located in a single file, just like CSS would be for a web app. The familiarity is great except when we have problems.

Just like with CSS, unintended consequences do crop up when you change something and you don’t immediately see the results. Like when you change a padding for one control or page, and you don’t see the disastrous results on another page until a few hours or days later. Yikes!

XAML Styles

Xaml Styles just like code styles are possible but they do come at a cost. If you want global styles, you are going to have to put the styles in the Apps ResourceDictionary. Unfortunately, this causes a lookup problem. See every time a control uses a style, the platform climbs the resource dictionary from the control to the page and then to the app looking for the style.

Looking through numerous Resource Dictionaries are not a problem with PC and web browsers, which is the home of Silverlight and WPF. On mobile, in the current Xamarin.Forms, we have a bit of a horsepower problem. And it has nothing to do with Xamarin.Forms. It’s really an issue of processor speed and how much work needs to be done rendering the page.

One obvious thing you could do is break up your styles and put them closer to the control that needs them. This is the sage advice you’ll get from the Xamarin.Forms book by Charles Petzold and you should follow it. Once Xamarin.Forms gets Merge Dictionaries, most of this problem will go away, I think.

The End

That about wraps up this series and post. Next week “I’ll be back” with more action packed posts on how to make your Xamarin.Forms UI look and work great. I’ll see you next week.

Adam

5 Days to a Beautiful Xamarin.Forms User Interface

Check out the other posts in the Build a Beautiful Xamarin.Forms User Interface series.

The post 5 Days to a Beautiful Xamarin.Forms User Interface – Styles appeared first on Syntax is my UI.

July 10, 2015 12:38 GMT

New & Improved Xamarin.Android Templates for Visual Studio

It has been a bit over a year since I first introduced my Xamarin.Android Templates pack for Visual Studio and things sure have changed in the world of Android since then. Early on the templates pack only introduced a few item templates for menu items and a simple implementation of the Navigation Drawer, my favorite way to navigate in Android. Then this March Google went and changed everything with AppCompat and the introduction of the new Toolbar. I rushed to update all of my templates to include all these nice new features. It looks like it is that time of the year again with the new Android Design Support Library, which yet again changes how we implement the Navigation Drawer and of course let’s not forget about the big change to AppCompatActivity. 

I am pleased to announce the latest release of my templates that incorporate all of these changes to make it easy to get up and running with AppCompat and the new fancy navigation drawer featuring the NavigationView.

You can grab these templates from the Visual Studio Gallery by going to “Tools->Extensions and Updates” in any flavor of Visual Studio and searching for Xamarin.Android Templates

Once installed you will see a few new Project Templates under Android to create a blank app that features AppCompat or a full Navigation Drawer enabled app also featuring AppCompat:

Once you have your app up and running you might want to add a few new menu items such as search, share, or just a menu item and I have you covered:

Of course everything is open source on GitHub so you take take a peek at what I am doing in the templates. Additionally, if you already have an app and are looking to upgrade your navigation drawer or tabs to the new material support library implementations then look no further than my Xam.NavDrawer GitHub repo that has been updated with an awesome new example! 

I hope you enjoy these new updated templates and I look forward to your feedback or suggestions for future updates!

July 09, 2015 12:00 GMT

5 Days to a Beautiful Xamarin.Forms User Interface – Backgrounds

5Days-Day4Now that we have Colors, Fonts, and Icons out of the way, it’s time to focus on backgrounds. Yes, backgrounds. Not everything in your app has to be white. Apple might like that, but come on, the world is full of colors and images.

Background images were all the rage a couple of years ago, you remember, all the fake stitching and Corinthian leather. Or how about the fake wood backgrounds, I loved that one. Today though, we have different tastes, and ideas, of what a beautiful app is.

With Google’s new Material Design and Apple sweeping skeuomorphic design under the rug, a cleaner, more authentic, esthetic is popular. Now that does not mean everything has to be flat and lifeless, like the Windows live tiles. Nothing says dated like 8 bit graphics on a tile that flips. Sorry Microsoft, but I got like a billion pixels in my pocket and you use 8 of them.

Colors

Adding colors to the background of a page can add some interest. Take a look at how Pinterest added a light grey to the background under the Pins counter. It makes a nice transition from the top where status is and the bottom where the boards are located.

5Steps-Backgrounds

Images

In my opinion, background images make the biggest impact on the design of your app. Take a look at how Twitter uses them at the top of the profile page and how Flipboard uses them to highlight news articles. You know I am a sucker for the text overlay on the image. Be careful with this technique, a light picture with light text looks terrible.

Colorbackgrounds

Every background image need not be a full Ansel Adams panorama of vistas in the wild west. They can also be like these four splash screens that have a centered logo and subtile highlights or shadows of a solid color.

Now, are you ready to add some backgrounds to your app? I hope so. There’s nothing wrong with white or black for that matter, but color and images will help make your next Xamarin.Forms app beautiful. Give it a try.

5 Days to a Beautiful Xamarin.Forms User Interface

Check out the other posts in the Build a Beautiful Xamarin.Forms User Interface series.

The post 5 Days to a Beautiful Xamarin.Forms User Interface – Backgrounds appeared first on Syntax is my UI.

July 08, 2015 12:00 GMT

5 Days to a Beautiful Xamarin.Forms User Interface – Icons

5Days-Day3Woohoo! It’s hump day in our 5 days to a more beautiful Xamarin.Forms user interface blog series. Today is going to be easy; all you have to do is buy an icon set.

Yep, you heard me, go out and purchase an icon set from Picons.me or any other reputable designer or company. The only caveat is that the icon set needs to have enough icons to satisfy your current project.

Icons

Icons are a pretty important part of the design of your application. It comes in a comfortable third behind colors and font. Every polished application out in the app store can be differentiated by a few things, one of them being the design and style of their icons.

Next time you’re in Twitter, look at how many different icons they use and how stylistically similar each one is. The reason for getting a large icon set is to cover all the use cases for your current app and maybe your future ones as well.

iPhone & iOS

PiconsFor iPhone and iOS you can’t go wrong with the Thin icon set from Picons.me. I use the icons exclusively on this blog. With over 1000 different icons, I usually have a choice between which icon to use. Mixing and matching icon pieces is easy for when the set doesn’t have what I’m looking for.

Included in the set are a bunch of sizes and, of course, they also come in my favorite format, SVG. With SVG, I can modify the stroke of the icons and beef them up a little. I occasionally do this for icons on Android.

Sizes

Android

For Android, you can also use Picons.me thin set if you want, but they may seem out of place. Android and Material Design have taken a different approach to the design of icons. One suggestion is to use the free Material Design icon pack from Google. Take a look at all these icons.

style_icons_system_intro

 

IconFinderThe key to a beautiful user interface when it comes to icons is consistency and appropriateness for the platform. Mixing and matching icons can be done, especially if you use a service like IconFinder.com. You can find almost any icon, but when you’re looking for 4 or 5 in the same style, it can be challenging.

IconFinder is also a good place to find a designer. Most designers uploading icons also have sets you can buy.

With Android and iOS having a different set of icon styles can make cross-platform icons a challenge; it’s not hopeless. If you’re looking to walk a fine line between Androids’ Material Design and iOS light and airy, I wish you luck. I have not found a single icon set that handles both and looks native to the platforms.

5 Days to a Beautiful Xamarin.Forms User Interface

Check out the other posts in the Build a Beautiful Xamarin.Forms User Interface series.

The post 5 Days to a Beautiful Xamarin.Forms User Interface – Icons appeared first on Syntax is my UI.

July 07, 2015 1:30 GMT

Episode 27: Automated App Testing with Niels Frydenholm

Interested in getting started writing automated tests for your apps but don’t know where to start? In this episode we’re joined by Niels Frydenholm to talk about how his team set themselves up for success over at eBay.

Hosts: Greg Shackles, Jon Dick

Guest: Niels Frydenholm

Links:

Thanks to our Sponsors!

Raygun.io

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

July 06, 2015 2:38 GMT

Bibbidi-Bobbidi-Boo – Using Custom Renderers to enchant your UI

While Xamarin.Forms provides a unified way to also create our UI from a single code base, the default controls tend to be just that; default controls.
Don’t get me wrong, I am very happy with these controls and they can be used to create simple, no-fancy-design-needed apps. But when you have created some apps, you want a little bit more. You have to stand out between all the other apps already out there and how to do that better then with an awesome UI?

Luckily for us, Xamarin already foresaw this and gave us something that is called Custom Renderers. With custom renderers we’re able to render controls in our own way, rather than having Xamarin rendering it to the default control for that platform. With this we can customise how an image looks for example. And this is exactly what we will be doing, turn our UI into something magical like we are the fairy godmother herself!

The ugly pumpkin

Right now my 4DotNet app has the default implementation of a ListView with Image Cells. This shows up in the app like this:

Employee list screenshot iOS
Employee list screenshot iOS

It looks ok! But why settle for ok if we can have AWESOME?
For mobile apps, especially for profile pictures, it seems to be required that they are shown as circular images rather than the squares I have now. Let’s see if we can turn this around.

Bibbidi-Bobbidi-Boo!

Now let us work some magic.

To work with our custom renderer, we first have to create our own image type. Let’s call this CircularImage.
This type we can use in all our apps, so put it in the shared project of your solution.

namespace FourDotNet.Controls
{
   public class CircularImage : Image
   {
   }
}

Our CircularImage inherits from the default Xamarin.Forms.Image. If you like you could add some custom properties and other stuff in there, but for what we’ll be doing right now that won’t be necessary.

Now the rest consists of creating a custom renderer per platform. These I will name the CircularImageRenderer and these will inherit from the default Xamarin.Forms ImageRenderer, which will be the platform specific one (i.e. Xamarin.Forms.Platforms.iOS.ImageRenderer).

public class CircularImageRenderer : ImageRenderer
{
   // TODO
}

Bibbidi-Bobbidi-iOS!

Let’s start with iOS.

We create our new file according to the above empty class and declare our iOS CircularImageRenderer.

private void DrawCircle()
{
    double min = Math.Min(Element.Width, Element.Height);
    Control.Layer.CornerRadius = (float)(min / 2.0);
    Control.Layer.MasksToBounds = false;
    Control.Layer.BorderColor = Color.White.ToCGColor();
    Control.Layer.BorderWidth = 3;
    Control.ClipsToBounds = true;
}

We start with defining a custom private method which transforms our square image to a round one and adds a border around it so it looks extra fancy.

In itself this does nothing, because we have to override our default renderer behaviour to make this transformation visible. So we override the OnElementChanged and OnElementPropertyChanged method like underneath.

protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
{
   base.OnElementChanged(e);
            
   if (e.OldElement != null || Element == null)
      return;
            
   DrawCircle();
}

protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
   base.OnElementPropertyChanged(sender, e);
   
   if (e.PropertyName == VisualElement.HeightProperty.PropertyName || e.PropertyName == VisualElement.WidthProperty.PropertyName)
   {
      DrawCircle();
   }
}

With this code we respond to the event which is fired when the Element (Image in this case) has changed or any property of the Element has changed.

Within the ElementChanged we just check for nulls and then draw our CircularImage, with the PropertyChanged we check if the changed property has anything to do with the appearance of our Image. If so, we then redraw, if not, we do nothing.

That concludes the code we have to write for our renderer, that wasn’t so bad now, was it?

There is one vital line we have to add. We have to tell Xamarin that whenever it finds our custom control CircularImage, that there is a custom renderer for that. We do that in the same way as we saw in my previous post about Dependency Injection.

[assembly: ExportRenderer(typeof(CircularImage), typeof(CircularImageRenderer))]
namespace FourDotNet.iOS.CustomRenderers
{
    public class CircularImageRenderer : ImageRenderer
    {
       // ... The above code is here
    }
}

Note the first line here. We state that we export a renderer for our type CircularImage, and that renderer is of our type CircularImageRenderer.

Bibbidi-Bobbidi-Android!

On to our Android renderer.

As you might expect this process will be roughly the same, only the implementation will be different. However, this is more true for Windows Phone than Android. On Android there is no physical layer to interact with, so instead we need to override the method that Xamarin uses to draw the child controls.

We can do this by using the below code;

protected override bool DrawChild(Canvas canvas, View child, long drawingTime)
{
   var radius = Math.Min(Width, Height)/2;
   var strokeWidth = 10;
   radius -= strokeWidth/2;
            
   //Create path to clip
   var path = new Path();
   path.AddCircle(Width/2, Height/2, radius, Path.Direction.Ccw);
   canvas.Save();
   canvas.ClipPath(path);
          
   var result = base.DrawChild(canvas, child, drawingTime);
   canvas.Restore();
   
   // Create path for circle border
   path = new Path();
   path.AddCircle(Width/2, Height/2, radius, Path.Direction.Ccw);
   var paint = new Paint();
   paint.AntiAlias = true;
   paint.StrokeWidth = 5;
   paint.SetStyle(Paint.Style.Stroke);
   paint.Color = Color.White;
   canvas.DrawPath(path, paint);
   
   //Properly dispose
   paint.Dispose();
   path.Dispose();

   return result;
}

Also, since API Level 18, hardware acceleration for drawing was introduced. As you might know, that is something you’d want to use!

You can set a flag to use software rendering for below API Level 18 in the OnElementChanged event like below.

protected override void OnElementChanged(ElementChangedEventArgs e)
{
   base.OnElementChanged(e);

   if (e.OldElement == null)
   {
      if ((int)Android.OS.Build.VERSION.SdkInt < 18)
         SetLayerType(LayerType.Software, null);
   }
}

Of course, don’t forget to export your renderer!

Bibbidi-Bobbidi-Windows Phone!

The Windows Phone renderer is again a bit easier. We can just use the Clip property here and assign a EllipseGeometry to it, like so.

protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
  base.OnElementPropertyChanged(sender, e);

  if (Control != null && Control.Clip == null)
  {
    var min = Math.Min(Element.Width, Element.Height) / 2.0f;

    if (min <= 0)
      return;

    Control.Clip = new EllipseGeometry
    {
      Center = new System.Windows.Point(min, min),
      RadiusX = min,
      RadiusY = min
    };
  }
}

And again, let’s not forget to register our custom renderer.

[assembly: ExportRenderer(typeof(ImageCircle), typeof(ImageCircleRenderer))]
namespace FourDotNet.iOS.CustomRenderers
{
   // ...
}

Turning it into majestic golden carriage

For the last bit we have to use our new CircularImage and see how all this looks like.

Before I have used a ListView with an ImageCell, in XAML that looks like this.

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

Of course an ImageCell is a composite of a few controls already which acts as a template for a list item. although you can create your own custom cell, for now I will create my own list item template right here in the ListView. This probably isn’t what you would want in your final application, but for the sake of this example it will do.

In the underneath code you will see how I replaced the ImageCell with my own template and made it look similar.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:controls="clr-namespace:FourDotNet.Controls;assembly=FourDotNet"
             x:Class="FourDotNet.Pages.EmployeesPage"
             Title="Medewerkers">
<!-- ... Some XAML omitted here ... -->
<ListView.ItemTemplate>
   <DataTemplate>
      <ViewCell>
         <ViewCell.ContextActions>
            <MenuItem Text="Stuur e-mail" Clicked="EmployeeContextEmail_OnClicked" />
         </ViewCell.ContextActions>

         <StackLayout Orientation="Horizontal">
            <controls:CircularImage Source="{Binding PhotoUrl}" />

            <Grid>
               <Grid.RowDefinitions>
                  <RowDefinition Height="*" />
                  <RowDefinition Height="*" />
               </Grid.RowDefinitions>

               <Label YAlign="End" Grid.Row="0" Text="{Binding Name}" TranslationY="4" />
               <Label YAlign="Start" Grid.Row="1" Text="{Binding Function}" FontSize="Micro" TextColor="Accent" />
            </Grid>
         </StackLayout>
      </ViewCell>
   </ListView.ItemTemplate>
</ListView>
<!-- ... Some XAML omitted here ... -->
</ContentPage>

You will notice that you have to specify a new namespace which specifies where my custom CircularImage resides. In this case I have used ‘controls’.
Now with this new namespace I can define my CircularImage control just like any other ‘normal’ control.

When we run this on all of the different platforms, you will see an enchanting result…!

CircularImage on all platforms
CircularImage on all platforms

To create these custom renderers I have followed another blog-post by James Montemagno and the documentation of Xamarin, so code similarities might be apparent. All credits for the math-hocus-pocus goes to him/them.

July 03, 2015 12:59 GMT

From Zero to Hero in Xamarin Forms in 53 Minutes

Looking for a fast way to get up to speed on Xamarin Forms? There are tons of learning resources out there, including a series of articles I published this spring, the first of which can be found here. But while some developers prefer learning by reading, others find video training the best learning medium. Which is why I recorded a 53-minute video entitled Introduction to Xamarin Forms and conspired with the folks at WintellectNOW to make it available for free. It covers the basics of using Visual Studio 2015 and Xamarin Forms to build apps for iOS, Android, and Windows Phone, and it comes with 30 MB of downloadable sample code. In future videos, I’ll cover topics such as custom renderers and process lifetime management. For now, enjoy the inaugural video, and have fun learning Xamarin Forms!

 

imageRead more

July 02, 2015 7:58 GMT

Determining the Correct String for UIFont.FromName

We use a lot of different fonts throughout the different apps on our platform, and often it can be a little bit of a chore to figure out the correct string to feed to UIFont.FromName() in order to properly instantiate a font from the files. One approached I've used in the past is to throw some lines in my app's startup code like this:

foreach (var family in UIFont.FamilyNames)  
    foreach (var fontName in UIFont.FontNamesForFamilyName(family))
        Console.WriteLine(fontName);

Then I could quickly skim the output, pick out the name I was looking for, and move on with my life. This works, but it's a bit tedious and requires manual work every time. Neither of those really sits well with me.

I recently came across LCDF Typetools which is a nice little set of tools, including otfinfo. You can get these tools in a variety of ways. I went with Homebrew, which is nice and simple:

brew install lcdf-typetools  

Here's what the output of otainfo looks like:

+ otfinfo -i SourceSansPro-Light.ttf
Family:              Source Sans Pro Light  
Subfamily:           Regular  
Full name:           Source Sans Pro Light  
PostScript name:     SourceSansPro-Light  
Preferred family:    Source Sans Pro  
Preferred subfamily: Light  
Version:             Version 2.010;PS Version 2.0;hotconv 1.0.78;makeotf.lib2.5.61930  
Unique ID:           2.010;ADBE;SourceSansPro-Light;ADOBE  
Designer:            Paul D. Hunt  
Manufacturer:        Adobe Systems Incorporated  
Vendor URL:          http://www.adobe.com/type  
Trademark:           Source is a trademark of Adobe Systems Incorporated in the United States and/or other countries.  
Copyright:           Copyright 2010, 2012, 2014 Adobe Systems Incorporated (http://www.adobe.com/), with Reserved Font Name 'Source'.  
License URL:         http://scripts.sil.org/OFL  
License Description: This Font Software is licensed under the SIL Open Font License, Version 1.1.

This license is available with a FAQ at: http://scripts.sil.org/OFL. This Font Software is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the SIL Open Font License for the specific language, permissions and limitations governing your use of this Font Software.  
Vendor ID:           ADBE  

In this case we're looking specifically for PostScript name. It wouldn't be difficult to parse this output to get it, but thankfully they have us covered and have a flag for just returning that name:

+ otfinfo -p SourceSansPro-Light.ttf
SourceSansPro-Light  

Perfect! No extra parsing needed. As I've documented before, I use F#/FAKE for all of my build scripting, so naturally I needed to try hooking this up into that as well:

Target "font-test" (fun () ->  
    ExecProcessAndReturnMessages (fun p ->
        p.FileName <- "otfinfo"
        p.Arguments <- "-p SourceSansPro-Light.ttf"
    ) (TimeSpan.FromSeconds 30.)
    |> fun response ->
        match response.ExitCode with
        | 0 -> 
            let postscriptName = response.Messages.[0]

            printfn "PostScript Name: %s" postscriptName
        | 1 -> failwith "Error processing font file"
)
July 01, 2015 5:45 GMT

Code Mill Minute: Setting Up Xamarin Studio To Work With TFS Online Git Source Control

Today I’m starting a new series of blog posts entitled “Code Mill Minute”. These will be a departure from my normal novel length posts (I’m trying to shorten those too, but that’s another story) and will focus on just fixing or doing something that we developers encounter on a day to day basis.

Short and sweet… to the point… and only takes a minute to read.

So let’s dive into today’s topic … integrating Xamarin Studio on the Mac with TFS Online’s (aka Visual Studio Online) Git source control.

The Problem

By default, the account you login as to Visual Studio Online is your Microsoft account, which is an email address. The problem with that is the “@” symbol. Applications other than Visual Studio have an issue using that symbol to connect with Git.

The Solution

We need to enable another set of credentials in TFS Online, link the new credentials up to our existing VSOnline account, clone the repository with our new user, then have Xamarin Studio perform a remote Git operation, so it can cache the user credentials as well.

Enabling VSOnline Alternate Credentials

The first thing we’ll do is enable alternate credentials in VSOnline. To do so, follow these steps.

  1. Login to VSOnline with your normal credentials
  2. In the upper right corner, you’ll see your name, click on that, then click on “My Profile” in the resulting dropdown.
  3. A screen similar to the one below will appear. Click on the “Credentials” tab and then “Enable Alternate Credentials”.
    Enabling Alternate Credentials

    Enabling Alternate Credentials

  4. Enter the username and password you want to use for Git access with Xamarin Studio (or the command line).

Integrating With Xamarin Studio on the Mac

Next we need to clone the repository with the new credentials, then make sure Xamarin Studio has those credentials cached as well.

  1. First, note the clone URL of the repository from TFS Online. (This can be found from the “clone” button while viewing the top level source code structure within TFS Online website.)
  2. Open up Terminal and navigate to the directory you want to clone the repository to.
  3. Run the Git clone command with the URL of the repository you want to clone to (from step 1 above).
    git clone "https://testproject.visualstudio.com/DefaultCollection/_git/Test"
  4. You’ll be prompted for your username and password – enter the “alternate” ones you just created.
  5. Then you’ll see a screen similar to this… I had no idea what it was at first & I thought I did something wrong, but then I realized it was the friendly Visual Studio logo!
    TFS Git Cloning!

    TFS Git Cloning!

  6. Finally, you can start using local Git within Xamarin Studio as normal. When you need to do the first operation against the remote repository, you’ll be prompted for your username and password – again this is the “alternate credentials” you created. Once entered, Xamarin Studio will cache them, and you’ll be off and running!

That’s all there is to getting a TFS Online Git repository working with Xamarin Studio on the Mac … the secret sauce really is just enabling alternate credentials with your Visual Studio Online account. Once that’s done… off to the races!

June 30, 2015 9:39 GMT

Love and Free Apps

This. 100 times this.

This is the age of writing iOS apps for love.

Well, that’s not true for everybody. Well-established and awesome companies such as Omni, Panic, Flexibits, AgileBits, Tapbots, and The Iconfactory have a business writing iOS apps. (They do it for love, but not just for love.) Companies like Black Pixel make money by writing apps for other companies that have money.

And big companies and funded companies don’t actually have to make money from their iOS apps. They have other goals. (I don’t pretend to understand the economics of funded companies.)

You the indie developer could become the next Flexibits. Could. But almost certainly not. Okay — not.

What’s more likely is that you’ll find yourself working on a Mobile Experience for a Big National Brand(tm) and doing the apps you want to write in your spare time.

If there’s a way out of despair, it’s in changing our expectations.

Write the apps you want to write in your free time and out of love for the platform and for those specific apps. Take risks. Make those apps interesting and different. Don’t play it safe. If you’re not expecting money, you have nothing to lose.

Could the do-it-for-love era — with the creative freedom that that brings — bring us back to the days when we downloaded apps that weren’t from Facebook and Starbucks and Funded Company X, and we told our friends about our exciting finds?

I hope. I have hope.

Niche is the only other area I can see. Find something where you - or someone close to you - have an itch. Scratch it with an App. See if other people have the same itch. eg:

  • Trip Wallet. We needed something to keep track of travel spending on a long trip
  • Nearest Bus. I was catching the bus a lot in London
  • mobileAgent. I was using FreeAgent a lot, and wanted to do it from my phone.
  • On the roll (unreleased). Leonie needed to keep track of what film was in her various cameras.
  • Tides (unreleased). I could only swim in a +/- 2 hour window of high tide. So I wrote an app which reminded me of that.

Find an itch. Scratch it. Do it for love.

June 30, 2015 8:51 GMT

Refining the Economics of Your App for the Right Market

Url: https://visualstudiomagazine.com/articles/2015/06/30/app-to-market-part-2-right-app.aspx

In part 1, we looked at researching whether your brilliant idea was worth pursuing as a business venture and it all starts with seeing if the need exists. Now that you've validated that there is a need for the product, only then is it time to start building things. Let's take the next step, which is to work through the basics of the economics of your idea.

June 30, 2015 7:13 GMT

TechDays 2015

Den 20 oktober börjar TechDays med förkonferens, jag och Johan Karlsson kommer att dela med oss av våra kunskapar gällande cross-platformutveckling.

Att bygga cross-platformlösningar är alltid en stor utmaning då det i grunden är olika operativsystem, programmeringsspråk och utvecklingsmiljöer.
Xamarin löser en stor del av cross platform problematiken genom att man kan utveckla appar för iOS, OSX och Android med C#. iOS och Android kan även byggas i Visual Studio. Under dagen kommer vi gå genom hur man bygger arkitektur och gränssnitt för en optimal native upplevelse på varje plattform, det vill säga iOS, OSX, Android och Windows. Vi kommer också att visa hur man kan testa mobila applikationer på ett effektivt sätt med hjälp av Xamarin TestCloud.

Läse mer här, http://tdswe.kistamassan.se/Program-2015/Sessioner/Pre-Conf-Cross-Platform-pa-ratt-satt

June 30, 2015 8:19 GMT

iOS range slider for Xamarin and Xamarin.Forms

In this post I will show you how to build a range slider for Xamarin.iOS and how to write a custom renderer if you want to use it with Xamarin.Forms. If you want to use the range slider control you can write the code yourself or use the flipper forms control library, https://github.com/johankson/flipper, that can be installed from NuGet, https://www.nuget.org/packages/Flipper.Forms/. On GitHub you will also find a sample app that using the control.


iOS Range Slider

The control will be built up of six UIViews, one for the slider background, two for the indicators, two transparent views to increase the touch area for the indicators and one for the range between the indicators. The first step is to create a new class that inherits from UIView. In the constructor of the new class we are creating the views and adding them to the view. On the both indicators we’re adding a UIPanGestureRecognizer so we can detect when the users dragging the indicator.

public class RangeSlider : UIView
{
    private UIView _background, _leftIndicator, _rightIndicator, _range, _leftTouchArea, _rightTouchArena;
        private UIPanGestureRecognizer _leftIndicatorGesture, _rightIndicatorGesture;
 
     public RangeSlider()
     {
            _background = new UIView();
            _background.BackgroundColor = UIColor.LightGray;
 
            _range = new UIView();
            _range.BackgroundColor = UIColor.Blue;
 
            _leftIndicator = CreateIndicator();
            _leftIndicatorGesture = new UIPanGestureRecognizer(OnPan);
 
            _rightIndicator = CreateIndicator();
            _rightIndicatorGesture = new UIPanGestureRecognizer(OnPan);
 
            _leftTouchArea = new UIView();
            _leftTouchArea.BackgroundColor = UIColor.Clear;
            _leftTouchArea.AddGestureRecognizer(_leftIndicatorGesture);
 
            _rightTouchArena = new UIView();
            _rightTouchArena.BackgroundColor = UIColor.Clear;
            _rightTouchArena.AddGestureRecognizer(_rightIndicatorGesture);
 
            AddSubview(_background);
            AddSubview(_range);
            AddSubview(_leftIndicator);
            AddSubview(_rightIndicator);
            AddSubview(_leftTouchArea);
            AddSubview(_rightTouchArena);     
     }
 
     private UIView CreateIndicator()
     {
            var indicator = new UIView()
            {
                   BackgroundColor = UIColor.Gray
            };
 
            indicator.Layer.CornerRadius = 10;
            indicator.Layer.MasksToBounds = true;
 
            return indicator;
      }
}

Then we need to layout our views, we will do that in an override of the LayoutSubviews method. We also need to check if the views already is layouted so the layout not will be restored to the start layout if the method runs again.

private bool _layouted;
public override void LayoutSubviews()
{
      base.LayoutSubviews();
 
      if (!_layouted)
      {
            _background.Frame = new RectangleF(0, 19, (float)Frame.Width-20, 2);
            _range.Frame = new RectangleF(0, 19, (float)Frame.Width-20, 2);
            _leftIndicator.Frame = new RectangleF(0, 10, 20, 20);
            _rightIndicator.Frame = new RectangleF((float)Frame.Width - 40, 10, 20, 20);
 
            _leftTouchArea.Frame = new RectangleF(0, 0, 40, 40);
            _rightTouchArena.Frame = new RectangleF((float)Frame.Width - 60, 0, 40, 40);
 
            _layouted = true;
       }
}

In the OnPan method we want to update the position of the indicators if state of the gesture recognizer is began or changed. For this range slider we want the indicator to move in steps. To do this we need to move the indicator to next step if we have started to slide from the previous step. For that we need to know the step length in pixels and the cumulative manipulation and the delta manipulation. To calculate cumulative manipulation we need to save the position of the indicator when we starting the manipulation.

While you moving the indicator to next step when it has passed the previous you will have to check if the cumulative manipulation has passed the current step before you moving the indicator to next step.

 private void OnPan(UIPanGestureRecognizer recognizer)
        {
            if (recognizer.State == UIGestureRecognizerState.Began || recognizer.State == UIGestureRecognizerState.Changed)
            {
                var stepLength = _background.Frame.Width / ((MaxValue - MinValue) / Step);
 
                var touchPoint = recognizer.LocationInView(this);
 
                UIView indicator = null;
                UIView touchArea = null;
 
                //Is this a slide to left or right?
                if (recognizer == _leftIndicatorGesture)
                {
                    indicator = _leftIndicator;
                    touchArea = _leftTouchArea;
                }
                else if (recognizer == _rightIndicatorGesture)
                {
                    indicator = _rightIndicator;
                    touchArea = _rightTouchArena;
                }
 
                //save the start position for use when calculating cumulative manipulation
                if (recognizer.State == UIGestureRecognizerState.Began)
                {
                    _startX = (float)indicator.Center.X;
                }
 
 
                var cumulativeManipulation = touchPoint.X - _startX;
                var deltaManipulation = touchPoint.X - indicator.Center.X;
 
                //Check if the cumulative manipulation is has passed the last step
                if (deltaManipulation > 0 && cumulativeManipulation / stepLength > _lastStep ||
                    deltaManipulation < 0 && cumulativeManipulation / stepLength < _lastStep)
                {
                    if (deltaManipulation > 0)
                    {
                        _lastStep++;
                    }
                    else
                    {
                        _lastStep--;
                    }
 
                    //Calculate the new position of the indicator
                    var numberOfSteps = Math.Ceiling(deltaManipulation / stepLength);
                    var newPosition = new CGPoint(indicator.Center.X + stepLength * numberOfSteps, indicator.Center.Y);
 
                    var pixelStep = (MaxValue - MinValue) / Frame.Width;
 
                    if (touchPoint.X >= 0 && touchPoint.X <= _background.Frame.Width-10)
                    {
 
 
                        if (recognizer == _leftIndicatorGesture)
                        {
 
                            var newLeftValue = Round(MinValue + (pixelStep * newPosition.X));
 
                            if (newLeftValue >= RightValue)
                            {
                                return;
                            }
                        }
                        else if (recognizer == _rightIndicatorGesture)
                        {
                            var newRightValue = Round(MinValue + (pixelStep * newPosition.X));
 
                            if (newRightValue <= LeftValue)
                            {
                                return;
                            }
                        }
 
 
                        if (recognizer == _leftIndicatorGesture)
                        {
                            indicator.Center = newPosition;
                            touchArea.Center = newPosition;
                            var width = _rightIndicator.Center.X - _leftIndicator.Center.X;
                            _range.Frame = new CoreGraphics.CGRect(newPosition.X, _range.Frame.Y, width, _range.Frame.Height);
                        }
                        else if (recognizer == _rightIndicatorGesture)
                        {
                            indicator.Center = newPosition;
                            touchArea.Center = newPosition;
                            var width = _rightIndicator.Center.X - _leftIndicator.Center.X;
                            _range.Frame = new CoreGraphics.CGRect(_range.Frame.X, _range.Frame.Y, width, _range.Frame.Height);
                        }
 
 
 
                        LeftValue = Round(MinValue + (pixelStep * _leftIndicator.Center.X));
                        RightValue = Round(MinValue + (pixelStep * _rightIndicator.Center.X));
 
                        if (ValueChanging != null)
                        {
                            ValueChanging(this, new EventArgs());
                        }
                    }
                }
            }
            else if (recognizer.State == UIGestureRecognizerState.Ended)
            {
                if (ValueChanged != null)
                {
                    ValueChanged(this, new EventArgs());
                }
 
                _lastStep = 0;
            }
        }

I have added to events to the slider, ValueChanging and ValueChanged. ValueChanging occurs during the manipulation of the range slider and ValueChanged when the manipulation is finished. This because you maybe want to update labels with the values of the range slider during manipulation and update data based on the range slider when the manipulation is completed.

We also want to make it possible to set start values for the indicators. To do that we are creating a method called UpdateValue. We call the method from LayoutSubviews and from the setters of LeftValue and RightValue. It is important that the code not is running after that we have started using the slider. Therefore we have surrounded the call to the method with an if-statment. The code will run if a initialized variable is false, we will set it to true in the OnPan method.

private void UpdateValue(UIView indicator, UIView touchArea, double value)
{
            var percent = value / (MaxValue - MinValue);
 
            var position = (double)(_background.Frame.Width * percent);
 
            if (!double.IsNaN(position))
            {
                indicator.Center = new CGPoint(position, indicator.Center.Y);
                touchArea.Center = new CGPoint(position, indicator.Center.Y);
 
                var width = _rightIndicator.Center.X - _leftIndicator.Center.X;
                _range.Frame = new CoreGraphics.CGRect(_leftIndicator.Center.X, _range.Frame.Y, width, _range.Frame.Height);
 
                if (ValueChanged != null)
                {
                    ValueChanged(this, new EventArgs()); 
                }
            }
}

Xamarin.Forms
If you want to use the control with Xamarin.Forms you need to create a Xamarin.Forms control and a custom renderer. The Xamarin.Forms control will inherit from View and it will contains all the properties of the range slider, no logic at all.

 public class RangeSliderRenderer : ViewRenderer<Flipper.Controls.RangeSlider, iOS.Controls.RangeSlider>
    {
        protected override void OnElementChanged(ElementChangedEventArgs<RangeSlider> e)
        {
            base.OnElementChanged(e);
 
            if (e.NewElement != null)
            {
                var slider = new Controls.RangeSlider();
                slider.Frame = new CGRect((float)Frame.X, (float)Frame.Y, (float)Frame.Width, 200);
 
                slider.ValueChanging += slider_ValueChanging;
                slider.ValueChanged += slider_ValueChanged;              
 
                SetNativeControl(slider); 
            }
 
        }
 
        void slider_ValueChanged(object sender, EventArgs e)
        {
           if(Element.Command != null && Element.Command.CanExecute(null))
           {
               Element.Command.Execute(null);
           }
 
           Element.NotifyValueChanged();
        }
 
        void slider_ValueChanging(object sender, EventArgs e)
        {
            Element.LeftValue = (float)Control.LeftValue;
            Element.RightValue = (float)Control.RightValue;
        }

The complete code can be found at GitHub, https://github.com/johankson/flipper

June 29, 2015 7:15 GMT

Guide to Add Windows Phone to Xamarin.Forms 1.3+ Projects

I am a huge fan of Xamarin Studio and live inside of it around 50% of my development time. When I need to do library or Windows development though I head over to my good friend Visual Studio. Luckily the same exact project and solutions open in either IDE so it makes syncing with GitHub extremely easy. When I start up a Xamarin.Forms project I usually do it from Visual Studio so it spins up an iOS, Android, and Windows Phone Project. However, there are times that I am in XS, which doesn’t create the Windows Phone project so I need to add it after. Rob Gibbens wrote a great guide on adding Windows Phone projects to Xamarin.Forms in this case, but it is for the older Xamarin.Forms model pre 1.3. It is still a great guide and my guide follows this closely but updated with the new Application class requirements. Additionally, since Rob’s post we did release support for Windows Phone/Store RT apps and that process was documented as well, however Silverlight was left out, so let’s do it!

Going into this you will need at least Windows 8 and the Windows Phone SDK for Windows Phone 8.0 Silverlight.

Add Windows Phone Project

This is probably the easiest part of the process as all you need to do is right click on your Solution node and select Add -> New Project… From there you will need to find the Blank App (Windows Phone Silverlight) option under Installed -> Visual C# -> Store Apps -> Windows Phone Apps -> Blank App (Windows Phone Silverlight).

I personally name it: ProjectName.WinPhone and I turn OFF App Insights. You will then be prompted to select which version of Windows Phone to use. Simply select Windows Phone 8.0.

Restore NuGet Packages

You can always manually search for Xamarin.Forms in the NuGet Package manager, however it is easiest to actually right click on the SOLUTION node and select Manage NuGet Packages for Solution… This will allow you to see ALL NuGet packages installed in your projects and add them into your Windows Phone project. Simply Find Xamarin.Forms in the list, select Manage, and check ProjectName.WinPhone.

You may have additional NuGets installed so be sure to add those to your Windows Phone Project as well.

Fix Toolkit.Content

Xamarin.Forms uses the all powerful WPToolkit for some of its controls. When we added the Xamarin.Forms NuGet it also installed the WPToolkit NuGet and some new images were added under Toolkit.Content. We must select all of the files in this folder and mark the Build Action as Content and the Copy to Output directory to Copy always.

Add Portable Class Library or Shared Project Reference

Of course now we need to add in our shared code. Simply right click on the Windows Phone project’s references and find your “ProjectName” portable class library or Shared Project.

Modify MainPage.xaml

Xamarin.Forms 1.3 changed the normal flow of Xamarin.Forms applications include the Windows Phone’s main page, which is now inherits from FormsApplicationPage. We will now add in a custom xmlns of forms and then inherit from FormsApplicationPage:

Ensure you change “ProjectName” with your actual project name.

Modify MainPage.xaml.cs

Of course there is a bit of code behind to modify in the MainPage.xaml.cs to reference this new FormsApplicationPage and also call the LoadApplication of Xamarin.Forms. Simply replace the entire class with the following:

Ensure you change “ProjectName” with your actual project name.

You should be all set at this point with your Windows Phone project ready to go!