February 08, 2016 7:03 GMT

Contest: Show Us Your Favorite C# 6 Feature

C# 6 includes a wealth of new features to make you a more productive developer, simplify your code, and vastly increase readability. This builds on an already great foundation that makes C# the best language for mobile development, such as easy asynchronous operations with async/await, generics support, and more.

If you use Xamarin Studio or Visual Studio to build applications, you’re already using C# 6, so you can start incorporating these features into your applications today! In this contest, we invite you to share your favorite C# 6 feature in action.

How to Enter

To enter, tweet a photo of your favorite C# 6 feature being used in your code, along with the hashtags #Xamarin and #CSharp, as seen below:
 

Prize

The first 50 participants with a valid entry will receive an adorable plush Xamarin code monkey!

Xamarin code monkey hard at work on his own tiny Macbook

Need some ideas?

Check out Xamarin University’s “What’s New in C# 6” video, or pick from one of the features listed below:

  • Expression-bodied functions
  • String interpolation
  • Null-conditional operators (elvis operators)
  • Auto properties
  • Property initializers
  • Using static
  • Nameof expressions
  • Index initializers
  • Exception filters

Rules

All submissions must be made by Monday, February 22 at 12 pm EST. A valid entry consists of a tweet containing the hashtags above, along with an image of your favorite C# 6 feature in action on your mobile application. The first 50 submissions with a valid entry will receive a plush Xamarin code monkey. To be eligible, you must follow @XamarinHQ to enable us to DM you for private-follow up. There is no purchase necessary to enter the “Show Us Your Favorite C# 6 Feature” contest.

The post Contest: Show Us Your Favorite C# 6 Feature appeared first on Xamarin Blog.

February 07, 2016 2:50 GMT

The Case of REST & Azure Resource Manager APIs

There are two kinds of people in this world. One who love ready made SDKs and then there are others who love to work on pure REST APIs. I’m from the 1st category. :)

The reason behind using SDKs is they include pure abstracted API calls. For example, if you use Active Directory Authentication Library (ADAL), it has AcquireTokenAsync method. This method, if you call, takes just couple of lines of code and makes your life much more easier.

However, behind the scenes, this method does a lot of stuff. For example, in case of Windows apps: calling WebAuthenticationBroker, launching Web UI, handling app navigation, etc. Similarly, it does same thing, in iOS and Android. But that entire code base is repetitive in every app which is going to use Active Directory for login. Now, one may ask, why so many calls are made just to authenticate and acquire token or as we progress through this blog post, why so many calls are required to perform basic operations. The answer lies in purity of REST APIs. And ADAL makes life easier here by providing one method doing all this for you while abstracting all the details.

When I was working on my blog post Monitor Azure Resource Usage and Predict Expenses, there was no SDK available for Azure Resource Manager (ARM) and the old API was not an ideal way to handle Resource Management APIs.

So, I had to write an app from scratch to get ARM working in my sample and here my friend Gaurav Mantri (@gmantri) helped me a lot. Gaurav founded Cloud Portam, which helps to manage resources in Azure like Storage, Search, etc… Thanks to him, I could understand the flow and I’m going to put it here on this blog post.

Step 1: Authenticate with Common

ARM allows you to manage resources within subscription and subscription is now part of your Active Directory. So, the first thing that you need to do is to authenticate with right Active Directory. This is simple if you’ve just one subscription and one Active Directory in your subscription, but if you’ve multiple subscriptions/active directories, you may want to iterate through them and get separate access tokens. To avoid this, first we hit the ‘common’ endpoint and then get the Tenants available.

Step 2: Get Tenants

As a user, your user account may be associated with multiple active directories. A tenant is nothing but an active directory to which you have access. Here, in this step we get all active directories first by calling below method. Later on we’ll try to fetch subscription (if available) from each directory.

Step 3: Get Subscriptions

Once we get tenants, each tenant may have subscription on which we may want perform some actions. To do so, we pass each tenant ID from GetTenants() to this method and acquire new token silently (without login prompt)

Step 4: Call ARM APIs

In order to perform management operations on an Azure Subscription, a user must be authenticated and authorized. Authentication part is handled by Azure Active Directory. There is a one to many relationship between an Azure AD and Azure Subscription. i.e. an Azure AD can be used as an authentication store for many Azure Subscriptions however authentication for an Azure Subscription can happen only with a single Azure AD. Once a user is authenticated with an Azure AD, next step is to find out a list of Azure Subscriptions the logged in user has access to. This is what we’re doing in this step. What a user can do in each of these subscriptions (i.e. the authorization part) can be accomplished by using Azure Resource Manager (ARM) API’s Role-based access control (RBAC).

Now you can replace your code in Step 4 to manage or monitor resources in your Azure subscription, but the flow will not change. The entire list of APIs covering resources and possible operations on them is available here

I hope this post will helps you to understand the model behind ARM API calls.

Namaste,
Mayur Tendulkar

February 05, 2016 10:20 GMT

Podcast: Simplify Your Code With C# 6

This week on the Xamarin Podcast, Mike and I are joined by James Montemagno to overview all of the fantastic features introduced in C# 6 to simplify your code and bring readability to a new level.

Subscribe or Download Today

Knowing the latest in .NET, C#, and Xamarin is easier than ever with the Xamarin Podcast! The Xamarin Podcast is available from iTunes, Stitcher, and SoundCloud. Do you have an interesting story, project, or advice for other .NET mobile developers? If so, we’d love to share it with the Xamarin community! Tweet @pierceboggan or @MikeCodesDotNet to share your blog posts, projects, and anything else you think other mobile developers would find interesting. Be sure to download today’s episode breaking down all the awesome features of C# 6, and don’t forget to subscribe!

The post Podcast: Simplify Your Code With C# 6 appeared first on Xamarin Blog.

February 05, 2016 8:48 GMT

Report an Exception with Xamarin Insights Contest Winner

Proactively monitoring the health of your mobile apps is crucial to ensuring a bug-free, positive user experience. Xamarin Insights makes it extremely simple to do this by identifying what issues real users are facing and how to fix them. Xamarin Insights was promoted to general availability in Xamarin 4, giving all Xamarin subscribers access to free crash reporting with detailed crash reports and crashed-user identification.

Two weeks ago, we invited you to start monitoring the health of your apps by adding Xamarin Insights to your mobile app(s) with just a few lines of code and tweeting an unexpected exception discovered with your free crash reporting.

There were some exceptional entries, but I’m happy to announce that the winner of the “Report an Exception with Xamarin Insights” contest, and brand new Xamarin swag bag, is Ken Pespisa for his submission:


A big thank you from all of us here at Xamarin to everyone who entered the “Report an Exception with Xamarin Insights” contest and shared how Xamarin Insights came to the rescue for their mobile app! Everyone who submitted a valid entry will be receiving 10 Xamarin Test Cloud hours to help test their mobile apps on thousands of devices.

Didn’t get a chance to enter in this contest?

Be sure to follow us on Twitter @XamarinHQ to keep up with Xamarin announcements, walkthroughs, case studies, contests, and more!

The post Report an Exception with Xamarin Insights Contest Winner appeared first on Xamarin Blog.

February 05, 2016 1:30 GMT

Weekly Xamarin Newsletter Issue #78

Easy App Theming with Xamarin.Forms
Pierce Boggan, from Xamarin Inc., shows how you can switch your apps theme with Xamarin.Forms.

Xamarin vs. Hybrid HTML: Making the Right Choice for the Enterprise
Courtney Witmer, from Xamarin Inc., puts up the webinar recording.

Stretchy UITableView Headers with Xamarin
Mike James is keen on the parallax header and shows you how to do it.

Turn Events into Commands with Behaviors
David Britch, from Xamarin Inc., starts giving commands to his View Models.

Announcing the Behaviors Toolkit for Xamarin!
Tom helps you add common and reusable interactivity to your Xamarin applications with minimal code.

Announcing SlideOverKit for Xamarin.Forms
Michael Ridland released a premium component for Xamarin.Forms.

Building a Xamarin Android app – part 4
Jim Bennett gets into binding his view models to the UI.

Microsoft VS Dev Essentials + Xamarin University
Bryan Costanich, from Xamarin Inc., announces free access to Xamarin University for Dev Essential members.

 

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

February 04, 2016 7:49 GMT

Consulting Partners Bring Real-World Experiences to Xamarin Evolve 2016

Since launching the Xamarin Consulting Partner program in 2012, the network has grown to over 350 partners worldwide. We’re excited to showcase the expertise from the following partners at Xamarin Evolve 2016 and we encourage you to attend to learn from these successful companies.

Zühlke: Is Your App Secure?

There’s a lot of discussion about security on the web, Kerry W Lothrop, Lead Software Architect, Zuehlke Groupbut what about app security? What do developers need to look out for when attempting to write a secure app? How should we handle sensitive data? What should we consider when designing an API consumed by a mobile app?

Kerry W Lothrop, Lead Software Architect at Zuehlke Group will demonstrate the different security aspects that Android and iOS developers should be aware of, the corresponding infrastructure to consider at the beginning of their projects, and some techniques to help ensure a secure mobile app.

Magenic: Understanding Implications of Build Options

Xamarin.iOS and Xamarin.Android have several build optionsKevin Ford, Mobile Practice Lead, Magenic that can have a large impact on runtime performance, compile times, and even the size of an app binary. What changes when I switch between linker options or select the SGen generational garbage collector? Should I enable incremental builds? We’ll compare these different options and discuss how to prepare your libraries for linking or dealing with a library that wasn’t. Understanding these build options can have huge benefits in the application you deploy.

Pariveda Solutions with their client Compass Professional Health Services: Healthcare Redefined: How We Used Xamarin to Make Healthcare Simpler and Smarter
MattLineberger

With the rise of mobile technology and consumers’ desire to manage their healthcare via mobile devices, Compass saw an opportunity to transform their business and brought in technology consulting firm Pariveda Solutions to help them execute their mobile-first vision.

Given the diversity of the Compass client base (from truck drivers to CEOs), the first design consideration was that the app had to support multiple devices from the beginning. Working with ParivedaCliff Sentell, CTO, Compass Professional Health Services, Compass was able to meet the goal of deploying across multiple devices, while also significantly reducing development time, lowering testing costs and enabling data backed decisions from analytics captured with Xamarin Insights.
 
 
 
You won’t want to miss the expertise shared by these partners at Xamarin Evolve 2016, so be sure to register today to reserve your spot!

Register Now

The post Consulting Partners Bring Real-World Experiences to Xamarin Evolve 2016 appeared first on Xamarin Blog.

February 03, 2016 9:33 GMT

Easy App Theming with Xamarin.Forms

Popular Twitter Client Tweetbot for iOS "Night Theme"Beautiful user interfaces sell mobile apps, and designing a successful user experience for your app is a great first step for success. But what about all of the little details that combine to create a fantastic design, such as colors and fonts? Even if you create what you believe to be the perfect design, users will often find something to dislike about it.

Why not let the user decide exactly how they would like their app to look? Many popular apps have taken this approach. Tweetbot has light and dark modes and the ability to change fonts to find the one that works best on the eyes during late-night Twitter sessions. Slack takes user customization to the next level by allowing users to customize the entire theme of the app through hexadecimal color values. Properly supporting theming also brings some tangible benefits to code, such as minimizing duplicated hardcoded values throughout apps to increase code maintainability.

Xamarin.Forms allows you to take advantage of styling to build beautiful, customizable UIs for iOS, Android, and Windows. In this blog post, we’re going to take a look at how to add theming to MonkeyTweet, a minimalistic (we mean it!) Twitter client, by replicating Tweetbot’s light and dark mode as well as Slack’s customizable theming.

Introduction to Resources

Resources allow you to share common definitions throughout an app to help you reduce hardcoded values in your code, resulting in massively increased code maintainability. Instead of having to alter every value in your app when a theme changes, you only have to change one: the resource.

In the code below, you can see several duplicated values that could be extremely tedious to replace and are ideal candidates for using resources:

Resources are grouped together and stored in a ResourceDictionary, a key-value store that is optimized for use with a user interface. Because a ResourceDictionary is a key-value store, you must supply the XAML keyword x:Key for each resource defined:

#33302E
White
24

You can define a ResourceDictionary at both the page and app-level, depending on the particular scope needed for the resource at hand. If a particular resource will be shared among multiple pages, it’s best to define it at the app-level in App.xaml to avoid duplication, as we do below with the MonkeyTweet app:


    
		
			#33302E
			White
        
    

Now that we have defined reusable resources in our application ResourceDictionary, how do we reference these values in XAML? Let’s take a look at the two main types of resources, StaticResource and DynamicResource, and how we can utilize them to add a light and dark mode to MonkeyTweet.

Static Resources

The StaticResource markup extension allows us to reference predefined resources, but have one key limitation: resources from the dictionary are only fetched one time during control instantiation and cannot be altered at runtime. The syntax is very similar to that for bindings; just set the property’s value to “{StaticResource Resource_Name}”. Let’s update our ViewCell to use the resources we defined:

Dynamic Resources

StaticResources are a great way to reduce duplicated values, but what we need is the ability to alter the resource dictionary at runtime (and have those resource updates reflected where referenced). DynamicResource should be used for dictionary keys associated with values that might change during runtime. Additionally, unlike static resources, dynamic resources don’t generate a runtime exception if the resource is invalid and will simply use the default property value.

We want MonkeyTweet’s user interface to be able to switch between light and dark modes at runtime, so DynamicResource is perfect for this situation. All we need to do is change StaticResources to DynamicResources. Updating our resources on-the-fly is super easy as well:

App.Current.Resources ["backgroundColor"] = Color.White;
App.Current.Resources ["textColor"] = Color.Black;

Users can now switch between a light and dark theme with the click of a button:
Monkey Tweet with a dark and light theme applied via dynamic resources.

Introduction to Styles

When building a user interface and theming an app, you may find yourself repeatedly configuring controls in a similar way. For example, all controls that display text may use the same font, font attributes, and size. Styles are a collection of property-value pairs called Setters. Rather than having to repeatedly set each of these properties to a particular resource, you can create a style, and then simply set the Style property to handle the theming for you.

Building Custom Styles

To define a style, we can take advantage of the application-wide resource dictionary to make this style available to all controls. Just like resources, each style must contain a unique key and target class name for the style. A style is made up of one or more Setters, where a property name and value for that property must be supplied. The TargetType property defines which controls the theme can apply to; you can even set this to VisualElement to have the style apply to all subclasses of VisualElement. Setters can even take advantage of resources to further increase maintainability.


    
		
			#33302E
			White
			
        	
        
    

We can apply this style by setting the Style property of a control to the name of the style’s unique key. All properties from the style will be applied to the control. If a property is explicitly defined on the control that is also part of a referenced style, the property set explicitly will override the value in the style.

Our style is a dynamic resource behind the scenes, so they can be altered at runtime. I’ve created a custom page that allows users to enter their own hexadecimal colors to theme MonkeyTweet thanks to Xamarin.Forms resources and styles:

Feb 03, 2016 15:34

Conclusion

In this blog post, we took a look at theming applications with the Xamarin.Forms’ styles by theming our MonkeyTweet application to have a customizable, user-defined theme. We only just scratched the surface of styling; there are lots of other cool things you can do with styling, including style inheritance, implicit styling, platform-specific styling, and prebuilt styles. Be sure to download the MonkeyTweet application to apply your own theme and see just how easy it is to build beautiful, themed UIs with Xamarin.Forms!

The post Easy App Theming with Xamarin.Forms appeared first on Xamarin Blog.

February 03, 2016 7:22 GMT

Live Webinar: Xamarin vs. Hybrid HTML: Making the Right Choice for the Enterprise

Selecting the right mobile platform for your enterprise can be a high-risk gamble that will affect thousands of your employees and millions of your customers. Building the right app will either digitally transform your business or derail your efforts and force you to start over while the industry and customers leave you behind.

The two leading choices for building cross-platform native apps are Xamarin or hybrid mobile solutions that utilize HTML and JavaScript. How do you know which option is the best fit for you? Which solution provides superior user experience (UX), performance, faster development time, full hardware access, and a lower TCO?

Magenic, a leading solution provider, built an enterprise-focused application using the Xamarin Platform and a hybrid HTML framework to quantitatively compare the differences between the two approaches. In this webinar, Steven Yi from Xamarin and Kevin Ford of Magenic will break down the essential advantages, roadblocks, and observations they found to help you make the best choice for your strategic mobile initiatives.

Sign up below to join us on Thursday, February 18, 2016 at 8:30 am PT / 11:30 am ET / 4:30 pm GMT.
 

Register

About the Speakers

Kevin Ford
Kevin Ford is the Mobile Practice Lead with Magenic, leading development with native mobile technologies, Xamarin, and Cordova. He has worked with application development using the Microsoft stack for over twenty years. He is an accomplished architect, speaker and thought leader.
 
 
Steven Yi, Xamarin
Steven Yi is the Head of Product Marketing at Xamarin. Prior to Xamarin he held senior leadership roles in product management and strategy for Microsoft Azure and Red Hat, as well as architecting and developing large-scale applications.

The post Live Webinar: Xamarin vs. Hybrid HTML: Making the Right Choice for the Enterprise appeared first on Xamarin Blog.

February 02, 2016 8:01 GMT

Turn Events into Commands with Behaviors

Utilizing data binding in mobile apps can greatly simplify development by automatically synchronizing an app’s data to its user interface with minimal set up. Previously, we looked at the basics of data binding, and then explored some more advanced data binding scenarios where values are formatted and converted as they are passed between source and target by the binding engine. We then examined a Xamarin.Forms feature called commanding, that allows data bindings to make method calls directly to a ViewModel, such as when a button is clicked.

In this blog post, I’m going to explore a Xamarin.Forms feature called behaviors, which in the context of commanding, enables any Xamarin.Forms control to use data bindings to make method calls to a ViewModel.

Introduction to Behaviors

Behaviors let you add functionality to UI controls without having to subclass them. Instead, the functionality is implemented in a behavior class and attached to the control as if it was part of the control itself. Behaviors enable you to implement code that you would normally have to write as code-behind, because it directly interacts with the API of the control in such a way that it can be concisely attached to the control and packaged for reuse across more than one app. They can be used to provide a full range of functionality to controls, from adding an email validator to an Entry, to creating a rating control using a tap gesture recognizer.

Implementing a Behavior

The procedure for implementing a behavior is as follows:

  1. Inherit from the Behavior<T> class, where T is the type of control that the behavior should apply to.
  2. Override the OnAttachedTo method and use it to perform any set up.
  3. Override the OnDetachingFrom method to perform any clean up.
  4. Implement the core functionality of the behavior.

This results in the structure shown in the following code example:

public class CustomBehavior : Behavior<View>
{
	protected override void OnAttachedTo (View bindable)
	{
		base.OnAttachedTo (bindable);
		// Perform setup
	}
	protected override void OnDetachingFrom (View bindable)
	{
		base.OnDetachingFrom (bindable);
		// Perform clean up
	}
	// Behavior implementation
}

The OnAttachedTo method is fired immediately after the behavior is attached to the UI control. This method is used to wire up event handlers or perform other set up that’s required to support the behavior functionality. For example, you could subscribe to the ListView.ItemSelected event and execute a command when the event fires. The behavior functionality would then be implemented in the event handler for the ItemSelected event.

The OnDetachingFrom method is fired when the behavior is removed from the UI control and is used to perform any required clean up. For example, you could unsubscribe from the ListView.ItemSelected event in order to prevent memory leaks.

Consuming a Behavior

Every Xamarin.Forms control has a behavior collection to which behaviors can be added, as shown in the following code example:

<Editor>
	<Editor.Behaviors>
		<local:CustomBehavior />
	</Editor.Behaviors>
</Editor>

At runtime the behavior will respond to interaction with the control, as per the behavior implementation.

Invoking a Command in Response to an Event

In the context of commanding, behaviors are a useful approach for connecting a control to a command. In addition, they can also be used to associate commands with controls that were not designed to interact with commands. For example, they can be used to invoke a command in response to an event firing. Therefore, behaviors address many of the same scenarios as command-enabled controls, while providing a greater degree of flexibility.

The sample application contains the ListViewSelectedItemBehavior class, that executes a command in response to the ListView.ItemSelected event firing.

Implementing Bindable Properties

In order to execute a user specified command, the ListViewSelectedItemBehavior defines two BindableProperty instances, as shown in the following code example:

public class ListViewSelectedItemBehavior : Behavior<ListView>
{
	public static readonly BindableProperty CommandProperty =
            BindableProperty.Create ("Command", typeof(ICommand), typeof(ListViewSelectedItemBehavior), null);
	public static readonly BindableProperty InputConverterProperty =
            BindableProperty.Create ("Converter", typeof(IValueConverter), typeof(ListViewSelectedItemBehavior), null);
	public ICommand Command {
		get { return (ICommand)GetValue (CommandProperty); }
		set { SetValue (CommandProperty, value); }
	}
	public IValueConverter Converter {
		get { return (IValueConverter)GetValue (InputConverterProperty); }
		set { SetValue (InputConverterProperty, value); }
	}
    ...
}

When this behavior is consumed by a ListView, the Command property should be data bound to an ICommand to be executed in response to the ListView.ItemSelected event firing, and the Converter property should be set to a converter that returns the SelectedItem from the ListView.

Implementing the Overrides

The ListViewSelectedItemBehavior overrides the OnAttachedTo and OnDetachingFrom methods of the Behavior<T> class, as shown in the following code example:

public class ListViewSelectedItemBehavior : Behavior<ListView>
{
    ...
	public ListView AssociatedObject { get; private set; }
	protected override void OnAttachedTo (ListView bindable)
	{
		base.OnAttachedTo (bindable);
		AssociatedObject = bindable;
		bindable.BindingContextChanged += OnBindingContextChanged;
		bindable.ItemSelected += OnListViewItemSelected;
	}
	protected override void OnDetachingFrom (ListView bindable)
	{
		base.OnDetachingFrom (bindable);
		bindable.BindingContextChanged -= OnBindingContextChanged;
		bindable.ItemSelected -= OnListViewItemSelected;
		AssociatedObject = null;
	}
    ...
}

The OnAttachedTo method subscribes to the BindingContextChanged and ItemSelected events of the attached ListView. The reasons for the subscriptions are explained in the next section. In addition, a reference to the ListView the behavior is attached to is stored in the AssociatedObject property.

The OnDetachingFrom method cleans up by unsubscribing from the BindingContextChanged and ItemSelected events.

Implementing the Behavior Functionality

The purpose of the behavior is to execute a command when the ListView.ItemSelected event fires. This is achieved in the OnListViewItemSelected method, as shown in the following code example:

public class ListViewSelectedItemBehavior : Behavior<ListView>
{
    ...
	void OnBindingContextChanged (object sender, EventArgs e)
	{
		OnBindingContextChanged ();
	}
	void OnListViewItemSelected (object sender, SelectedItemChangedEventArgs e)
	{
		if (Command == null) {
			return;
		}
		object parameter = Converter.Convert (e, typeof(object), null, null);
		if (Command.CanExecute (parameter)) {
			Command.Execute (parameter);
		}
	}
	protected override void OnBindingContextChanged ()
	{
		base.OnBindingContextChanged ();
		BindingContext = AssociatedObject.BindingContext;
	}
}

The OnListViewItemSelected method, which is executed in response to the ListView.ItemSelected event firing, first executes the converter referenced through the Converter property, which returns the SelectedItem from the ListView. The method then executes the data bound command, referenced through the Command property, passing in the SelectedItem as a parameter to the command.

The OnBindingContextChanged override, which is executed in response to the ListView.BindingContextChanged event firing, sets the BindingContext of the behavior to the BindingContext of the control the behavior is attached to. This ensures that the behavior can bind to and execute the command that’s specified when the behavior is consumed.

Consuming the Behavior

The ListViewSelectedItemBehavior is attached to the ListView.Behaviors collection, as shown in the following code example:

<ListView ItemsSource="{Binding People}">
	<ListView.Behaviors>
		<local:ListViewSelectedItemBehavior Command="{Binding OutputAgeCommand}"
            Converter="{StaticResource SelectedItemConverter}" />
	</ListView.Behaviors>
</ListView>
<Label Text="{Binding SelectedItemText}" />

The Command property of the behavior is data bound to the OutputAgeCommand property of the associated ViewModel, while the Converter property is set to the SelectedItemConverter instance, which returns the SelectedItem of the ListView from the SelectedItemChangedEventArgs.

The result of the behavior being consumed is that when the ListView.ItemSelected event fires due to an item being selected in the ListView, the OutputAgeCommand is executed, which updates the SelectedItemText property that the Label binds to. The following screenshots show this:

ExecuteCommand

Generalizing the Behavior

It’s possible to generalize the ListViewSelectedItemBehavior so that it can be used by any Xamarin.Forms control, and so that it can execute a command in response to any event firing, as shown in the following code example:

<ListView ItemsSource="{Binding People}">
	<ListView.Behaviors>
		<local:EventToCommandBehavior EventName="ItemSelected" Command="{Binding OutputAgeCommand}"
            Converter="{StaticResource SelectedItemConverter}" />
	</ListView.Behaviors>
</ListView>
<Label Text="{Binding SelectedItemText}" />

For more information, see the EventToCommandBehavior class in the sample application.

Wrapping Up Behaviors

In the context of commanding, behaviors are a useful approach for connecting a control to a command. In addition, they can also be used to associate commands with controls that were not designed to interact with commands. For example, they can be used to invoke a command in response to an event firing. Therefore, behaviors address many of the same scenarios as command-enabled controls, while providing a greater degree of flexibility.

For more information about behaviors, see our Working with Behaviors document.

The post Turn Events into Commands with Behaviors appeared first on Xamarin Blog.

February 02, 2016 11:46 GMT

Announcing SlideOverKit for Xamarin.Forms

I’m very happy to announce XAM Consulting’s first Premium component release, SlideOverKit for Xamarin.Forms. As I’ve discussed before at XAM Consulting we have a goal to contribute to the Xamarin ecosystem and help companies build great things, our premium components are one part of this goal.

This component is something we’ve been working on for a while after being frustrated with the lack of high quality sliders in Xamarin.Forms.

This component is flexible enough to create any type of Slider you might like, some examples might be a Large Menu that slides from the top of the screen, a small draggable context menu from the right/bottom of the screen or even a right side master detail. There’s a large amount of options that you can tweak to allow you to get your menu looking just right. In this component we’ve done all the slider code in Native (eg we’ve done the hard native work), this means that the component is… 1) it’s super quick 2) you don’t need to use the slow Xamarin.Forms layouts 3) the touch/gesture support is very smooth.

In some ways we would love to give it away for free but after consideration we would prefer to offer a higher quality product with support rather than a half finished product with no support, hence why it’s a ‘Premium Component’. If you would like to read more about our thoughts in regards to pricing components please take a look at this blog post on Pricing Xamarin.Forms Components.

SlideOverKit is available in nuget right now and is available for purchase @ $100 USD. Please head over the the SlideOverKit for Xamarin.Forms website to get more details on how to get started. We have a github repository with a bunch of samples for the component.

Take a look below to see some of the awesome options available for the SlideOverKit.

So check it out SlideOverKit for Xamarin.Forms.








So check it out SlideOverKit for Xamarin.Forms.

The post Announcing SlideOverKit for Xamarin.Forms appeared first on Michael Ridland.

February 01, 2016 7:59 GMT

Xamarin Events in February

Join one of these many user groups, conferences, webinars, and other events to help celebrate something we all love this February — native mobile development in C#!

February 2016 Banner
Here are just a handful of the many developer events happening around the world this month:

SWETUGG se

  • Stockholm, Sweden: February 2
  • Get Started Building Cross-Platform Apps with Xamarin (Xamarin MVP Johan Karlsson speaking)

XLSOFT Japan Japan

  • Tokyo, Japan: February 5
  • Xamarin with NuGet and CI

Xamarin Costa Rica Mobile .NET Developer Group cr

  • San Jose, Costa Rica: February 8
  • Introduction to Mobile Development with C#/.NET and Xamarin

Gauteng Xamarin User Group za

  • Johannesburg­, South Africa: February 9
  • Xamarin 4: Everything You Need to Build Great Apps

South Florida Xamarin User Group us

  • Fort Lauderdale, FL: February 9
  • Demo Day: Share Your Xamarin Apps

Mobile-Do Developers Group do

  • Santo Domingo, Dominican Republic: February 12
  • Data Persistence with SQLite and SQLite.Net

Concord .Net User Group us

  • Concord, NH: February 16
  • Cross-Platform .NET Development with Carl Barton – Xamarin MVP

Orlando Windows Phone User Group us

  • Orlando, FL: February 17
  • Xamarin.Forms for .NET Developers

.NET Coders Brazil

  • São Paulo, Brazil: February 18
  • Deliver Top Quality Apps Using Xamarin Test Cloud and Xamarin Test Recorder

Boston Mobile C# Developers’ Group us

  • Boston, MA: February 18
  • Powerful Backends with Azure Mobile Services

Mobilize Enterprise Applications with Oracle and Xamarin au

  • Melbourne, Australia: February 23
  • Build Better, More Engaging Mobile Apps with Oracle and Xamarin in Melbourne

Chicago .NET Mobile Developers us

  • Chicago, IL: February 24
  • FreshMvvm : A Lightweight MVVM Framework for Xamarin.Forms

Mobilize Enterprise Applications with Oracle and Xamarin au

  • Sydney, Australia: February 26
  • Build Better, More Engaging Mobile Apps with Oracle and Xamarin in Sydney

XHackers in

  • Bangalore, India: February 27
  • MVVM & DataBinding + Intro to Game Dev with Xamarin

Didn’t see an event in your area?

Not to worry! Check out the Xamarin Events Forum for even more Xamarin meetups, hackathons, and other events happening near you.

Interested in getting a developer group started?

We’re here to help! Here are a few tools to help you out:

Also, we love to hear from you, so feel free to send us an email or tweet @XamarinEvents to let us know about events in your neck of the woods!

The post Xamarin Events in February appeared first on Xamarin Blog.

February 01, 2016 12:34 GMT

Stretchy UITableView Headers with Xamarin

The Yahoo News Digest app includes a couple of interesting user interface elements that I wanted to use within my own apps. The feature that I was most keen to recreate was the stretching UITableViewHeader. Its an effect seen in lots of iOS (sometimes referred to as a parallax header). As Beer Drinkin is going to support multi-tasking on iOS, I needed to ensure my implementation continues to support Storyboards and Auto Layout. Fortunately it proved very simple to get everything setup. In this blog post I’ll be sharing how I went about implementing it

beerdrinkinStretchy

Setting up the Storyboard

Adding a header view

To get started I opened my existing Storyboard and selected the UIViewController that requires the tableview header. In my case the scene (or view controller) isn’t a UITableViewController because I require a floating ‘Check in’ button to be visible at all times. Its worth noting that all the steps in the tutorial work with both UITableViewControllers and UIViewControllers.

Screen Shot 2016-02-01 at 11.36.06

Once I had the storyboard loaded, I dragged a UIView from the toolbox and made sure to insert it above the UITableViewCells as a the header view for the table. I then added a UIImageView to the new UIView and set its constraints to be 0,0,0,0. This way when the parent view (the UIView) resizes, the UIImageView will resize as well. I also made sure to set the UIImageView view mode property to Aspect Fit, which makes sure the image looks great no matter what size the view.

Screen Shot 2016-02-01 at 11.39.13

Adding some C#

Adding the resize code

If I were to have run this now, the table header would be displayed but wouldn’t resize with scroll events. To add scaling, I needed to add a code into my ViewController to setup the stretchy goodness that I wanted.

Because I use the header views height in a number of locations throughout the beer description view controller, I went ahead and created a variable rather than scattering magic numbers over my class.

private nfloat headerViewHeight = 200;

Managing the header view

To allow me to manage the table header, I needed to remove it from the UITableView and keep it as a variable for use later. To do this I created a variable in the beer description view controller.

private UIView headerView;

When we load the view controller, we’ll want to set our headerView variable and then set the UITableViews header property to null. This means the tableview has no header view to manage anymore, instead I’ve taken control of the view which allows me to ensure it resizes correctly as the table view scrolls.Despite having just removed the header view from the UITableView, I actually want to go ahead and add it to the table view hierarchy (but not as the header view property of the UITableView)

 headerView = tableView.TableHeaderView;
 tableView.TableHeaderView = null;
 tableView.AddSubview (headerView);
 tableView.ContentInset = new UIEdgeInsets (headerViewHeight, 0, 0, 0);
 tableView.BackgroundColor = UIColor.Clear;

Listening to TableViewDidScroll

In order to successfully respond to the DidScroll event of the UITableViewSource, I’ll need to create an event in the table views delegate. This is because of an issue with the UITableView DidScroll event not firing when a delegate has been set.

public override void Scrolled (UIScrollView scrollView)
{
    DidScroll ();
}

public event DidScrollEventHandler DidScroll;

We can now hook up the table DidScroll event with a small piece of logic for resizing the view.

//Update Tableview
tableView.Source = new BeerDescriptionDataSource(ref cells);
var deleg = new DescriptionDelegate (ref cells);
deleg.DidScroll += UpdateHeaderView;
tableView.Delegate = deleg;

tableView.ReloadData ();
View.SetNeedsDisplay ();
//...
void UpdateHeaderView ()
{
    var headerRect = new CGRect (0, -headerViewHeight, tableView.Frame.Width, headerViewHeight);
    if (tableView.ContentOffset.Y &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt; -headerViewHeight)
    {
        headerRect.Location = new CGPoint (headerRect.Location.X, tableView.ContentOffset.Y);
        headerRect.Size = new CGSize (headerRect.Size.Width, -tableView.ContentOffset.Y);
    }
    headerView.Frame = headerRect;
}

Conclusion

Its very easy to use this approach to add resizing animations to any number of controls within your UITableView. My favourite part of this solution is that it works perfectly across all iOS devices and doesn’t force me to drop support of Autolayout.


February 01, 2016 9:41 GMT

How to solve Xamarin.Forms android build error after updated to Forms 2.0+

Exception while loading assemblies: System.IO.FileNotFoundException: Could not load assembly 'Microsoft.Windows.Design.Extensibility, Version=4.3.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Perhaps it doesn't exist in the Mono for Android profile?

If you updated the nuget packages for Xamarin Forms to 2.0+ and the android project stops to build there are a simple solution. Just delete the references which ends with .Design. In my project it was: Xamarin.Forms.Core.Design, Xamarin.Forms.Xaml.Design and Xamarin.Android.Support.Design. I have read about a solution to add the assemblies Microsoft.Windows.Design.Extensibility and System.Xaml. I don’t know if it will work, I think to delete the .Design references is a better solution so I never tried to add those assemblies.

January 29, 2016 8:02 GMT

Don’t Miss Big Medium’s Josh Clark at Xamarin Evolve 2016

Josh Clark HeadshotIf anyone has secrets to spill about how to make your next mobile app a hit, Josh Clark is your man, and he’ll be sharing some of them with you at Xamarin Evolve 2016, the world’s largest cross-platform mobile development conference!

Josh has written several books on mobile app design, including Designing for Touch and Tapworthy: Designing Great iPhone Apps, and he founded his agency Big Medium to help brands such as Samsung, Time Inc, eBay, and Entertainment Weekly get the most out of their mobile strategies.

Josh joins a great and growing lineup of industry-leading speakers, including MythBusters’ Grant Imahara, and legendary technical author Charles Petzold, as well as several other Xamarin gurus. Tickets are going fast, so be sure to register today!
 

Register Now

The post Don’t Miss Big Medium’s Josh Clark at Xamarin Evolve 2016 appeared first on Xamarin Blog.

January 29, 2016 4:50 GMT

Microsoft VS Dev Essentials + Xamarin University

Xamarin University CrestMicrosoft launched its Visual Studio Dev Essentials program at Microsoft Connect (); 2015, and today we’re excited to announce that we’re giving Dev Essentials members free access to select Xamarin University content!

Visual Studio Dev Essentials is available to all developers free of charge. Through the program, developers receive various benefits, including developer tools, software, cloud service credits, as well as education and training. Now, it’s even better because it includes Xamarin University class recordings and materials from our Xamarin Mobile Fundamentals course.

Xamarin University includes 60+ courses taught live by mobile experts on a wide range of topics and out of those, we’ve carefully selected a subset of the curriculum for the Dev Essentials program, making the 60-75 minute lecture recordings available for on-demand viewing at any time.

Our initial course line-up* includes the following lectures and all of the associated materials, including interactive lab projects:

  • Intro to iOS 101 and 102
  • Intro to Android 101 and 102
  • Intro to Xamarin.Forms
  • 2 guest lectures from industry luminaries (Azure Mobile Services and Intro to Prism)

*We may alter the content from time to time

It’s simpler than ever for developers to get started with Visual Studio and Xamarin! Xamarin is bundled with VS 2015 to give teams mobile templates from day one, easily connects to Azure for critical mobile functionality, and now developers can access industry-leading training for rapid onboarding and skill development.

Visual Studio Dev Essentials activation page

We look forward to powering even more successful mobile apps for the .NET community!

Get Started

Visit Visual Studio Dev Essentials to sign up and activate your Xamarin University Mobile Training benefits.

Learn more about Xamarin University at xamarin.com/university.

The post Microsoft VS Dev Essentials + Xamarin University appeared first on Xamarin Blog.

January 29, 2016 1:30 GMT

Weekly Xamarin Newsletter Issue #77

Xamarin’s Newest Most Valued Professionals
Joseph Hill, from Xamarin Inc., announces the new rockstars of Xamarin.

Getting Started with Azure Mobile Apps’ Easy Tables
James Montemagno, from Xamarin Inc., has fallen in love with ‘Easy Table’.

Gone Mobile 29: Push Notifications
Greg Shackles and Jon Dick go over everything from PushSharp to APNS and GCM.

James Montemagno: TintColor & Selected Tab Images in Xamarin.Forms iOS
James Montemagno, from Xamarin Inc., gives the TabbedPage a small tweak and polish.

Shared Projects or PCL?
Miguel de Icaza, from Xamarin Inc. shares his view on the PCL vs. Shared Project debate.

Quick & Dirty Cookies Access (iOS & Android)
Wislon built his own cross-platform cookie access in Xamarin.Forms.

Tables Full of Cheese: An Intro to Azure Table Service and Xamarin
Matthew Soucoup, from Codemill Technology shares his whirlwind tour of Azure Table Store.

Sport: A Beautiful Open Source Consumer App
Rob DeRosa, from Xamarin Inc., shows off a beautiful UI with Xamarin.Forms.

Simplifying Events with Commanding
David Britch, from Xamarin Inc., explores Commanding in Xamarin.Forms.

Implement a ShakeDetector in your Xamarin.Android application
Tom plays around with the sensors on his Android device.

XAML Relative Binding trick
Corrado helps the MVVM newcomers with an intricate situation that requires stealing.

Toasts Plugin For Xamarin And Windows
Adam Pedley adds some toast notifications to Xamarin.Forms.

CI With VSTS And Xamarin
Rasmus Tolstrup Christensen makes sure that it works on your machine.

Data Binding Tips and Tricks for iOS, Android, and Windows
David Britch, from Xamarin Inc., simplifies development with databinding in Xamarin.Forms.

Los Angeles Department of Building and Safety Goes Mobile with Xamarin
Jo Ann Buckner, from Xamarin Inc., shows us another Xamarin.Forms success.

Portable Class Library (PCL) vs Shared Projects
Adam Pedley adds his opinion to the PCL vs Shared debate.

 

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

January 29, 2016 7:01 GMT

How to price Xamarin.Forms components

This post is primarily documenting my thought process when trying to come up with pricing for two premium components that we’re about to release at XAM Consulting. We’re very excited about releasing these components. We’re looking forward to contributing to the Xamarin ecosystem and helping developers build great things. Many companies I’ve worked for have clearly stated that their whole company has been built on the back of great component vendors like DevExpress and Telerik. It’s pretty amazing to know that something you’ve built has also helped build an amazing company or change the world.

The first component we are releasing is called SlideOverKit. This is a powerful component that allows you to slide over from anywhere on the screen, with nice smooth animations. It can be used to create slide menus such as a Right Side Master Detail, Mini Context Menu’s or the display of Contextual Information. The key advantage of this menu is that internally we’ve built the code using Native APIs and therefore it is has the advantages of not only being incredibly quick but it also supports swipe/touch gestures. (Note* that when I refer to Native APIs, that’s only from our internal perspective, from a developer’s perspective the component is built completely from Xamarin.Forms). To illustrate its performance and ease of use, I’ve included some samples below with the SlideOverKit component.

The second component, called TEditor, is a rich/html text editing component designed for Xamarin.Forms. It is intended to be used for the editing, importing and exporting of HTML documents. As such, it supports the majority of rich text editing functions such as Bold, Italic to text color. Like the first component, it takes only a few lines of code to include this component in a project.

So what price do I sell it for?

This is a very hard question; if you price it too high then people won’t see it’s value and if you price it too low then you won’t have enough money to continue it’s development. It’s important to me that we have continued development on the components that we sell. Nobody wants a component vendor that’s not committed.

To investigate further, I researched the components supplied within the ecosystem. There’s the many big vendors like DevExpress and Telerik, who sell their components at over $1000 per year. I’ve also know about the MR.Gestures component developed by Michael Rumpler, who sells it at a very affordable $10. That’s a huge difference in pricing, so I wanted to reach out to Michael and see if he could provide any insights based on his experiences. Michael mentioned that the amount of demand was much less than was suggested on the uservoice website for his component. He also mentioned that at the price of $10, combined with the amount of sales, it wasn’t anywhere near the amount of effort he had to put in to develop it. Michael confirmed a few suspicions that I had:

1) there’s likely to be a much lower demand than you think for a component and

2) there’s a reason companies like telerik must charge so much for their components. eg. component development is hard and it’s very time consuming.

I’ve been in software long enough to know there’s a lot of hidden time and costs in software. At a minimum you need to calculate:

  • Initial development costs
  • Costs in writing documentation
  • Costs in handling support requests (per sale)
  • Maintenance development costs

Xamarin.Forms is a fast moving target, not only because of the speed of development from the Xamarin team, but also because of the rapidly changing underlying platforms (iOS, Android and Windows). The other issues we also encounter is that most components need to use the Native APIs on the platforms.

So far we’ve spent ~150 hours on each of the components, and on top of this there is a yearly maintenance of ~50 hours. Adding these up, based on an estimate of $75 per hour development cost, leads to a cost of $11,250 in the first year and $3,750 each year after that.

It would be nice if the components were to break even in the 24 months. In order to calculate this, we need to guesstimate the amount of sales each component will generate each year. Given that each component is a niche component inside Xamarin.Forms, which is a niche in Xamarin, which is a niche in Native Apps, which is a niche in the software world. I’m really not expecting a huge amount of sales each year, for SlideOverKit. I don’t think that I would expect more than 50-100 sales per year. Assuming 75 sales in 12 months, the costs are $15,000 in the first 2 years, then $15,000 / 150 = $100 per component. Now the RichTextEditor is an even more Niche component, which I’m only expecting a few sales each per year. Assuming 10 sales per year, then $15,000 / 20 = $750.

Shouldn’t it be free and open source like in XLabs and other components?

Open source software is great, I get a lot from the open source community and love contributing to the open source community, I spent a lot of time developing the FreshMvvm Framework. The problem with projects like XLabs, is that many of the components are not feature complete or are half finished (or are implemented on only a single platform). The reason for this is that most of us contributors to XLabs, also have full-time jobs and can only work on the project in our spare time.

XLabs works great if you’re an expert in Forms, Android, or iOS and don’t mind getting your hands dirty delving deep into code. Many developers and business don’t have all day and night to be working on building components.

So I wanted to put in the effort up front so that I can help time-poor developers and businesses, so we invest in developing production ready components that are easy to use, feature rich, well documented and production ready and developers can just build awesome stuff.

If you would like early access to any of the components please feel free to contact me anytime.

Thanks

Michael

 

 

The post How to price Xamarin.Forms components appeared first on Michael Ridland.

January 27, 2016 8:03 GMT

Tables Full of Cheese: An Intro to Azure Table Service and Xamarin

In our last post on Azure Storage we looked at how to save large amounts of binary data to a BLOB from a Xamarin Forms app. We also took a quick look at what Azure Storage’s offering all provided, how to create a service account, and then how to access the BLOB service portion of it via the WindowsAzure.Storage NuGet package.

Today we’re going to turn our attention to another offering inside Azure Storage – that of Table Storage. We’re going to answer the question… what exactly is Table storage? Then we’ll look at why would somebody want to use Table Storage within a mobile app. Finally, we’ll explore ways in which a developer can integrate Table Storage into an Xamarin app.

So without further delay…

What Is Azure Table Storage?

Table Storage is a key/value store that can be used to store massive amounts of structured data within Azure. It is not, however, a relational database. Each “row” (or entity as we’ll refer to it from now on) in a table can have different columns from one another. In other words, it’s a schema-less NoSQL database.

Let’s take a closer look of the structure of Table Storage.

  • Storage Account – This is the top-level entry point for all of Azure Storage’s services.
  • Table – A storage account can contain one or many tables. Tables, obviously, are a means to store and group data.
  • Entity – Akin to an individual row of a table. An entity will be identified by 2 columns, a partition key and a row id (and those columns must exist). An entity also will contain a last modified date (again this is a system column and must exist, and in fact cannot be changed by code). The partition key and row id serve as the “Key” portion of the key/value pair storage. The value portion is made up of a collection of properties and can be whatever we want them to be – as long as it can be serialized to JSON or XML. (And the individual properties can differ from one entity to another within the same table).

Entities / Tables / Storage Account

Entities / Tables / Storage Account


It is worth noting that the “partition key” and the “row id” portion of the entity must be unique across the table in which they exist. (That makes sense considering they do make up the “key” of the key/value pair). But since they are unique, that means we’ll be able to use them to query and obtain results in a speedy manner. Just querying off the “partition key” will return all the entities within that table partition. Whereas querying for both parts of the key will zero in on the entity exactly. (It’s also possible to query off the properties within the value portion as well, but obviously that won’t be as performant).

Pricing

Table Storage, for the most part, does not cost a whole lot. The pricing is based off of how much data you’re storing, how many requests you’re making against it, the type of replication, and then how often data is transferred outside of the region in which it is stored.

As a practical example – in the Central US – to store 1 GB of data against 100,000 requests / month has a cost of … $0.07. That’s right – 7 cents. Not too bad. (Then again SQL server would run $4.98 for roughly the same amount, not terrible and not apples to apples, but definitely more than 7 cents).

Why Use Table Storage In A Mobile App?

There are several reasons one might consider using Table Storage instead of a regular relational database within a mobile app. We won’t get into the full relational vs. NoSQL debate here, but let’s just say in some situations it can be very useful to be able to store different types of object schemas within a single table without having to modify the database schema at all.

Some of the other benefits that Azure Table storage gives us are, as mentioned above, the amount of storage for the price paid is very good. Table Storage also provides optimistic concurrency – meaning that multiple clients will be able to edit the same entity at once, but the last one to commit the changes will get an exception automatically from the server – we don’t have to do the checking.

Table Storage is also very performant – if the tables are designed appropriately, queries are able to be run across millions of entities very quickly. Also Table Storage gives us the ability to batch multiple operations up together to run at once. This way we can support offline editing and then send everything up to the cloud at one time instead of piecemeal.

Some of the downsides though are that the client library does not support on device storage. So we’re going to have to design our own solution. If supporting offline editing, we will also need to manually keep track of what transactions need to be sync’d to the cloud. (Azure Mobile Services kind of spoils us in handling it all).

All in all – if you’re considering a NoSQL storage option for your app and you need the ability to have access to a massive amount of storage for a very reasonable price – Azure Table Storage is something you’ll want to consider.

Integrating Into A Xamarin App

Now to the part we’ve all been waiting for – integrating Table Storage into a Xamarin app! The simple app that we’re going to build will retrieve reviews of cheeses based on email address. (It’s always an app around cheese with me, isn’t it)? The app will also allow you to enter a new review and have that persisted in table storage. The idea is that there will be hundreds and thousands of reviews – and we need an easy and cheap way to store them … so Table Storage is the way to go.

You can find all of the example code and a working Xamarin Forms app in my CheesedTable GitHub repo.

Installing

The very first thing that needs to be done is to setup a storage account within Azure. See the last post on BLOB storage (under Setup) for the instructions.

The next thing to do is add the NuGet to our Xamarin project. In the NuGet package manager search for

WindowsAzure.Storage
and make sure you have pre-release selected. As of this post, the latest version is 6.2.2-preview.
WindowsAzure.Storage 6.2.2-preview NuGet

WindowsAzure.Storage 6.2.2-preview NuGet


One particular thing to note is that this package is PCL profile 111 – that means if you’re going to use it within a PCL project – it will need to be compatible with profile 111 as well.

Ok – the NuGet package is installed, all we need is the URL and username & password and we can start querying data, right? Not quite … first we need to handle some security.

Shared Access Signature

The Shared Access Signature, or SAS is one means by which access is granted to objects within Azure’s Storage Account. As with BLOBs, we need to generate a token that provides a certain level of access (read, add, update, delete) to certain objects, that is valid for a certain time period. Then with this token we’ll be able to connect to Table Storage from the device.

The following is a snippet of node.js code that will generate a sas for table storage. One thing to note is this code is based off the “azure” v0.10.6 package. This code will not work as is in a default installation of the legacy Azure Mobile Services. (Can you tell I was bit by that once)?

// This is a "restify" get listener - what matters is the code in the middle
server.get('/sas', function (req, res) {
    var azure = require('azure');

    // First 2 parameters are account name and key for your service
    var tableService = azure.createTableService('', '', 'https://xxx.table.core.windows.net/');

    // creating the table we want the token for - on the off chance it's not there yet
    tableService.createTableIfNotExists('reviews', function (err, result, response) {
        if (!err) {
            var startDate = new Date();
            var expiryDate = new Date(startDate);
            expiryDate.setMinutes(startDate.getMinutes() + 100);
            startDate.setMinutes(startDate.getMinutes() - 100);

            var sharedAccessPolicy = {
                AccessPolicy: {
                    Permissions: 'raud', // requesting read, add, update and delete
                    Start: startDate,
                    Expiry: expiryDate
                },
            };

            // "reviews" is the table name
            var tableSAS = tableService.generateSharedAccessSignature('reviews', sharedAccessPolicy);

            // just returning it - not important, just get it back to the client
            res.writeHead(200, { 'Content-Type': 'text/json' });
            res.write(tableSAS);
            res.end();
        }  
    });
});

Ok .. that little snippet of code will get us a token that will authenticate us for the rest of our adventure!

Modeling The Entities

If there’s a motto for the things that you can put into Azure Table Storage it should be …

… if you can serialize it, you can store it …

Remember that we somehow need to transfer our objects up the Azure cloud – which means they need to get serialized to XML or JSON along the way. So as long as the properties on our objects are serializable, then we’ll be able to store them in Table Storage.

Otherwise the classes we want to put into Table Storage are plain old POCO classes – deriving from

TableEntity
.

The biggest thing you’ll need to remember is to set the

PartitionKey
and
RowKey
properties. Combined those essentially form the primary key of the entity and are required.

The Cloud Client and Cloud Tables.

The gateway to the clouds, so to speak, goes through an object called the

CloudTableClient
. The main purpose of this object is to take the table storage’s URL, the credentials we generate from the token above, and then provide access to various tables through the
GetTableReference
function.

The

GetTableReference
returns a
CloudTable
object … and it’s with that we can start doing interesting things with.

Reading Data

There are 2 ways we can get entities out of Table Storage – we can either query it out and get a result set, or we can go after a single entity exactly. Let’s talk about querying first.

Querying Tables

Unfortunately getting at the data stored within the Table Storage isn’t as simple as just writing a SQL query or using LINQ against the

CloudTable
. Instead we have to create and populate a
TableQuery
object and then have our
CloudTable
execute that.

As you may suspect – the

TableQuery
object gives us a means by which to specify a where clause. But the where clause isn’t the normal SQL where syntax … in fact it’s just a string and looks suspiciously like OData, but there are helper functions available so we don’t have to remember that syntax.

TableQuery.GenerateFilterCondition
and several of its strongly typed related cousins (such as
TableQuery.GenerateFilterConditionForBool
) exist to help us.

These functions take 3 parameters, the first being the property to apply the condition to, the second being the operator (equal, less than, etc) enumerated by the

QueryComparisons
class, and the final being the value.

Using that, you’ll end up with something of the following:

string whereClause =  TableQuery.GenerateFilterCondition ("PartitionKey", QueryComparisons.Equal, emailAddress);

That’s the filter portion of the query … but how do we execute it? We need to use the

CloudTable.ExecuteQuerySegmentedAsync
function. This function will execute the passed in
TableQuery
, and will only return 1000 entities at a time.

If you need to get more than 1000 entities out, that function also takes a

TableContinuationToken
object. The return from the execute query contains another
TableContinuationToken
, and you can continually pass the new result in to grab the next 1000 rows as needed.

When put all together a query against an Azure Storage Table looks like this:

public async Task<List<CheeseReviewEntity>> SearchCheeseReviewsAsync (string emailAddress)
{
    List<CheeseReviewEntity> results = new List<CheeseReviewEntity> ();

    try {
        if (client == null)
            await InitializeCloudClientAsync ();
                
        var table = client.GetTableReference (reviewTable); // reviewTable is just the table's name

        // Generate a query
        var query = new TableQuery<CheeseReviewEntity> ();
                            
        // Looking for an exact match
        query.Where (TableQuery.GenerateFilterCondition ("PartitionKey", QueryComparisons.Equal, emailAddress));

        // This version of the Table Storage NuGet only has the option
        // of returning a subset of the entire entity set at a time. 
        // We could use the TableContinuation token along with a loop to get
        // everything out - but we'll just go with the first return
        TableContinuationToken continueToken = null;

        // Execute the query
        var s = await table.ExecuteQuerySegmentedAsync (query, continueToken);

        continueToken = s.ContinuationToken;

        var searchResults = s.Results;

        results.AddRange(s.Results);

    } catch (Exception ex) {
        var exMsg = ex.ToString ();
    }

    return results;
}

Loading A Single Entity

Know exactly what you’re looking for? Then you don’t have to bother with the query operations and their (somewhat convoluted) syntax at all! Instead we can use a

TableOperation
instead. (We’ll see more of these when we start to write data).

There are several different types of

TableOperation
’s we can choose from – and one just happens to be Retrieve. The Retrieve will zero in on the exact entity we want and return it. All we need to do is specify the unique identifier for the table – if you remember the partition key and the row key.

From there we just invoke the

ExecuteAsync
function on the
CloudTable
and the entity we want will be returned.

An example of getting at a single entity looks like:

public async Task<CheeseReviewEntity> GetCheeseReview (string emailAddress, Guid rowKey)
{
    CheeseReviewEntity returnCheese = null;

    try {
        if (client == null)
            await InitializeCloudClientAsync ();

        // Define a table operation that grabs the exact partition & row key
        var op = TableOperation.Retrieve<CheeseReviewEntity> (emailAddress, rowKey.ToString ());

        // Get a table reference
        var table = client.GetTableReference (reviewTable);

        // Execute the table operation
        var result = await table.ExecuteAsync (op);

        // Parse the return - will need to cast it
        if (result.Result != null)
            returnCheese = (CheeseReviewEntity)result.Result;

    } catch (Exception ex) {
        returnCheese = null;
    }

    return returnCheese;
}

We’re on a roll now … but what good is getting data out if there’s nothing in Table Storage to begin with?

Writing Data

As mentioned above the

TableOperation
object plays a role in writing data to Table Storage. There are several static methods to create
TableOperation
objects used for data modification. All of these take a
TableEntity
or our model class, as input.

Operation Description
Delete Deletes the entity matching the partition and row key
Insert Create a new entity
InsertOrMerge Merges uploaded entity with existing otherwise insert
InsertOrReplace Replaces existing entity with uploaded otherwise insert
Merge Merge the uploaded entity with the existing
Replace Replace the uploaded entity
A common area of confusion is the difference between Merge and Replace. Merge is updating the value portion of the entity with an object of the same type. A Replace operation is completely overwriting the value portion of the entity with an object of a different type. (So if we wanted to start uploading reviews for beer on top of existing ones for cheeses, we’d use the Replace operations – because the beer reviews would be completely different object types).

Once a

TableOperation
is obtained, all we need to do is use the
ExecuteAsync
function of the
CloudTable
and we’re good to go.

An example would look like the following:

public async Task<bool> SaveReviewAsync (CheeseReviewEntity entity)
{
    try {                           
        if (client == null)
            await InitializeCloudClientAsync ();
            
        // Define the insert operation
        var operation = TableOperation.InsertOrReplace (entity);

        // Get a reference to the review table
        var table = client.GetTableReference (reviewTable);

        // Execute the insert against the table
        var result = await table.ExecuteAsync (operation);

        return true;

    } catch (Exception ex) {
        return false;
    }
}

We can send more than one operation up in a single request as well. In order to do so we would create the

TableOperation
’s as above, but add them to a
TableBatchOperation
object.
TableBatchOperation
works just like an
IEnumerable
as far as adding things goes … then just have the
CloudTable.ExecuteAsync
work against the
TableBatchOperation
.

Design Considerations

We know how to get a security token … We can query … we can write … what else can be involved with Azure Table Storage?

Offline persistence? Ugh…

Luckily we have something at our fingertips which gives us a pretty darn good offline persistence layer for Table Storage, and it goes hand in hand with the key/value storage that Azure Tables does as well … that thing? Akavache!

We can use Akavache as an offline repository of our entities. Then within those entities we just need to keep track of what’s been sync’d with Azure and what hasn’t been. At appropriate times we sync – update Akavache – and off we go.

I’m making it sound easier than what it is – but Akavache really does give us a huge head start at implementing our own offline persistence without starting from scratch.

The other design considerations is to make sure our objects are serializable so they can be transmitted via JSON/XML, and to watch for areas where we can batch operations together.

Then there’s the best practices of table design … my blog posts are long and cover a lot of ground … but I won’t even attempt to cover that. This article from Microsoft does a great job.

Summary

The whirlwind tour of Azure Table Storage has come to an end. We covered a lot of ground in this post, including defining what Table Storage is and identifying its constituent parts. We then covered why we’d want to consider using a NoSQL solution that can hold massive amounts of data in a mobile application.

With the theory out of the way, we dove into how to actually use the

WindowsAzure.Storage
NuGet package from within a Xamarin solution. First up was how to download the package itself (remember PCL profile 111)! Then we looked at a way to generate a token to grant access to the table storage. After that we found out some ways to query and return entities. Finally we talked about the many ways to write entities back to Table Storage.

To wrap it all up, we touched a bit on how to handle offline data persistence with the little library that could … Akavache.

All in all, Table Storage is pretty cool, and not something that immediately comes to mind when thinking about NoSQL databases on devices – but it warrants a look.

Cover image via Wiki Media Commons: https://commons.wikimedia.org/wiki/File:Parmigiano_reggiano_factory.jpg
January 22, 2016 1:30 GMT

Weekly Xamarin Newsletter Issue #76

Syncing Files Between Devices with Azure File Sync
Nish Anil, from Xamarin Inc., shows how Azure makes difficult problems easy.

A Nicer Messaging Interface For Xamarin.Forms
Thomas Bandt finds a nicer and simpler way to send messages.

Use IDEA IDE for Android UI design with Visual Studio and Xamarin
Corrado shows you how to use IntelliJ for Android designs.

Custom made Xamarin.Forms radial progress control
Dot Jord builds an awesome circular progress control.

XFBehaviors: Open Source Xamarin.Forms behaviors library
Yeray codes up the most common behaviors in the new XFBehaviors library.

Xamarin.Forms Complete
Jason Smith, from Xamarin Inc., is on a tear with his new blog. Check it out.

Xamarin: Data Binding Tips and Tricks for iOS, Android, and Windows
David Britch, from Xamarin Inc., wants to help you out and save you some work with bindings.

FreshMvvm 1.0 Preview Release
Michael Ridland is releasing FreshMvvm 1.0

Using custom fonts on iOS and Android with Xamarin.Forms
Gerald Versluis, with a few warnings, shows you how to do it.

 

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

January 20, 2016 7:10 GMT

FreshMvvm 1.0 Preview Release

Since the first release of FreshMvvm it’s been a wild ride, the up take of FreshMvvm has been very impressive it’s really good to see others having success using FreshMvvm. While I’ve been using and loving FreshMvvm for a long long time, even since before it was called FreshMvvm, it’s great to see others also enjoying the Framework.

Since this release has a few large features and breaking changes I’ve decided bump the version up to 1.0 preview. Please see below of a description of the features.

Multiple Navigation Services

It’s always been possible to do any type of navigation in FreshMvvm, with custom or advanced scenarios were done by implementing a custom navigation service. Even with this ability people found it a little hard to do advanced navigation scenarios in FreshMvvm. After I reviewed all the support questions that came in for FreshMvvm I found that the basic issue people had was they wanted to be able to use our built in navigation containers multiple times, two primary examples are 1) within a master detail having a navigation stack in a master and another in the detail 2) The ability to push modally with a new navigation container. In order to support both these scenarios I concluded that the FreshMvvm required the ability to have named NavigationServices so that we could support multiple NavigationService’s.

Using multiple navigation containers

Below we’re running two navigation stacks, in a single MasterDetail.

var masterDetailsMultiple = new MasterDetailPage (); //generic master detail page

//we setup the first navigation container with ContactList
var contactListPage = FreshPageModelResolver.ResolvePageModel<ContactListPageModel> ();
contactListPage.Title = "Contact List";
//we setup the first navigation container with name MasterPageArea
var masterPageArea = new FreshNavigationContainer (contactListPage, "MasterPageArea");
masterPageArea.Title = "Menu";

masterDetailsMultiple.Master = masterPageArea; //set the first navigation container to the Master

//we setup the second navigation container with the QuoteList 
var quoteListPage = FreshPageModelResolver.ResolvePageModel<QuoteListPageModel> ();
quoteListPage.Title = "Quote List";
//we setup the second navigation container with name DetailPageArea
var detailPageArea = new FreshNavigationContainer (quoteListPage, "DetailPageArea");

masterDetailsMultiple.Detail = detailPageArea; //set the second navigation container to the Detail

MainPage = masterDetailsMultiple;

PushModally with new navigation stack

//push a basic page Modally
var page = FreshPageModelResolver.ResolvePageModel<MainMenuPageModel> ();
var basicNavContainer = new FreshNavigationContainer (page, "secondNavPage");
await CoreMethods.PushNewNavigationServiceModal(basicNavContainer, new FreshBasePageModel[] { page.GetModel() }); 

//push a tabbed page Modally
var tabbedNavigation = new FreshTabbedNavigationContainer ("secondNavPage");
tabbedNavigation.AddTab<ContactListPageModel> ("Contacts", "contacts.png", null);
tabbedNavigation.AddTab<QuoteListPageModel> ("Quotes", "document.png", null);
await CoreMethods.PushNewNavigationServiceModal(tabbedNavigation);

//push a master detail page Modally
var masterDetailNav = new FreshMasterDetailNavigationContainer ("secondNavPage");
masterDetailNav.Init ("Menu", "Menu.png");
masterDetailNav.AddPage<ContactListPageModel> ("Contacts", null);
masterDetailNav.AddPage<QuoteListPageModel> ("Quotes", null);
await CoreMethods.PushNewNavigationServiceModal(masterDetailNav);

Custom IOC Container

The second major request for FreshMvvm 1.0 was to allow custom IOC containers. In the case that your application already has a container that you want to leverage.

Using a custom IOC container is very simple in that you only need to implement a single interface.

public interface IFreshIOC
{
    object Resolve(Type resolveType);
    void Register<RegisterType>(RegisterType instance) where RegisterType : class;
    void Register<RegisterType>(RegisterType instance, string name) where RegisterType : class;
    ResolveType Resolve<ResolveType>() where ResolveType : class;
    ResolveType Resolve<ResolveType>(string name) where ResolveType : class;
    void Register<RegisterType, RegisterImplementation> ()
        where RegisterType : class
        where RegisterImplementation : class, RegisterType;
}

And then set the IOC container in the System.

FreshIOC.OverrideContainer(myContainer);

Breaking Changes

Please remember whenever you register a IFreshNavigationService it now has to have a name.

FreshIOC.Container.Register<IFreshNavigationService> (this, Constants.DefaultNavigationServiceName);

Please find this pre-release in nuget. – https://www.nuget.org/packages/FreshMvvm/1.0.0-pre1

FYI – This nuget is a pre-release nuget and you’ll need to have the ‘pre-release’ option selected on nuget.

The main repo for FreshMvvm can be found on github – https://github.com/rid00z/FreshMvvm.

Please post any issues on the github repository.

Thanks

Michael

 

The post FreshMvvm 1.0 Preview Release appeared first on Michael Ridland.

January 20, 2016 12:00 GMT

Using Effects

With the release of Xamarin.Forms 2.1.0-pre1 we have introduced the new Effects API. Effects are methods for applying runtime changes to renderers for Views. This post will focus on advanced applications of effects for complicated use cases. Along the way I will point out areas where things could be drastically simplified for non-reusable scenarios.

However, I want to stress this, Effects are designed to be highly reusable. If an effect solves a problem, it can likely be applied to your app. If an Effect you wrote solved a problem for you, you could likely share that with others having the same problem. However if sharing Effects is going to be made easy, there needs to be a method to the madness. This post is attempting to show one approach to solving the madness.

public class ShadowEffect : PlatformEffect
{
	protected override void OnAttached ()
	{
		UpdateSize ();
		UpdateColor ();
		UpdateOpacity ();
	}

	protected override void OnDetached ()
	{
		Container.Layer.ShadowOpacity = 0;
	}

	protected override void OnElementPropertyChanged (PropertyChangedEventArgs e)
	{
		Debug.WriteLine (e.PropertyName);
		if (e.PropertyName == ViewExtensions.HasShadowProperty.PropertyName) {
			UpdateOpacity ();
		} else if (e.PropertyName == ViewExtensions.ShadowColorProperty.PropertyName) {
			UpdateColor ();
		} else if (e.PropertyName == ViewExtensions.ShadowSizeProperty.PropertyName) {
			UpdateSize ();
		}
	}

	private void UpdateOpacity ()
	{
		Container.Layer.ShadowOpacity = ViewExtensions.GetHasShadow (Element) ? 1 : 0;
	}

	private void UpdateColor ()
	{
		var color = ViewExtensions.GetShadowColor (Element);
		Container.Layer.ShadowColor = color.ToCGColor ();
	}

	private void UpdateSize ()
	{
		Container.Layer.ShadowRadius = (nfloat)ViewExtensions.GetShadowSize (Element);
	}
}

Whew, thats a monster! Just so we’re clear it could have looked like this:

public class ShadowEffect : PlatformEffect
{
	protected override void OnAttached ()
	{
		Container.Layer.ShadowOpacity = 1;
		Container.Layer.ShadowColor = UIColor.Black.ToCGColor;
		Container.Layer.ShadowRadius = 6;
	}

	protected override void OnDetached ()
	{
		Container.Layer.ShadowOpacity = 0;
	}
}

Writing the effect this way is MUCH simpler, but also removes any chance of making it configurable and greatly reduces the re-usability for more than just the obvious reasons of no longer being parameterized. This is approximately what most of the older CustomRenderer approaches looked like when we were looking into this issue.

The ShadowEffect is created subclassing from PlatformEffect in the platform specific codebase. Like custom renderers, the implementations of PlatformEffects lives in the platform specific codebase, however the API for a Effect is identical across platforms, just deriving from PlatformEffect<T, T> with different generic parameters. One major difference of note is that Effects do not have type information about the Container/Control/Element they are attached to, this is because they can be attached to any Element. An effect needs to be able to either gracefully degrade or throw an exception when attached to an Element it doesn’t support.

There are two important attributes to be set on any library containing an Effect.

  • [assembly: ResolutionGroupName ("YourCompany")] : This is used to set a company wide namespace for your effects and prevents collisions with other effects with the same name. You can use the same group name in multiple assemblies.
  • [assembly: ExportEffect (typeof (ShadowEffect), "ShadowEffect")] : This exports the effect with a unique ID which we will use along with the group name to locate the effect.

Simple usage

Adding an effect to view at runtime is easy:

var button = new Button { Text = "I have a shadow" };
button.Effects.Add (Effect.Resolve ("YourCompany.ShadowEffect"));

If you don’t export an effect for a particular platform, Effect.Resolve will return a non-null value which does effectively nothing. This makes handling cross-platform fixes that are unique to individual platforms much easier, but comes with a tiny memory penalty.

This is the point where we get off the boring train and get onto the hype train with a side of this-is-just-my-opinion soup. There is a much better way to do things with effects, which I hinted at above.

All aboard the awesome train

public static class ViewEffects
{
	public static readonly BindableProperty HasShadowProperty =
		BindableProperty.CreateAttached ("HasShadow", typeof (bool), typeof (ViewEffects), false, propertyChanged: OnHasShadowChanged);

	private static void OnHasShadowChanged (BindableObject bindable, object oldValue, object newValue)
	{
		var view = bindable as View;
		if (view == null)
			return;

		var hasShadow = (bool)newValue;
		if (hasShadow) {
			view.Effects.Add (new ShadowEffect ());
		} else {
			var toRemove = view.Effects.FirstOrDefault (e => e is ShadowEffect);
			if (toRemove != null)
				view.Effects.Remove (toRemove);
		}
	}

	public static readonly BindableProperty ShadowSizeProperty =
		BindableProperty.CreateAttached ("ShadowSize", typeof (double), typeof (ViewEffects), 0d);

	public static readonly BindableProperty ShadowColorProperty =
		BindableProperty.CreateAttached ("ShadowColor", typeof (Color), typeof (ViewEffects), Color.Default);

	public static void SetHasShadow (BindableObject view, bool hasShadow)
	{
		view.SetValue (HasShadowProperty, hasShadow);
	}

	public static bool GetHasShadow (BindableObject view)
	{
		return (bool)view.GetValue (HasShadowProperty);
	}

	public static void SetShadowSize (BindableObject view, double size)
	{
		view.SetValue (ShadowSizeProperty, size);
	}

	public static double GetShadowSize (BindableObject view)
	{
		return (double)view.GetValue (ShadowSizeProperty);
	}

	public static void SetShadowColor (BindableObject view, Color color)
	{
		view.SetValue (ShadowColorProperty, color);
	}

	public static Color GetShadowColor (BindableObject view)
	{
		return (Color)view.GetValue (ShadowColorProperty);
	}

	class ShadowEffect : RoutingEffect
	{
		public ShadowEffect () : base ("Xamarin.ShadowEffect")
		{
			
		}
	}
}

Okay this looks like a lot of code, and it kind of is, but really we are just looking at 3 attached BindablePropertys. Nothing scary really, some static getters and setters. The only complex code is the OnHasShadowChanged which simply adds or removes the effect based on the value of the attached property. Lastly the code uses a RoutingEffect rather than directly calling Effect.Resolve just to make the removal process easier since there is no compile time access to the type information for the platform specific Effect.

Usage then looks like this:

<Button local:ViewEffects.HasShadow="True" 
        local:ViewEffects.ShadowColor="#222222" 
        local:ViewEffects.ShadowSize="4" />

or even better, use it in Style that you can apply to any/all Buttons:

<Style TargetType="Button">
  <Style.Setters>
    <Setter Property="local:ViewExtensions.HasShadow" Value="True" />
    <Setter Property="local:ViewExtensions.ShadowColor" Value="#232343" />
    <Setter Property="local:ViewExtensions.ShadowSize" Value="5" />
  </Style.Setters>
</Style>

Now you’re writing effects like a boss.

January 20, 2016 12:00 GMT

Control Templates

Xamarin.Forms 2.1.0 has introduced ControlTemplates. For the uninitiated or unaware, Control Templating is a mechanism that allows separation of the logical view hierarchy from the visual hierarchy. Another way to think of it is a template that produces the visual hierarchy for your control or page. The concept can be confusing at first, however it is extremely powerful once understood and is best learned by example.

A simple control template

To make a Control Template first we need a view which can be templated. Xamarin.Forms currently provides ControlTemplate properties on the following types:

  • ContentPage
  • ContentView
  • TemplatedPage
  • TemplatedView

The differences between each of these views is unimportant at this early stage, so we will work with the simplest, a TemplatedPage.

public partial class LoginPage : TemplatedPage
    {
        public LoginPage ()
        {
            InitializeComponent ();

            // because its a demo damnit
            BindingContext = new LoginPageViewModel ();
        }
    }

And we will go ahead and apply a Style which we are fetching from our application resource dictionary

<?xml version="1.0" encoding="utf-8" ?>
<TemplatedPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="TemplatingDemo.Views.LoginPage"
             Title="{Binding Title}"
             Style="{StaticResource LoginPageStyle }">
  <!--Remove Alt from above to use the other Style. This could also be set by implicit style-->
</TemplatedPage>

LoginPageStyle is defined inside the App.xaml resource dictionary

<ControlTemplate x:Key="LoginTemplate">
  <StackLayout VerticalOptions="CenterAndExpand" Spacing="20" Padding="20">
    <Entry Text="{TemplateBinding Username}" Placeholder="Username" />
    <Entry Text="{TemplateBinding Password}" Placeholder="Password" />
    <Button Command="{TemplateBinding Command}" Text="Click Here To Log In" />
  </StackLayout>
</ControlTemplate>

<Style TargetType="views:LoginPage" x:Key="LoginPageStyle">
  <Style.Setters>
    <Setter Property="ControlTemplate" Value="{StaticResource LoginTemplate}" />
  </Style.Setters>
</Style>

We now have enough context to evaluate what is happening here. The TemplatedPage has a ControlTemplate property which is being set via a Style named LoginPageStyle. Inside of the ControlTemplate there are items using a new syntax called TemplateBinding.

<Entry Text="{TemplateBinding Username}" Placeholder="Username" />

It should look similar because it works almost identically to a Binding, however the Source of the Template binding is always defined to be the Templated Parent, which in this case is the LoginPage. So what is it binding to? Good question, because some code was left out. The LoginPage exposes bindable properties for the template to bind to.

public partial class LoginPage : TemplatedPage
    {
        public LoginPage ()
        {
            // SNIP
        }

        public static readonly BindableProperty UsernameProperty =
            BindableProperty.Create ("Username", typeof (string), typeof (LoginPage), null, BindingMode.TwoWay);

        public string Username
        {
            get { return (string)GetValue (UsernameProperty); }
            set { SetValue (UsernameProperty, value); }
        }

        // Other properties defined here as well, snipped for brevity
    }

In the end we get a page that looks like this:

Control Template Result

In effect then the Views inside the ControlTemplate are bound to values on the LoginPage which are in turn bound to the ViewModel in the normal fashion you would normally bind something. This might seem a bit heavy for this example, and to be honest it is.

Why go through all the trouble?

There are several scenarios where this technique enables you to do things that were previously quite difficult. Mostly it comes down theming and making things beautiful. With ControlTemplates pages containing standardized content, your app can be easily themed and re-themed at runtime to have to different looks and feels while still presenting the exact same information. Just apply a different style with a different ControlTemplate and it looks brand new!

It is also worth noting that while this example looked into TemplatedPage, TemplatedView/ContentView offer much more flexibility and composability because they are Views and not full size pages. This means it is much more likely to see them presenting similar/identical data but with different views.

Why introduce TemplatedView/Page?

TemplatedPage serves as a base class, replacing ContentPage as the most basic Page. Unlike ContentPage, TemplatedPage does not have a Content property. Therefor you cannot directly pack content into it. This means the only way to get content inside a TemplatedPage is to set the ControlTemplate, otherwise it will show up blank. The same is not true of a ContentPage, where the Content property can be assigned to as well as setting a ControlTemplate.

Setting both is where things start to get really interesting. If the ControlTemplate were modified to look like:

<ControlTemplate x:Key="LoginTemplate">
  <StackLayout VerticalOptions="CenterAndExpand" Spacing="20" Padding="20">
    <Entry Text="{TemplateBinding Username}" Placeholder="Username" />
    <Entry Text="{TemplateBinding Password}" Placeholder="Password" />
    <Button Command="{TemplateBinding Command}" Text="Click Here To Log In" />
    <ContentPresenter />
  </StackLayout>
</ControlTemplate>

And instead apply it to a ContentPage, the ContentPage.Content would end up inside the ContentPresenter in the ControlTemplate. The ControlTemplate effectively serves as an intermediate layer for the ContentPage and its Content.

There are lots of other neat things that can be done with ControlTemplates, and I’m sure many others will beat me to pointing them out, but I will try to hit some of the major ones as I find time.

January 19, 2016 12:00 GMT

PCL or Shared Project?

Since the dawn of time man has been faced with one question. Should I use PCL’s libraries for my Xamarin.Forms projects, or should I use a Shared project? I’m here to tell you the answer is PCL, it is the way, the truth, and the light. Friends don’t let friends use shared projects.

Okay so thats a bit strong but in general if you don’t know what you should do, go PCL. If you have a strong reason to use a shared project, sure, but otherwise go PCL, your lack of #ifdef and spaghetti code will thank me later. Among other things, PCL will ensure that code you write is going to be portable not just to all current platforms, but any future platforms we might support as well.

Also I want to make sure everyone knows PCL is pronounced Pickle. Thats all.

January 18, 2016 12:00 GMT

Compound Animations

Animations in Xamarin.Forms work in basically the same manner all animations systems do. At the core is a timekeeper, called the Ticker which gives callbacks with timestep values, those timesteps are fed into a Tweener which then calls whatever callbacks the animation has registered with tweened values, finally the callbacks update properties on the Element. The end result is properties are being updated at about 60hz.

On top of this system are implemented some basic animations as extension methods on Element: FadeTo, TranslateTo, ScaleTo and so on. These accomplish about 90% of any animation needed by an app, however sometimes you just need to do something special. A complex animations containing multiple stages.

Enter Xamarin.Forms.Animation

The animation class provides the basis for all Xamarin.Forms animations, as well as the capacity to compound them together. It serves as both low level tweener and storyboard. A basic animation wont need to use storyboarding. (It is worth noting this animation can be done much more simply with RotateTo, this is here for demo purposes!)

button.Clicked += (sender, args) => {
    var animation = new Animation(callback: d => button.Rotation = d, 
                                  start:    button.Rotation, 
                                  end:      button.Rotation + 360, 
                                  easing:   Easing.SpringOut);
    animation.Commit (button, "Loop", length: 800);
};

This produces the following animation.

The easing is what is providing the overshoot effect. This is nice, however if we want to add more complexity to the animation, we can do so by building a compound animation. Compound animations are constructed from multiple internal animations.

button.Clicked += (sender, args) => {
    // Dirty hack you probably shouldn't use
    var width = Application.Current.MainPage.Width;

    var storyboard = new Animation ();
    var rotation = new Animation (callback: d => button.Rotation = d, 
                                  start:    button.Rotation, 
                                  end:      button.Rotation + 360, 
                                  easing:   Easing.SpringOut);


    var exitRight = new Animation (callback: d => button.TranslationX = d,
                                   start:    0,
                                   end:      width,
                                   easing:   Easing.SpringIn);

    var enterLeft = new Animation (callback: d => button.TranslationX = d,
                                   start:    -width,
                                   end:      0,
                                   easing:   Easing.BounceOut);

    storyboard.Add (0, 1, rotation);
    storyboard.Add (0, 0.5, exitRight);
    storyboard.Add (0.5, 1, enterLeft);

    storyboard.Commit (button, "Loop", length: 1400);
};

Instead of creating a single animation, we create 4, an outer animation into which we pack 3 children. The first child, rotation, runs for the entire animation. exitRight runs for the first 50% of the animation as specified by the parameters 0, 0.5. The enterLeft animation runs for the final 50%. Unlike the rotation argument, here we always hardcoding the start value, so as the tweener ticks over from the previous animation to the next one, the button is getting warped from the right edge of the screen to the left. The final result looks like this!

Due to the way the rotation animation is coded, the button.Rotation value is increasing by 360 degrees every click. Worse if the button were double activated the button would become permanently stuck at an off angle as the value would be started from somewhere mid animation. For this reason it is generally advisable to have either the start or the end parameter be a hardcoded value. This prevents any screwy final states from occurring, like we do with the other animations.

Using the technique seen here it is possible to create a library of pre-built animation components which can be used to piece together more complex animations.

January 15, 2016 1:30 GMT

Weekly Xamarin Newsletter Issue #75

Geolocation for iOS, Android, and Windows Made Easy
Pierce Boggan, from Xamarin Inc., shows how easy it is to add Geolocation to your apps.

LayoutTo doesn’t do what you think it does
Jason Smith, the father of Xamarin.Forms, admits he screwed up!

Custom layouts with Xamarin.Forms, Part 1
Jason Smith, the father of Xamarin.Forms, starts his layout series.

Introduction to Data Binding
David Britch, from Xamarin Inc., gives you an alternative to the dark ages.

Building an Android app – part 1
Jim Bennett gets busy building the most amazing counter app ever!

Universal Windows Platform (UWP) App in Xamarin Forms
Adam Pedley is blogging about his experiance using UWP in Xamarin.Forms.

Revisiting Pixel Access in a Xamarin.Forms App – iOS
David Britch was busy over the holidays and cleans up his memory.

Connect with your users with Google Search and App Indexing
James Montemagno, from Xamarin Inc., helps you drive users back to your app.

TDD in Xamarin Studio – Live Coding FreshMvvm
Michael Ridland releases another video with new FreshMvvm features.

Think Hexagonal Architecture for Cross-Platform Mobile Applications
Chris Williams hopes you’ll ditch the layers and go with the hexagon.

Test Your Way to a Five-Star App
Pierce Boggan, from Xamarin Inc., covers everything you need to know about testing.

Adding Suggestions to Mobile Search with Azure Search
Mike James, from Xamarin Inc., creates vastly improved search experiences with his mobile apps.

 

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

January 14, 2016 12:00 GMT

Custom layouts with Xamarin.Forms, Part 2

Part 1

When it comes to Layout performance Xamarin.Forms contains a very young layout system. I will be the first to admit that it is not the most blazing fast layout system in the world, however I like to think it’s gotten to the point now where it is in the ballpark of acceptable. We are continuing to iterate on it and improve it with every cycle, and there is a lot of internal work going on to make sure that happens.

I want to digress slightly into what makes Layouts slow. In general layout performance issues arise when unbounded measure invalidation occurs. There are two key phases to this invalidation, and stopping the propagation earlier in the cycle results in better performance.

The Invalidation Phase

Invalidation Propagation

During the invalidation phase the each child informs the parent that it’s measured size might change on the next measure call. Essentially this call informs the parent that any caches of measure calls are no longer valid. There is opportunity at this point to short circuit the cycle if the parent knows that the child’s size will not change regardless of measurement results. An example of this would look like:

<Grid x:Name="parent">
	<Grid.RowDefinitions>
		<RowDefintion Height="50" />
	</Grid.RowDefinitions>
	<Grid.ColumnDefinitions>
		<ColumnDefintion Width="50" />
	</Grid.ColumnDefinitions>
	<Label Text="I am now a fixed size" />
</Grid>

No matter what the label measured size comes out to be, the Grid will always size it to be 50x50dp, so there is no need to propagate the event further up the hierarchy. More complex examples include using Star columns/rows when the Grid has a fixed size, or using ContentView’s with WidthRequest and HeightRequest set on the child. However if you are not careful when crafting a Xamarin.Forms app, it is possible to allow these events to propagate to the top of the hierarchy, which is seriously bad juju. I will be giving a talk on this very topic at Xamarin Evolve 2016.

The Layout Phase

Layout Propagation

During the Layout phase, all parents of children which have received an invalidation event will relayout their children. Invalidation is quite expensive as it can easily impact parts of the tree which were logically nowhere near the original invalidation point. Propagating will stop if and only if the a child is layed out to the same size it was before the cycle began. This will exclude that part of the subtree from the rest of the layout cycle.

Unfortunately this is the most expensive possible place to have optimization taking place, it is significantly faster to prevent propagation in the first place.

Caching Measurement Results

The most important optimization to perform is the caching of measurement results. This prevents the layout from having to remeasure every time OnSizeRequest is called. Building on the result from last time:

readonly Dictionary<Size, SizeRequest> measureCache = new Dictionary<Size, SizeRequest> ();

protected override SizeRequest OnSizeRequest (double widthConstraint, double heightConstraint)
{
	// Check our cache for existing results
	SizeRequest cachedResult;
	var constraintSize = new Size (widthConstraint, heightConstraint);
	if (measureCache.TryGetValue (constraintSize, out cachedResult)) {
		return cachedResult;
	}

	var height = 0;
	var minHeight = 0;
	var width = 0;
	var minWidth = 0;

	for (int i = 0; i < Children.Count; i++) {
		var child = (View) Children[i];
		// skip invisible children

		if (!child.IsVisible) 
			continue;
		var childSizeRequest = child.GetSizeRequest (double.PositiveInfinity, height);
		height = Math.Max (height, childSizeRequest.Minimum.Height);
		minHeight = Math.Max (minHeight, childSizeRequest.Minimum.Height);
		width += childSizeRequest.Request.Width;
		minWidth += childSizeRequest.Minimum.Width;
	}

	// store our result in the cache for next time
	var result = SizeRequest (new Size (width, height), new Size (minWidth, minHeight));
	measureCache[constraintSize] = result;
	return result;
}

Cached results must be cleared whenever the measurement of the layout is invalidated by any means.

protected override void InvalidateMeasure ()
{
	measureCache.Clear ();
	base.InvalidateMeasure ();
}

Cached results prevent propagation of the measure portion of the layout phase (which is the expensive part) and can result in dramatic speedups, especially in heavily nested scenarios. All default Xamarin.Forms layouts that benefit from caching already perform caching, so you would only need to implement this to add it to your own layout.

Future Improvements

Unfortunately when the original API for the layout system was designed some information that is useful for optimization was not passed into key methods. InvalidateMeasure does not pass along the reason for the invalidation, and even more important OnChildMeasureInvalidated does not pass along which child was invalidated. This has been resolved in internal API’s however exposing these publicly requires an API break. Therefor the intention is to fix this with 3.0.

In part 3 we’ll talk about animations inside of layouts.

January 14, 2016 12:00 GMT

LayoutTo doesn't do what you think it does

Okay I need to cop up to something here. I screwed up View.LayoutTo hard. Unfortunately it is too late to fix for 2.0 without a big API break, so I am writing this page to explain what it does, what it is useful for, what you probably want instead, and how to get the effect you wanted from LayoutTo. I would not be surprised if we fix this in some fashion for 3.0.

First what it is meant for. LayoutTo is actually used cause a child to be layed out in a series of animated steps to a new location. This sounds useful but there are a couple important things to note.

  • It was only intended to be used by Xamarin.Forms.Layout subclasses, not externally.
  • It is stupidly exposed in the same way the other animation methods are.
  • It will initially appear to do what you want, but anything that triggers a relayout will cause your views position to reset to where it started.

Essentially the parent of the View you are calling LayoutTo on will not be aware of the translation/resize that happened, and will simply overwrite it at the next layout cycle (like when you rotate the device). This is because LayoutTo is calling the same method Layouts call to position children.

What it is useful for

LayoutTo is useful if you are a layout and you want to animate transitions between layout states that contain both size and position changes. None of the default layouts do this, but it is actually trivial to make them do so during the layout pass. This will be covered in the series I am writing on custom layouts in Xamarin.Forms. Though I suspect the LayoutTo method will eventually be moved to live somewhere less harmful.

What you want instead

Generally speaking what most users are looking to do is just translate things around the screen. This can be achieved with TranslateTo. TranslateTo is a post layout mechanism, and is thus respected by all layouts. There is also a solution if you want to both translate and resize, but that involves an absolute layout and is a topic I will resolve for a future post.

January 13, 2016 12:00 GMT

Custom layouts with Xamarin.Forms, Part 1

Writing custom layouts in Xamarin.Forms gives you control over exactly where and how your controls appear on screen. Further in complicated layouts this can result in improved overall performance as the absolute minimum amount of work required to produce the layout is performed. This series assumes you are familiar with Xamarin.Forms. We will be covering the following topics:

All layouts derive from the Xamarin.Forms.Layout class. This class provides the required mechanisms for adding and removing children internally as well as some key utilities for writing a layout. Further there is a generic subclass available, Xamarin.Forms.Layout<T> which provides a publicly exposed IList<T> Children that end-users can access. This collection can be typed to restrict the type of View the user can add, however most layouts should simply use Xamarin.Forms.Layout<View>.

We start by simply creating our class

public class CustomLayout : Layout<View>
{
	public CustomLayout ()
	{

	}
}

LayoutChildren

The layout must to override the LayoutChildren method. This method is responsible for positioning children on screen. For this example a very simple algorithm producing a horizontal stack will be used. We will assume we always want to vertically fill our children.

// This method has some errors, do not copy!
protected override void LayoutChildren (double x, double y, double width, double height)
{
	for (int i = 0; i < Children.Count; i++) {
		var child = (View) Children[i];
		// skip invisible children

		if(!child.IsVisible)
			continue;
		child.Layout (new Rectangle (x, y, 100, 100));
		x += 100;
	}
}

Directly calling into child.Layout does not respect child.VerticalOptions or child.HorizontalOptions, so instead of using child.Layout it is prefered to use a call to Layout.LayoutChildIntoBoundingRegion. Further our layout does not currently attempt to measure the children at all to figure out the size they wish to be, instead everything is just hardcoded to 100x100. Children can be measured by using the GetSizeRequest method, which will return both the desired size and the minimum size the child desires. The updated method looks like:

protected override void LayoutChildren (double x, double y, double width, double height)
{
	for (int i = 0; i < Children.Count; i++) {
		var child = (View) Children[i];
		// skip invisible children

		if(!child.IsVisible) 
			continue;
		var childSizeRequest = child.GetSizeRequest (double.PositiveInfinity, height);
		var childWidth = childSizeRequest.Request.Width;
		LayoutChildIntoBoundingRegion (child, new Rectangle (x, y, childWidth, height));
		x += childWidth;
	}
}

This method will automatically be called whenever the layout needs to be recomputed. If your layout consists of hardcoded or fixed size elements, hard code their sizes into this algorithm instead of measuring. GetSizeRequest calls are some of the most expensive calls that can be made, and are not predictable in their runtime as the subtree may be arbitrary complex. Fixing their size is a great way to get a performance boost if dynamic sizing is not required.

OnSizeRequest

Implementing OnSizeRequest is required to make sure the new layout is sized correctly when placed inside other layouts. During layout cycles this method may be called many times depending on the layout above it and how many layout exceptions are required to resolve the current layout hierarchy. It is therefor important to consider speed when implementing this function. Failure to implement this function will not always break your layout, particular if its always inside of parents which fix the child size anyway. However in most situations this is not the case.

protected override SizeRequest OnSizeRequest (double widthConstraint, double heightConstraint)
{
	var height = 0;
	var minHeight = 0;
	var width = 0;
	var minWidth = 0;

	for (int i = 0; i < Children.Count; i++) {
		var child = (View) Children[i];
		// skip invisible children

		if(!child.IsVisible) 
			continue;
		var childSizeRequest = child.GetSizeRequest (double.PositiveInfinity, height);
		height = Math.Max (height, childSizeRequest.Minimum.Height);
		minHeight = Math.Max (minHeight, childSizeRequest.Minimum.Height);
		width += childSizeRequest.Request.Width;
		minWidth += childSizeRequest.Minimum.Width;
	}

	return new SizeRequest (new Size (width, height), new Size (minWidth, minHeight));
}

By computing both a request size and a minimum size the layout is able to take part in overflow negotiation. This will allow for things like label truncation as needed or scrollable regions to be compressed and made to scroll.

That’s it! That’s a basic Xamarin.Forms custom layout. Of course this example is very simple and intended to provide you with the necessary context for the rest of the series.