August 26, 2016 5:29 GMT

More Xamarin Dev Days!

Xamarin Dev Days XDD Agendawere created to give developers the opportunity to learn native mobile development for iOS, Android, and Windows from the ground up. If you’ve been waiting to take the plunge into native mobile development, now is your opportunity!

The day starts off with a comprehensive introduction to building mobile apps with Xamarin before taking a look at creating cloud-connected mobile apps with Microsoft Azure. Spend the afternoon putting new skills into practice with a hands-on workshop to build your first mobile app for iOS, Android, and Windows. Have questions? Xamarin experts will be around to help debug code and guide you along.

The events have been a huge success thus far, covering over 55 cities in 25 countries in more than 10 languages, so we wanted to bring the fun to even more developers by announcing the next round of Xamarin Dev Days cities coming up. Here’s a list of the newest cities, but don’t forget to scope out the Xamarin Dev Days website for a full list of all of the Xamarin Dev Days cities around the world!

XDD India + Nish PIC

New Xamarin Dev Days Cities!

9/07: Namakkal, India
9/24: Tunis, Tunisia
9/24: Lisbon, Portugal
9/26: Santa Cruz de la Sierra, Bolivia
9/30: Birmingham, AL
10/1: San José, Costa Rica
10/15: Chennai, India
10/15: Las Vegas, NV
10/15: Indore, India
10/19: Mons, Belgium
10/22: Vancouver, BC
10/22: Vienna, Austria
10/22: Trujillo, Peru
10/22: Phoenix, AZ
11/04: Manchester, UK
11/12: Chicago, IL
11/12: Tokyo, Japan
11/19: Tampa, FL

You can also check out this sweet interactive map to help find a Xamarin Dev Days in your area:
 

Get Xamarin Dev Days in Your City

Interested in organizing an event locally? Apply as a Xamarin Dev Days host! We’ll provide you with everything you need for a fantastic Dev Days event in your town, including all of the speaker content and lab walkthrough, a hosting guidline to help organize your event, and assistance with registration and promotion.

Sponsoring Xamarin Dev Days

We’re working with tons of Xamarin Partners and community members around the world to help facilitate Xamarin Dev Days. If your company is interested in participating, apply to be a sponsor and get global recognition as well as access to our worldwide developer community!

The post More Xamarin Dev Days! appeared first on Xamarin Blog.

August 25, 2016 5:55 GMT

Continuous Integration for iOS Apps with Visual Studio Team Services

Visual Studio Team Services (VSTS) delivers services for teams to share code, track work, and ship software, including all of their mobile applications built with Xamarin. In the first post in this series, we automated a Xamarin.Android app in VSTS. We created our account, connected to our GitHub account, built and signed the app, and delivered it to HockeyApp for beta testers to start testing it. Today, we’re going to continue to automate the Coffee Tipper application, but this time for iOS.

AnyADeveloperAnyLanguage

Getting Started

At this point we’ve already created our first project and have connected to our source code repository. If you haven’t gotten this far, be sure to read through the first post in the series. We’ll continue to edit our existing projects in VSTS, but first there are a few prerequisites.

Preparing an iOS Build Agent

Since Xamarin.Android applications can be completely built and packaged on a Windows machine, we were able to leverage VSTS’ hosted solution to build our application. iOS applications must be built and compiled on a macOS device. Within VSTS, we have a few solutions available.

  1. MacinCloud Build Agent: Fully hosted with Xamarin support (paid plan)
  2. Utilize an on premise macOS machine with VSTS build agent installed

For this post, I’m going to utilize a Mac mini that I have on-premise as my build agent. You’ll only have to set up the agent once, as it can be used by multiple applications in VSTS. It can be a bit tricky to set up since it will require installing Homebrew, .NET Core, and npm on your macOS device, so here’s a quick rundown:

New Agent Pool

Create new “On Premise” Agent Pool under the projects Settings -> Agent Pools:
NewAgentPool

Install VSTS Build Agent

Before we can install the VSTS Build agent we must install a few prerequisites on our macOS machine.

  1. Install Homebrew package manager for macOS
  2. Install .NET Core
  3. Tip: after calling brew install openssl be sure to call:
    mkdir -p /usr/local/lib/

    This will ensure that the /user/local/lib folder is created before linking files.

  4. Install npm by running the following command in the terminal: brew install npm
  5. Create a Personal Access Token for the Build Agent. Select the Scope: Agent Pools (read, manage)
  6. On the Agent Pool page where we created the new pool, tap Download agent and follow the setup steps to properly configure the Build agent.
  7. InstallAgent

With that, the build agent should be sitting in an open terminal window listening for jobs to come in.
Listening

iOS Build Definition

Heading back to our Build Definitions, it’s time to create our new iOS definition, which tells VSTS how to go about building our iOS app. Tap on the new icon and then select Xamarin.iOS from the template list.

iOS_Build_Definition

The next step is the settings for source repository. Coffee Tipper is hosted on GitHub, which is already configured, so we’ll select that and then check the Continuous Integration check box and select the new On Premise agent queue.

Repo_Settings

This will create our definition with a few build steps set up for us. Before we configure the steps, let’s finalize the repository settings to point to the Coffee Tipper repository, which can be set up under the Repository tab:

FinalizeRepo

Back on the Build we can start to fill in our steps. Similar to our Android setup in VSTS, we can disable the Activate, Deactivate, and Test Cloud steps for now. I like to keep them in the definition in case I need to go back and toggle them on. We’re going to focus the rest of the time on the Build Xamarin.iOS Solution step.

This step has two main parts to configure. First is pointing to the actual solution to build. It’s important to point it to the .sln and NOT the .csproj as xbuild will take over and build the iOS projects in the solution. You’ll also notice that there is no NuGet restore step, but don’t fear—as part of this step, xbuild will automatically call NuGet restore on the entire solution.

BuildSLN

Configuring Solution

Note here that the default build configuration is set to Release under the Variables tab. You can adjust this at any time, but this is what I’ll use for this example. To ensure that the build is successful, go into the solution’s Build Configuration in Visual Studio or Xamarin Studio, where we’ll configure the Release/iPhone and Release/iPhoneSimulator builds to ONLY build the projects we need.

CopnfigSLN

Signing and Provisioning

At this point, if we wanted to build for the iPhoneSimulator and not generate an .ipa package, we could go ahead and build. This would be good for a smoke test of the build, but we want to do a full app package build.

BuildAppPackage

Only one of these check boxes should be checked, and if we are creating the app package then we must ensure that our P12 Certificate and Provisioning Profile are installed on the machine or are temporarily installed on the machine. There are a few ways to accomplish this:

  1. If using MacinCloud, simply follow the configuration steps here.
  2. For on-premise, we could simply use a machine that has the P12 Cert and Provisioning Profiles installed and there is nothing else to configure.
  3. Specify the Certificate and Profile locations in the Signing & Provisioning section

I went for the latter option, as I’m using a build machine that doesn’t have anything installed on it yet. I have exported my P12 Certificate and downloaded the Provisioning Profile for my app following these directions. We’ll store it in secure blob storage and use the command line build step to download it with a curl command much like we did for the keystore in the Android build. Since we have the actual machine we are building on, we can simply copy and paste them into the root directory from where the VSTS Agent was extracted and running from. Here are my settings:

Signing_Settings

Ensure that you specify the P12 Password and have it encrypted in the Variables tab.

Copy and Publish Artifacts

Before we can run, we want to make sure we can capture all of the artifacts we need to deploy to testers. Let’s add two more steps: the Copy File step and then the Publish Artifacts step.

CopyandPublish

Copy Files

We know that all of the build artifacts that we want will be in our bin/iPhone/$(BuildConfiguration) folder and can then specify to find all of our .ipa and .dll files by using the following:

**/*.ipa
**/*.dll

Then we can copy them to the built in staging directory with $(Build.ArtifactStagingDirectory) (a predefined variable).

CopyFiles

Finally, we can publish the artifacts so they can be used during release management by specifying the same staging directory and the name of the artifact to create.
Artifacts

Queue a New Build

It’s now time to queue our very first build. This will pull down all of the sources, attempt to build the app, sign it, and publish the artifacts. We should see a full build readout that will tell us if anything has gone wrong or if a file can’t be found for signing. Once complete, we can tap on the build and explore all of the artifacts that are ready for publishing.

SuccessfulDrop

Deploy to Testers with HockeyApp

hockeyapp (1)To go one step further, we can get the app into our testers hands by deploying to HockeyApp. In the last post we saw how to add in the free HockeyApp VSTS Extension from the marketplace, which adds a new HockeyApp step into VSTS. This enables us to configure a new HockeyApp connection and specify the .ipa file to publish after the build is successful.

HockeyApp

Learn More

Just like that, we now have our iOS and Android applications building in Visual Studio Team Services completely signed and shipped to our testers utilizing HockeyApp. For further details on VSTS and Xamarin, be sure to read through the full documentation on setting up Xamarin projects. Then take it a step further and send your app along with test scripts up to the Xamarin Test Cloud in one simple step.

The post Continuous Integration for iOS Apps with Visual Studio Team Services appeared first on Xamarin Blog.

August 25, 2016 3:23 GMT

Xamarin Utility in 5 Minutes with Plugins

[This article was restored]

I needed a quick and dirty program to create quick notes and mail them to myself.  You can see how this would be useful;  a way to jot down notes while away from the computer, with some high likelihood that I’ll see and remember the note when I get back.

I created a Xamarin.Forms application, and dropped an editor onto the page.  Here’s the complete XAML page:

  <?xmlversion="1.0"encoding="utf-8"?>
 <ContentPage
 xmlns="http://xamarin.com/schemas/2014/forms"
 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
 xmlns:local="clr-namespace:TextToMe"
 x:Class="TextToMe.TextToMePage">
 <StackLayout
 Padding="30">
   <Editor
   HeightRequest="300"
   x:Name="MessageEditor"
   Completed="Handle_Completed"
   BackgroundColor="Yellow"/>
 </StackLayout>
 </ContentPage> 


I implemented the event handler in code behind (this project was too small for MVVM),

  voidHandle_Completed(objectsender, System.EventArgse)
 {
   string message;
   message=MessageEditor.Text;
   varemailTask=MessagingPlugin.EmailMessenger;
   if(emailTask.CanSendEmail){
     emailTask.SendEmail("jesseliberty@gmail.com","Texttome",message);
     MessageEditor.Text="";
   }
 }
 

The magic here is accomplished by the Messaging plugin, which will let you make a phone call, send an SMS message or, in this case, send an email.  I could use some of the advanced features, like adding an attachment, but don’t need to.  I just want to send my text.  The three parameters are:

  • Recipient email address
  • Subject line
  • Body of message

 Pierce Boggan wrote up how to use the plugin in an excellent Xamarin blog article.

Hey! Presto! instant app.  But, the simulator can’t send email, so if you want to try it out, you need to do so on a device, which means you need to provision your phone.  Don’t panic, step by step directions are provided here.

Complete development time: 4 minutes.

 

But as I say, it is quick and dirty.  If I want to put it in the store, I still have some work to do.  First, I really don’t want all your notes, so I need an easy setup so that you can enter your own email address.  Second, it is ugly. Third, I need images, lots of images for the app store.  If you want to take that on, let me know and we can share the glory (and who knows, maybe advertising revenue).
August 25, 2016 2:44 GMT

Yet Another Podcast #161 – David Britch

David Britch is a Developer/Writer at Xamarin, and has previously spent many years working on projects for different groups at Microsoft.

David has authored and contributed to a range of recent software development publications including books, guidance documentation, reference implementations, whitepapers, videos, HOLs, and ILT courses.

Blog – www.davidbritch.com

 


August 24, 2016 6:03 GMT

How Olo Powers 150+ Restaurant Ordering Apps with Mobile DevOps

Olo’s customer and employee-facing Xamarin apps help restaurant brands deliver faster, more accurate, and more personalized service to their customers, building customer loyalty and improving restaurant operations. With a portfolio of over 150 brands and 25 million users, mobile DevOps is critical to Olo’s mobile strategy, and Xamarin helps the team deliver the highest quality experiences to their global clients.

Today, we’ve invited Greg Shackles, Principal Engineer at Olo and long-time Xamarin community member, to share his experiences with mobile development and his advice for aspiring app developers.
Which Wich App Screenshot
Tell us a little bit about your company and role. What is Olo and who are your customers?

I’m a Principal Engineer at Olo, which means I’m involved in a bit of everything we do.

Think of Olo as the digital layer between the restaurant and the on-demand world. Whether that’s takeout, delivery, or streamlined phone ordering, we integrate directly with the brands’ existing systems, including Point of Sale and loyalty, to bring digital commerce into their existing operations.

We generally work with large multi-location brands, typically over 40 locations. If you’ve used the Five Guys app, called 1-800-CHIPOTLE, or ordered Wingstop online, you’ve used Olo.

Tell us about your app(s).

We publish fully-branded iOS and Android apps for restaurants, enabling their customers to engage directly with their brand, customizing orders exactly how they want, on whichever platform they want, at their own pace, and be assured the restaurant will get it right.

With the apps, customers are able to easily find their closest locations, redeem loyalty rewards, see menus, view recent or favorite orders, order ahead, allowing them to Skip The Line® when they arrive, or even have their order delivered. Our open framework allows customers’ agencies to utilize our API, which we’ve seen with Sweetgreen.

What role does mobile play in your company’s strategy? Has your mobile offering evolved over time?

From the very beginning, and for the last decade, mobile has been the foundation for Olo.

Tired of waiting in long lines for his coffee every morning, our founder and CEO, Noah Glass, saw mobile’s potential to solve this problem and created Olo. In 2005, we launched our feature-phone based text message ordering; remember, this is still a couple of years before the launch of the original iPhone, and mobile remains a cornerstone of our platform to this day.

While we no longer support text message ordering, our customers engage with and accept orders from their customers on a wide variety of platforms including the web, iOS, Android, over the phone, and even Facebook and Twitter chat-based interfaces.

Why did you choose Xamarin?

Olo’s app platform wasn’t always built on Xamarin. Its was originally built using one of those Other Frameworks™ using JavaScript, which worked well enough for a while, but eventually put us in a tight spot. We found ourselves battling with the abstractions the framework put between us and the platforms, and at times it could take weeks to finish simple features. This was frustrating for our developers, but even more importantly, it meant that we couldn’t deliver the experience we wanted to our customers.

Any engineer knows that rewriting a platform is not a task to be taken lightly, but choosing to rebuild it using Xamarin was an obvious choice. We were already a .NET and C# shop, so being able to bring some of our existing amazing engineers into the mobile world, leveraging their existing skills, was a huge opportunity. With the new platform in place, we are able to deliver a stable, fully-native experience to our users, while still keeping our engineers happy.

What do you think about when you hear “native app”?

For me, it comes down to apps that fully leverage the native underlying UI frameworks, rather than an abstraction, and deliver the kinds of experiences users are accustomed to and expect from an app on that platform. Native apps need to feel native and to perform as such. They need to be able to use the things that make each platform unique and interesting, and not only build to the lowest common denominator across all of them.

Xamarin provides us with the best of both worlds, exposing direct access to all of the native APIs, while also allowing us to dial in our own abstractions the way we want them.
Wingstop App Screenshot
How much code do you typically share across platforms?

There’s an important qualifier that often gets lost in the discussion: how much code is shared across platforms that should be shared? Sharing code is great, but that doesn’t mean you need to avoid unshared platform-specific code, if it makes your app better on that platform. It’s our job as app developers to write code that gives our users the right experience.

We benefit from large amounts of code sharing at multiple different levels. At the base level, a core portable class library contains the real meat of the application: services, database access, network and API calls, application flow, logic behind each screen, etc. We have a large number of unit tests for everything in this layer, with the ability to run those tests on individual platforms to ensure compatibility.

On top of that, we’ve implemented our shared iOS and Android layers as shared code projects, allowing us to define all the platform-specific pieces needed to drive the app on each platform, agnostic to any particular brand.

For a specific brand’s apps, we have a lot of tooling built around our build and scaffolding pipelines that allow us to generate unique projects.

Describe your development process—how are you using mobile DevOps / CI?

With a platform like ours that maintains so many different apps, automation and CI is crucial. Every commit on every branch builds each project, runs unit tests, and builds the brand-specific apps, ensuring that the entire pipeline remains solid.

We can deploy versions of any brand’s app out to any of our environments via HockeyApp with the click of a button. We have automation in place around app store provisioning, packaging and signing, and also use Xamarin.UITest to automate screenshot generation.

How are you testing your apps? Why is mobile quality important?

Much like automation, testing is critical. We pride ourselves on delivering apps that are not only native and performant, but also incredibly stable. Unlike the web where you can quickly ship a fix and users get it on the next refresh, the barrier to releasing app updates is much higher. It’s crucial to smoke out as much as possible before the app makes it into your users’ hands.

We get a huge amount of wins out of unit testing. Since so much of our apps are driven from that layer, we can write tests that run quickly and test a significant portion of app behavior. Without spinning up a UI, we’re able to test everything from making network calls to defining the app’s flow from screen to screen.

We also love using Xamarin.UITest and Xamarin Test Cloud to make sure things are working correctly at that level too. Unit tests are awesome, but ultimately it’s the end user’s experience that matters.

We’ve gone through some big design changes in recent months, and being able to run our apps in Xamarin Test Cloud to see how different devices handled (or didn’t handle) things was simply invaluable. We were able to quickly and easily catch issues in random Android devices we likely would not have gotten otherwise.

How do you use HockeyApp?

We’re using HockeyApp purely for beta distribution, both internally and externally. For analytics, we’re using a mixture of technologies, ranging from things like Google Analytics and Google Tag Manager to custom homegrown instrumentation that we use to monitor how our apps are behaving in the wild.

My session at Xamarin Evolve 2016 dug into what we’re doing to monitor our apps’ performance in the hands of users in real time. One of the fun things about a platform like Olo is that we’re able to see how a wide range of brands and users interact with our apps, which puts us in a great position to learn and keep improving our flows and overall user experience.

What have your customers and their users said about your apps?

We’re always tracking customer feedback and doing user testing. Overall, the feedback has been overwhelmingly positive. Every time someone leaves an app review for one of our apps, both good and bad, it gets sent to the app team’s room in Slack for all to see.

It’s always a lot of fun when a brand launches with us and their customers go nuts. If you want to see what I mean, head over to Twitter and search “Wingstop app.”
 



 
What advice do you have for developers who are just starting out or investigating mobile development? Any best resources?

Between blogs, video services like Pluralsight, and the Xamarin site’s awesome documentation, there’s so much content available. This is great, but it can feel overwhelming for a newcomer.

My main piece of advice for new mobile developers is to start small. Don’t start out putting a bunch of abstractions between you and the platforms, such as big MVVM frameworks that add a lot of value, but also a lot of magic. There’s no escaping the fact that platforms like iOS and Android, while they do have many similarities, are ultimately very distinct. To start, spend some time learning the basics of how each operates, and then start diving into some of the abstraction layers once you understand exactly what they’re abstracting.

Read more about how our customers are transforming customer relationships and driving internal productivity on our Xamarin Customers webpage, and dig into Microsoft’s Mobile DevOps Solution.

The post How Olo Powers 150+ Restaurant Ordering Apps with Mobile DevOps appeared first on Xamarin Blog.

August 24, 2016 5:30 GMT

Using HttpClient with Xamarin.Forms

One can say Mobile Applications today cannot exist without a connected backend. Unless, you are building a calculator like app there’s a need for every app to connect to server to retrieve user’s data. In this post, I will show how we can use HttpClient module to make REST API calls in the Xamarin.Forms application.

In this post, I will be creating a simple ToDo app that:

  1. Adds a new item to server data
  2. Fetches existing items from server
  3. Update an existing item
  4. Delete an item

The sample can be opened in Xamarin Studio or Visual Studio. For simplicity, I have used Xamarin Studio here. Feel free to use the IDE of your choice, when you give it a try.

Step 1 : Create a Xamarin.Forms application

Open Xamarin Studio, File -> New Solution -> Under Multiplatform App -> Xamarin.Forms -> Forms App

Follow the steps and create a new project. Just to make sure, everything works fine. Build and run the app in iOS/Android. The finished project's folder structure would look like below :

Step 2 : Write REST API Invocation code in the PCL project - HttpClientDemo

  • Install the package Microsoft.Net.Http from Nuget -> For making REST API calls

  • Install the package Newtonsoft.Json from Nuget -> For Serialization/Deserialization of objects

  • Create a new file TodoItem.cs with the below lines of code

using System;  
namespace HttpClientDemo.Models  
{
    public class TodoItem
    {
        public string Description { get; set; }
        public string DueDate { get; set; }
        public bool isDone { get; set; }
    }
}
  • Add a new DataService class that is responsible for making API calls
HttpGet Request

HttpClient class exposes a method called GetStringAsync to make the get requests. Lets make use of them and invoke our API. The method to invoke get requests will look like below :

/// <summary>
/// Gets the todo items async.
/// </summary>
/// <returns>The todo items async.</returns>
public async Task<List<TodoItem>> GetTodoItemsAsync()  
    {
    var response = await client.GetStringAsync("http://localhost:5000/api/todo/items");
    var todoItems = JsonConvert.DeserializeObject<List<TodoItem>>(response);
return todoItems;  
    }

The async and await operators are very handy in making asynchronous calls. Similarly the other Http operations like Post/Put/Delete can be invoked using the below methods

HttpPost Request

Similar to GetStringAsync method, we also have PostAsync method which we can leverage for making Post requests. Sample code below :

/// <summary>
/// Adds the todo item async.
/// </summary>
/// <returns>The todo item async.</returns>
/// <param name="itemToAdd">Item to add.</param>
public async Task<int> AddTodoItemAsync(TodoItem itemToAdd)  
{
   var data = JsonConvert.SerializeObject(itemToAdd);
   var content = new StringContent(data, Encoding.UTF8, "application/json");
   var response = await client.PostAsync("http://localhost:5000/api/todo/item", content);
   var result = JsonConvert.DeserializeObject<int>(response.Content.ReadAsStringAsync().Result);
   return result;
}
HttpPut Request

When we have to modify any existing item, we should be using HttpPut method. Invoking a put method is as easy as using PutAsync method from HttpClient library. Sample code below :

/// <summary>
/// Updates the todo item async.
/// </summary>
/// <returns>The todo item async.</returns>
/// <param name="itemIndex">Item index.</param>
/// <param name="itemToUpdate">Item to update.</param>
public async Task<int> UpdateTodoItemAsync(int itemIndex, TodoItem itemToUpdate)  
{
   var data = JsonConvert.SerializeObject(itemToUpdate);
   var content = new StringContent(data, Encoding.UTF8, "application/json");
   var response = await client.PutAsync(string.Concat("http://localhost:5000/api/todo/", itemIndex), content);
   return JsonConvert.DeserializeObject<int>(response.Content.ReadAsStringAsync().Result);        }
HttpDelete Request

In our sample, to delete the unwanted To-do items, we can make HttpDelete request to the API. Sample code to do that is given below:

/// <summary>
/// Deletes the todo item async.
/// </summary>
/// <returns>The todo item async.</returns>
/// <param name="itemIndex">Item index.</param>
public async Task DeleteTodoItemAsync(int itemIndex)  
{
   await client.DeleteAsync(string.Concat("http://localhost:5000/api/todo/", itemIndex));
}

Step 3 : Consume the above changes in the HttpClientDemoPage.xaml.cs file

Add a method that makes the call to the DataService to load data

async void RefreshData()  
{
       items = await dataService.GetTodoItemsAsync();           
       todoList.ItemsSource = items.OrderBy(item =>         item.isDone).ThenBy(item => item.DueDate).ToList();
}

Invoke this RefreshData function from the Constructor to load the data from service on app launch.

public HttpClientDemoPage()  
        {
            InitializeComponent();
            dataService = new DataService();
            RefreshData();
        }

Similarly, we can make appropriate calls to the Add/Update/Delete methods depending on the UI events we wish.

  • Code to add a new todo Item
async void AddButton_Clicked(object sender, System.EventArgs e)  
{
     TodoItem newItem = new TodoItem
     {
    Description = txtTodoItem.Text.Trim(),
    DueDate = dpDueDate.Date.ToString("d")
     };
     await dataService.AddTodoItemAsync(newItem);
     RefreshData();
}
  • Updating a task as done
public async void OnDone(object sender, EventArgs e)  
{
  var mi = ((MenuItem)sender);
   TodoItem itemToUpdate = (TodoItem)mi.CommandParameter;
  itemToUpdate.isDone = true;
  int itemIndex = items.IndexOf(itemToUpdate);
  await dataService.UpdateTodoItemAsync(itemIndex,itemToUpdate);
  RefreshData();
}
  • Deleting the task
public async void OnDelete(object sender, EventArgs e)  
{
   var mi = ((MenuItem)sender);
   TodoItem itemToDelete = (TodoItem)mi.CommandParameter;
   int itemIndex = items.IndexOf(itemToDelete);
   await dataService.DeleteTodoItemAsync(itemIndex);
   RefreshData();
}

That's pretty much it from the code changes. The complete source code is available in Github repo.

https://github.com/svswaminathan/xamarin-forms-httpclient-sample

The repo contains code for both the Web API (built on asp.net core) and the Xamarin Forms app. The readme file contains instructions for running both the API and the App. The finished app should work as shown in the video below:

Though HttpClient is very easy to use and does the job in most cases, to gain more advantage of the platform specific network libraries, ModernHttpClient can be used. More on that on a separate blog post soon!

August 23, 2016 8:47 GMT

Creating a Serverless Backend for Mobile Apps

Azure Functions Functions_Logoenable developers to create a serverless, event-driven experience for their data and applications. In our first post on Azure Functions, we saw how to have an Azure Function perform an OCR of an image and insert it into an Azure Mobile table. Today, we’re going to take a look at turning Azure Functions into a serverless backend for our mobile apps that can integrate and connect with data from Azure, Office, Salesforce, or even Google Docs.

In this blog post, we’ll create a new mobile app that can query data through a single Azure Function endpoint. The Azure Function we create will take a country as input to a HttpRequest, parse data from a data source, and return a list of monkeys that live in that region.

Monkeys

Creating our Mobile App

To get started, we need to create a new blank Xamarin.Forms application and add a new XAML page for our user interface. The UI will have a few elements on it to select the location we want to query for monkeys from, a button to press to call our backend code, and a list of monkeys.


        
          

Now we’ve got our base page set up and ready to consume data from our Azure Function. Before we create the Azure Function, let’s set up our Model and ViewModel that our View will talk to.

First is the Monkey model, which has a few properties:

public class Monkey
{
    public string Name { get; set; }
    public string Location { get; set; }
    public string Details { get; set; }
    public string Image { get; set; }
}

Then we can create our ViewModel that the user interface will bind to, and we’ll also stub out a Command that will call our Azure Function when the “Find Monkeys” button is pressed.

public class MonkeysViewModel
{
    public MonkeysViewModel()
    {
        Monkeys = new ObservableRangeCollection();
        GetMonkeysCommand = new Command(async () => await GetMonkeysAsync());
    }
    //Monkey List: ObservableRangeCollection from: https://github.com/jamesmontemagno/mvvm-helpers
    public ObservableRangeCollection Monkeys { get; set; }
    //Selected Location index from our picker
    public int Location { get; set; }
    //Mirror list so we can use it later
    public List LocationList => new List
    {
        "Africa",
        "Asia",
        "Central America",
        "South America"
    };
    //Command that will call GetMonkeysAsync to get data
    public Command GetMonkeysCommand { get; }
    public async Task GetMonkeysAsync()
    {
        try
        {
           //Call to Azure Function here
           //Load Monkeys here.
        }
        catch (System.Exception ex)
        {
            Debug.WriteLine(ex);
        }
    }
}

Finally, in the code behind of our MonkeysPage.xaml.cs, we can set the BindingContext.

public MonkeysPage()
{
    InitializeComponent();
    BindingContext = new MonkeysViewModel();
}

Now, it’s time to create our backend with Azure Functions to pull data into our mobile app.

Creating the Function

Creating an Azure Function to respond to a web request is simple, as there’s already a template called “HttpTrigger – C#” that will provide boilerplate code to take in an HTTPRequestMessage and output a HttpResponseMessage with any data we’d like. Name the function and set the authorization level to anonymous, so our mobile app can access the endpoint.

NewFunction

Once created, we’ll see boilerplate code that parses the request for a field called “name” that we can use later on.

public static async Task Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");
    // parse query parameter
    string name = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
        .Value;
    // Get request body
    dynamic data = await req.Content.ReadAsAsync();
    // Set name to query string or body data
    name = name ?? data?.name;
    return name == null
        ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
        : req.CreateResponse(HttpStatusCode.OK, "Hello " + name));
}

Note that for extra security we could turn on authentication for our Function with Azure Easy Authentication or a secret key.

Adding Data from Input Bindings

At this point, we could call the function endpoint and it will return a simple message to us. For our app, we want to take in the parameters, talk to a data source, and return data for our mobile app. This is where input bindings for Functions are handy. Tap on the Integrate tab and select New Input. This will enable us to create a connector to several data sources to read data from.

New Input

There are several options, including integrating with Azure Mobile Table Records or existing SaaS solutions, for file and table access:
AddSaas

For this example, we’ll skip this step and hard code in the monkey data that will be returned. We can use the name parameter as the location that is passed in.

This means before we return, we’ll get the list of monkeys and then perform a Linq query to find the monkeys with the specified location:

var monkeys =  GetMonkeys().Where(m => m.Location.ToLower().Contains(name.ToLower()));
return name == null
        ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
        : req.CreateResponse(HttpStatusCode.OK, monkeys);

You can find the final run.csx file on my GitHub for reference.

Getting Data to our Mobile App

Now it’s time to integrate the Azure Function into our mobile applications. All we need to do is fill in our GetMonkeysAsync method to make a web request and deserialize the data from our Azure Function.

public async Task GetMonkeysAsync()
{
    try
    {
        using (var client = new HttpClient())
        {
            var url = "https://mobile-ocr.azurewebsites.net/api/Monkeys";
            var input = JsonConvert.SerializeObject(new { name = LocationList[Location] });
            var res = await client.PostAsync(url,
                new StringContent(input, Encoding.UTF8,"application/json"));
            var json = await res.Content.ReadAsStringAsync();
            var monkeys = JsonConvert.DeserializeObject<IEnumerable>(json);
            Monkeys.ReplaceRange(monkeys);
        }
    }
    catch (System.Exception ex)
    {
        //Something has gone wrong
        Debug.WriteLine(ex);
    }
}

In Action

In Motion

There you have it! Our mobile app is able to call and pass data to our Azure Function and get the correct list of monkeys back.

Learn More

There are so many more integrations for Azure Functions for mobile applications, especially around Bindings and Triggers to tie to several data sources. Be sure to head to the Azure Functions website for more information and download the full source code for the sample app on my GitHub.

The post Creating a Serverless Backend for Mobile Apps appeared first on Xamarin Blog.

August 22, 2016 5:33 GMT

Podcast: Identity Management in Mobile Apps

Whether you’re building an app that has user-specific data such as notes, or need to ensure access to internal data is restricted, it’s likely your mobile app needs identity management. In this edition of the Xamarin Podcast, Mike James and I discuss identity management in mobile apps. We start by exploring the question, “does my app even need identity?” If it does, we break down the various options available to mobile developers, from local to social to enterprise authentication.
 

 

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, Google Play Music, 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 on identity management in mobile apps, and don’t forget to subscribe!

The post Podcast: Identity Management in Mobile Apps appeared first on Xamarin Blog.

August 20, 2016 11:00 GMT

NuGet Package Explorer for Xamarin Studio

When diagnosing why a NuGet package cannot be installed into a project the application I use is the excellent NuGet Package Explorer. Whenever there is an error trying to install a NuGet package, similar to the one shown below, you can open the NuGet package with NuGet Package Explorer and take a look at the target frameworks it supports.

You are trying to install this package into a project that targets 'MonoAndroid,Version=v6.0',
but the package does not contain any assembly references or content files that are compatible with that framework.

Currently NuGet Package Explorer is only available on Windows. On other operating systems you can change the file extension to .zip, extract the contents of the NuGet package, or open it into a zip application, and take a look at the files.

To make exploring NuGet packages easier on operating systems where the NuGet Package Explorer application is not available there is a now NuGet Explorer addin that you can install into Xamarin Studio or MonoDevelop. With this addin you can open and explore NuGet packages from online package sources or from the local file system.

Exploring the Xamarin.Android.Support NuGet package in Xamarin Studio

Now let us take a look in more detail of the features provided by the NuGet Package Explorer addin.

Features

  • Open and view NuGet packages from online package sources or from the local file system.
  • View the NuGet package metadata.
  • View the NuGet package files.
  • View the NuGet package .nuspec file.
  • Open any file stored inside the NuGet package.
  • Open other NuGet packages that are listed as dependencies.

Supports Xamarin Studio 6.0 and MonoDevelop 6.0.

Opening a NuGet Package from a Package Source

To open a NuGet package from a package source you can select Open NuGet Package from the File menu.

File Open NuGet Package menu

Alternatively if you have a project open you can right click the Packages folder in the Solution window and select Open NuGet Package.

Open Package menu on Packages folder

This will open the Open Package dialog. This dialog is the same as the Add Packages dialog used when installing a NuGet package and allows you to search for NuGet packages. The dialog is based on the version available with Xamarin Studio 6.1 so it has a version combo box where you can select a specific package version instead of having to remember the syntax for the package version search.

Open Package dialog

Select one or more NuGet packages and click the Open Package button to download and display them in Xamarin Studio.

Exploring the JSON.NET NuGet package in Xamarin Studio

The NuGet package metadata is shown on the left. On the right are the files that the NuGet package contains. You can also view the .nuspec file stored in the NuGet package by selecting the NuSpec tab at the bottom of the window.

Viewing JSON.NET .nuspec file

Exploring Dependencies

NuGet package dependencies are displayed with hyperlinks.

If you click one these hyperlinks the Open Package dialog will be opened and the package will be searched for. You can then choose a package version and open the NuGet package.

Opening Files Contained Inside the NuGet Package

To open a file contained inside a NuGet package you can double click the file, or right click the file and select Open.

Open menu to open file inside NuGet package into Xamarin Studio

The file will then be opened inside Xamarin Studio.

Opening a NuGet Package File

If you have a NuGet Package (.nupkg) stored on the local machine that is not available from any package source you can open the file directly in Xamarin Studio by selecting Open from the File menu.

You can also associate .nupkg files directly with Xamarin Studio and have them automatically open inside the IDE.

Opening a NuGet Package Installed in a Project

You can explore NuGet packages that are installed in your project by right clicking the package in the Solution window and selecting Open Package.

Open installed package context menu

Installing the NuGet Package Explorer addin

The NuGet Package Explorer addin is available from the MonoDevelop addin repository on the beta channel. It can be installed by from the Add-in Manager by searching the gallery and then clicking the Install button.

Addin Manager dialog

August 18, 2016 11:58 GMT

Xamarin.Forms E-Z Print

It seems in the age of phones & tablets that are as powerful as computers used to be only a few years ago, with huge amounts of on-board storage and almost always on internet where anything can be looked up instantly, that the days of printing out documents would be over. Well, that’s not the case. There’s something to be said about holding a piece of paper in your hands to consume information from. In some ways, it’s reassuring the data one is looking at is real – not just some pixels on a screen. So it’s inevitable that we’ll be asked to add printing functionality to our apps one day … and if we’re creating a Xamarin.Forms app, there’s a very simple way of doing so. Let’s take a look at how it’s done!

Xamarin.Forms E-Z Print

First off I want to say that this solution may not be one size fits all. However, I have found it does work in the several use cases I have needed it for, and I wanted to share it with you. (If you just want to jump into some code, you can find a full demo solution on my GitHub here.)

Each operating system provides its own printing subsystem. The print engines on the respective platforms can do some pretty amazing things (as with UI graphics, you can go low-level & print in intricate detail). The problem arises when devising a way to give the print engine the content to print… AND ideally having that content be exactly the same type for both operating systems… AND providing the most flexibility for the layout of the content… AND requiring us to do the least amount of coding.

For example … do we need to do some custom drawing on each platform and print that out? Maybe create a PDF, and have the engine print that? The engine should probably be able to handle printing an image – so maybe we should take the content we want to print – convert it to an image & hand that over to be printed?

As you can imagine, there are any number of ways we can go about this. But the key is that we want to do it with the least amount of work possible – while providing the most flexibility as possible.

So what’s the easiest way to go about this? Our old friend HTML!

Make the OS Work For Us!

HTML … in a Xamarin-based app? Yup! But I’m not going to tell you we have to redo the whole thing as a Cordova app. Rather since each operating system supports the ability to print HTML from its version of a web view, and can do so with full formatting, images, color, etc … and since the

Xamarin.Forms.WebView
is really only an abstraction over each of the OS’s respective native web views … all we need to do is to get what we want to print into HTML, and then let iOS and Android take care of the rest!

We’ll get full access to the printing system, just by passing some HTML – satisfying the “only generating one type of data” requirement!

Razor to the Rescue!

Now, what’s the easiest way to generate the HTML so that we can do the least amount of work, but provide the most amount of flexibility? Enter the Razor templating engine … yes, the same Razor that you used to create ASP.NET MVC views before you discovered the glamorous world of app development!

Turns out Xamarin has robust support of Razor templates – one can even supply images and apply CSS frameworks – and generating HTML from those templates really is a breeze. Xamarin has some good documentation on Razor templates within their apps, but let’s take a quick tour at what we need to do to generate some HTML.

The first thing we want to do is add the Razor template to the solution – put it into the PCL or Shared Project portion of the Forms project. The new Razor file can be found under “Text Templating” section in the “New File” dialog.

Creating A New Razor Template

Creating A New Razor Template

One of the cool things that’ll happen with this template is that it will be available to instantiate from within our PCL. And that means we can set the

@model
property of the template … and of course that’s the property which is used as the data source when rendering the view.

As I mentioned above – another cool thing about the Razor templating within Xamarin – we can access static resources, such as images and CSS files. That means the resulting HTML can have some slick formatting to it without cluttering the template up, and if we’re using something like Bootstrap or Primer, without a lot of work on our part either.

The only thing to remember when using static assets is that they must be located in the platform project. On iOS, the images and CSS needs to go in the

Resources
folder and have a build action of
BundleResource
. On Droid, they need to reside in the
Assets
directory, and have a build action of
AndroidAsset
.

Here’s an example of a Razor template that has a

System.Collections.List<T>
as the model, uses Primer as a CSS framework. On line 21, it loops through the data to do a basic display.

@using FormsEZPrint;
@using System.Collections.Generic;

@model List<EZPrintModel>

<!DOCTYPE html>
<html lang="en">
    <head>
        <!-- iOS - needs to reside in the "Resources" directory and have build action of "BundleResource" -->
        <!-- Droid - needs to reside in "Assets" directory and have build action of "AndroidAsset" -->
        <link rel="stylesheet" href="primer.css">
    </head>
    <body>
        <div class="blankslate blankslate-spacious">
            <h3>Xamarin Forms EZ-Print!</h3>
            <p>Even works using the CSS frameworks like Primer!</p>
        </div>
        <div class="container">
            <div class="columns">
                @foreach (var m in Model) {
                    <div class="one-fifth column">
                        <span class="d-inline-block p-3 bg-red text-white">
                        @m.ModelName
                        </span>
                    </div>
                    <div class="four-fifths column">
                        <span class="d-inline-block p-3 bg-green">
                        @m.ModelDescription
                        </span>
                    </div>
                }
            </div>
        </div>
    </body>
</html>

So that’s all that’s needed for the template … but how does one actually generate the HTML from it? Even easier… Remember when I mentioned that we could instantiate the Razor template from our code? By doing that, setting its model property, and then telling the template to generate … that’s all that’s needed!

// New up the Razor template
var printTemplate = new ListPrintTemplate();

// Set the model property (ViewModel is a custom property within containing view - FYI)
printTemplate.Model = ViewModel.ezPrints.ToList();

// Generate the HTML
var htmlString = printTemplate.GenerateString();

Alright – with the HTML obtained – now’s the time to pop it into a

Xamarin.Forms.WebView
. Again, super easy, nothing you haven’t seen elsewhere.

// New up the Razor template
var printTemplate = new ListPrintTemplate();

// Set the model property (ViewModel is a custom property within containing view - FYI)
printTemplate.Model = ViewModel.ezPrints.ToList();

// Generate the HTML
var htmlString = printTemplate.GenerateString();

// Create a source for the webview
var htmlSource = new HtmlWebViewSource();
htmlSource.Html = htmlString;

// Create and populate the Xamarin.Forms.WebView
var browser = new WebView();
browser.Source = htmlSource;

You’ll notice that nothing is being added to any sort of layout anywhere … that’s because the

WebView
is not being displayed at all. We’re just using it to hold the rendered HTML content, and then passing it to the platform’s printing engine. By doing it this way, we work around the situation where one sees a screen -> taps Print -> Sees a screen with a web view -> taps Print (again) … then finally sees the platform’s printing dialog. In other words – we’re avoiding seeing the web view!

Now we’re up the point where we need to make a handoff to the individual platform’s operating system. The easiest way is to use Form’s built-in

DependencyService
.

Dependency Service Setup

To make it easy to get at the platform specific implementation of our print service – we’ll use the built-in

DependencyService
(although we don’t have to … partial classes, other IoC, etc. would work as well).

The

DependencyService
needs an interface to work with – so we’ll use this:

using Xamarin.Forms;

namespace FormsEZPrint
{
    public interface IPrintService
    {
        void Print(WebView viewToPrint);
    }
}

The big thing to notice here is that the

Print
function is taking a
Xamarin.Forms.WebView
as a parameter.

When the shared code needs to print – it will look something like the following to invoke the print service:

var printService = DependencyService.Get<IPrintService>();
printService.Print(browser);

We’re all set! Well, except for the platform specific implementation of printing that is…

iOS Implementation

The key to printing in iOS is to get the native implementation of

Xamarin.Forms.WebView

… which happens to be

UIWebView
in iOS. Once that
UIWebView
is in hand – then it’s a trivial matter to create the rest of the print job. Set some general parameters to the
UIPrintInfo
for page layout, and then show the shared
UIPrintInteractionController
– setting the
UIWebView
as the print formatter.

The secret sauce to get the

UIWebView
?
Xamarin.Forms.Platform.iOS.Platform.CreateRenderer(view).NativeView
… that’s going to get us the native view, and then the rest is standard iOS code.

[assembly: Xamarin.Forms.Dependency(typeof(ApplePrintService))]
namespace FormsEZPrint.iOS
{
    public class ApplePrintService : IPrintService
    {
        public ApplePrintService()
        {
        }

        public void Print(WebView viewToPrint)
        {
            var appleViewToPrint = Platform.CreateRenderer(viewToPrint).NativeView;

            var printInfo = UIPrintInfo.PrintInfo;

            printInfo.OutputType = UIPrintInfoOutputType.General;
            printInfo.JobName = "Forms EZ-Print";
            printInfo.Orientation = UIPrintInfoOrientation.Portrait;
            printInfo.Duplex = UIPrintInfoDuplex.None; 

            var printController = UIPrintInteractionController.SharedPrintController;

            printController.PrintInfo = printInfo;
            printController.ShowsPageRange = true;
            printController.PrintFormatter = appleViewToPrint.ViewPrintFormatter;

            printController.Present(true, (printInteractionController, completed, error) => { });        }
    }
}

That takes care of iOS … let’s look at Android …

Droid Implementation

Again, the whole point here is to get at Android’s native version of

WebView
Android.Webkit.WebView. Platform.CreateRenderer()
is our friend again in this situation!

[assembly: Xamarin.Forms.Dependency(typeof(DroidPrintService))]
namespace FormsEZPrint.Droid
{
    public class DroidPrintService : IPrintService
    {
        public DroidPrintService()
        {
        }

        public void Print(WebView viewToPrint)
        {
            var droidViewToPrint = Platform.CreateRenderer(viewToPrint).ViewGroup.GetChildAt(0) as Android.Webkit.WebView;

            if (droidViewToPrint != null)
            {
                // Only valid for API 19+
                var version = Android.OS.Build.VERSION.SdkInt;

                if (version >= Android.OS.BuildVersionCodes.Kitkat)
                {
                    var printMgr = (PrintManager)Forms.Context.GetSystemService(Context.PrintService);
                    printMgr.Print("Forms-EZ-Print", droidViewToPrint.CreatePrintDocumentAdapter(), null);
                }
            }
        }
    }
}

We have to jump through some more hoops to get at the Android

WebView
– but we can do it nonetheless. One BIG, BIG, BIG caveat however … this will only work for API level 19 and up.

Conclusion

And there you have it … a relatively easy and painless way to implement printing within Xamarin.Forms. The most difficult part is designing the template to get the exact look that you want … but with the ability to include CSS frameworks and static images, even doing that is easy. A full demo project can be found on GitHub here. Who would have thought printing could be so easy?!?

August 18, 2016 7:12 GMT

Continuous Integration for Android with Visual Studio Team Services

Commonly referred to as VSTS, Visual Studio Team Services is a developer’s dream, with tools for every step of development, including planning, building, testing, releasing, and insights for your application. Developers can pick just one service or utilize all of the tools in VSTS for their full DevOps pipeline. As I’m developing applications, it’s important that as soon as I push code to my repository that my application is built, tests are run, and it’s ready for deployment. VSTS has the perfect tools to build Xamarin applications in the cloud, and today we’ll take a look at building a Xamarin.Android application in the cloud.

AnyADeveloperAnyLanguage

Create Your Account

Before we begin, it’s required to create a new account at visualstudio.com and select a VSTS account name under which multiple projects can be created. If you already have an account, simply sign in and select an existing VSTS account or create a new one. During this step it’s possible to create a private code repository with a Git or Team Foundation Version Control for source control. These private repositories are a great option as they are completely free and unlimited, but it’s also possible to connect to an existing Git or on premise Team Foundation service for Continuous Integration.

Acreate account

With the account created, we will be redirected to our team overview page, where a new project has been created automatically. If you already had an account, simply add a new project.

Connecting to Code

If you’re hosting your application inside of VSTS, you can skip this step since you are ready to start automating your builds. Because we are able to connect to an existing code repository service, we can connect to GitHub to automate an existing app, Coffee Tipper. To add a service, we’ll have to go into our project settings on the top right of the page:

settings

We can add GitHub as a new service endpoint under the services tab. You’ll also find other services here such as External Git and Subversion.

new service endpoint

At this point, we can add a personal access token to authorize VSTS to talk to GitHub, or we can simply Grant Authorization by logging into GitHub.

Add GitHub

Creating the Build Definition

With GitHub connected, it’s time to create our first build definition that defines the workflow steps to build the application. Select Build at the top of our project page and then the Add button to open the Create new build definition, where we’ll find a build for Xamarin.Android.

New_Build_Definition

The next step is to select our repository source (in this case GitHub) and then a default agent queue. Think of an agent queue as a machine that will be used to pull down the source code and build the application fully. VSTS offers a hosted solution in the cloud that can be used with Xamarin.Android applications and includes 240 minutes of build time a month on a hosted build agent. It’s also possible to configure a local agent queue that’s running the VSTS agent to perform the builds on a machine of your choosing. For simplicity, we’ll select the hosted machine so there’s no further configuration needed!

AgentQueue

Configure Repository

After creating the definition, we can start adding and editing steps, but before we do, let’s finish configuring the repository that should be built under the Repository section of the build definition. Since we already connected to GitHub and selected it when creating the definition, all that’s left is to select and configure the repository:

ConfigureRepo

Configuring the Build Definition

The generated build definition has a few pre-defined steps that most Xamarin.Android applications need in order to be compiled, built, and signed for deployment. There are three steps that need configuration for the Xamarin License and for Xamarin Test Cloud. These can be configured later and are not required for building the application, so let’s simply right click and disable these steps so they aren’t run. If you don’t have any unit tests, the Build test can also be disabled.

Disable steps

All other steps, including restoring NuGet packages, building the Android project, and packaging the app can remain. Each step can be configured with properties specific for the step. The Build Xamarin.Android Project step allows us to configure the project to be built. By default, it will search any project that has “Droid” in the title. We can change this to point directly to the Coffee Tip Android project:

Update_property

Save and Queue Build

We’re now ready to test the build. Simply tap on Save to finalize the build definition and give it a unique name of your choosing. I’m going with Android – Release Build. Now, the Queue build… button will become enabled and we can manually queue our first build.

Just like that, our very first build is queued in the hosted agent and the build will start giving us a full readout of everything that’s happening.

AppBuilding

When the build is finished, a full build log is available and a list of artifacts that were built can be downloaded.

FInal_Build

Build with Every Commit

We manually queued this build, but to really integrate this newly created build definition into our DevOps cycle we can turn on Continuous Integration so a new build is started with each check-in. Under the Triggers section of the build definition, simply turn on Continuous Integration and configure as many or as few branch filters as you would like. By default it will only monitor for changes on the master branch.

CI

Going Further

There’s a lot more that we can do with VSTS for an Android application to get it ready for real production.

Signing with Keystore

One of the most important parts of releasing an Android application is signing it with a private keystore. VSTS can handle this easily with the built in Android Signing and Aligning step that was already added to the build definition. To use this step, we’ll need to have created a private keystore and have it accessible for the build agent. This can be accomplished by having it checked into a private repository or by downloading the keystore from secure blob storage.

To download the keystore for the build agent, we can use the command line step combined with curl, which is on the hosted agent.

AddCommandlline

Drag and drop the command line step above the sign step and set the following properties to download and copy the keystore to the root of the repository on the build agent:

Tool: c:\Program Files\Git\usr\bin\curl.exe
Arguments:

-k "URL_TO_KEYSTORE" --output $(Build.SourcesDirectory)\NAME_OF_KEYSTORE.keystore

Signing_Settings

Now, we can create a private Variable for the KeystorePassword that will be encrypted for the Android Signing process. Under the Variables tab, enter the name and value of the password of the keystore and then enable the lock to encrypt it.

KeystoreVariable

Finally, specify the Jarsigner options and ensure that Zipalign is enabled for the Android APK:

SigningSettingsFinal

Continuous Deployment to HockeyApp for Testing

Everything that we’ve done so far is included in VSTS by default, but there’s an entire Marketplace for VSTS that enables developers to extend and add new functionality with new build steps. HockeyApp is a service that enables mobile app developers to easily distribute apps to testers and get feedback from them. We can install the HockeyApp VSTS extension, which will add new build steps to easily deploy to HockeyApp.

AddHockeyAPp

Just like we connected to GitHub under our projects services in settings, we can also connect to HockeyApp to specify our API Token:

AddHockeyApp_001

Back in our build steps we can add the HockeyApp step under the Deploy category:

HockeyAppStep

The last thing to do is configure the step with the connection, App ID from HockeyApp, and the APK to upload to HockeyApp.

Configure_HockeyApp

Once the build is completed, it will have been signed and shipped to HockeyApp!

InHockeyApp

Learn More

We’ve now set up full Continuous Integration and Continuous Deployment for our Xamarin.Android application in Visual Studio Team Services. With every commit, our application will be built, signed, and shipped directly to HockeyApp for testing. There’s still so much more to explore, including testing with Xamarin Test Cloud and exploring the marketplace for VSTS. Be sure to check out VSTS’ full documentation for building and distributing Xamarin applications.

The post Continuous Integration for Android with Visual Studio Team Services appeared first on Xamarin Blog.

August 17, 2016 6:02 GMT

Xamarin Developer Certification is Getting Better

Xamarin University has constantly improved and progressed since we launched almost three years ago. Today, I’d like to announce some great changes to the Xamarin Certified Developer Program. These changes not only help to keep certification high value and trusted, but also make it easier to stay certified once you’ve attained it.

First Year Certification Changes

Xamarin Certified Mobile Developer BadgeFirst of all, we’re changing core (first year) certification to be based on Xamarin.Forms. This is an important strategic shift due to the maturation of Xamarin.Forms as a platform and because most Xamarin developers turn to Xamarin.Forms first when building applications, only going platform-specific when they need to. The required classes will still include some iOS and Android content, but it will be restricted to the minimum necessary to give a comfortable introduction to the platforms. You can find a living list of the new classes required for first year certification here.

Additionally, we’re adding a more personal touch to certification: once you’ve taken 85% or more of the required certification classes, we’ll reach out to schedule a free one-on-one office hour session with your primary instructor to discuss the certification exam, answer any questions you have about preparing for it, and just generally check in to make sure you’ll be successful.

Recertification

We’re also introducing a huge change to the recertification track. Instead of a list of mandated classes, we’re transitioning to an elective model whereby you retain your certification status by studying your own choice of topics from a subset of the curriculum. There will still be a small number of high value classes that will be required, but they will remain few and strategic, and you can decide on the bulk of classes that you want to take. This means that you can tailor your education to what’s important to you and your career, while still getting important platform updates.

The best part as long as you’ve taken the required classes and your electives, and kept your Xamarin University subscription active, you’ll stay certified without taking another exam!

Effective Date

These changes will go into effect on October 15, 2016. If you’re already on your way to certification and only have a few classes left, then you have 60 days to finish up your coursework and take the current test before these changes will be applied.

We’re all excited about these changes. I think it’s both a simplification and makes certification an even greater asset. If you have any questions, don’t hesitate to reach out to us at training@xamarin.com.

The post Xamarin Developer Certification is Getting Better appeared first on Xamarin Blog.

August 16, 2016 6:15 GMT

“Document All the Things” Contest Winners

At the heart of Xamarin has always been a desire to empower developers to create great mobile apps, and this goal includes fostering an active developer community. For this reason, we were very excited when Stack Overflow announced a new documentation feature enabling experts within the community to write documentation to share their knowledge with their fellow developers. We were so excited, in fact, that we launched a contest asking members of the .NET community to contribute Xamarin documentation to the new portal.

The response to the contest from our community was amazing, and the Xamarin documentation on Stack Overflow is already growing, which means it’s time to announce the winners of our Stack Overflow Documentation contest!

Contest Winners

The following randomly-selected winners can select a choice of a Microsoft Band, Apple TV, or Azure IoT Starter Kit.

Thank you to everyone who entered this contest and to those contributing to the documentation portal on Stack Overflow. We’ll be reaching out to the winners via Direct Message on Twitter, so please be sure to follow @XamarinHQ!

The post “Document All the Things” Contest Winners appeared first on Xamarin Blog.

August 16, 2016 4:40 GMT

Announcing FreshMvvm 2.1 and 2.2

Your favourite Mvvm Framework for Xamarin.Forms just keeps getting better. At XAM Consulting we use FreshMvvm in all of our serious production applications, the fact that we use FreshMvvm so intensely is the reason that FreshMvvm is easy to use, robust and flexible.

There’s been two releases of FreshMvvm since I last updated, Version 2.1 and Version 2.2.

Release 2.2.0

Better debug messages displayed

In previous versions of FreshMvvm construction errors of pages were in a few levels of inner exceptions, so if your xaml had a little error you had to dig into the inner exceptions. It was not an issue for experienced users of FreshMvvm but for people new to the Framework it was a bit hard to figure out the actual issue. Now exceptions will be bubbled up developers won’t need to look into inner exceptions.

Ability to remove a page from Navigation

In some cases you might want to remove a page from the Navigation stack. This works in the case you’ve Pushed a few pages but want to remove one of the pages from the stack before you return,  for example you’ve pushed to Page1 -> Page2 -> Page3, but you essentially you don’t want Page2 to be part of the stack anymore. In this case you can call the remove method.

CoreMethods.RemoveFromNavigation<Page2ViewModel>();

Add ability to SwitchSelectedRoot page in Tabs and MasterDetail

This is another special finite feature of FreshMvvm, in which you can switch the currently selected page of the main tabbed page or the master detail page.

//switch the selected tab to the HomePageModel
CoreMethods.SwitchSelectedTab<HomePageModel>();

//switch selected master to the HomePageModel
CoreMethods.SwitchSelectedMaster<HomePageModel>();

//switch selected to the HomePageModel
CoreMethods.SwitchSelectedRootPageModel<HomePageModel>();

 

Release 2.1.0

Adds ability to control PageModel mapping via PageModelMapper

You now have the ability to control the convention of mapping ViewModel to pages. You do this by using the IFreshPageModelMapper.

public interface IFreshPageModelMapper
{
    string GetPageTypeName(Type pageModelType);
}

Currently the PageModel mapper is defaulted to  the FreshPageModelMapper.

public static class FreshPageModelResolver
{
    public static IFreshPageModelMapper PageModelMapper { get; set; } = new FreshPageModelMapper();
    ...

The current behaviour is to map PageModel or ViewModel to Page.

public class FreshPageModelMapper : IFreshPageModelMapper
{
    public string GetPageTypeName(Type pageModelType)
    {
        return pageModelType.AssemblyQualifiedName
            .Replace ("PageModel", "Page")
            .Replace ("ViewModel", "Page");
    }
}

It’s easy to implement your own custom mapper and then set the PageModelMapper.

FreshPageModelResolver.PageModelMapper = MyPageModelMapper();

Adds ability to navigate without animation

You can now push and pop PageModel without animations.

Better cleanup of objects

We clean up after ourselves, even better now. :)

IOC now has unregister feature

You can now unregister a class out of the IOC container.

Add First Only Tabbed Navigation Container

FreshMvvm has always had a built in tabbed navigation container, the behaviour of this navigation is to keep the tabs always present but this is not what you always want. In some case you want the tabs to disappear when you push to a page, so we created the FreshFONavigationContainer. The FO stands for First Only and it means this tab page will only appear on the first page of the app.

FreshMvvm in Production

It makes us happy to see that so many others are also delivering great apps using FreshMvvm. I was recently informed that the Fraedom Expense app was built with FreshMvvm. Great work.

As always the latest version of FreshMvvm is up in nuget right now.

Thanks

 

The post Announcing FreshMvvm 2.1 and 2.2 appeared first on Michael Ridland.

August 15, 2016 5:58 GMT

Webinar Recording | Continuous Everything: Why You Need Mobile DevOps

Whether you’re a mobile-only startup looking to turn early adopters into evangelists or a multi-million dollar enterprise mobilizing your workforce, you need to ship the right apps, to the right customer, at the right time. You need users to use your apps, turning downloaders into engaged users. To win mobile users’ loyalty, you have to continuously ship high quality software and continuously listen and learn from your users, giving them features before they know they want them. Mobile isn’t just build, release, and done; it’s a continuous cycle of designing, coding, testing, releasing, monitoring, fixing, and improvement. With the right mobile DevOps processes and the right technology, this “continuous everything” is within reach for any organization and all developers.

In this webinar, Xamarin VP of Product Keith Ballinger discusses:

  • What he learned from his failed startup experience and how you can sidestep common pitfalls to beat your competition
  • How to balance shipping high quality software with speed to market
  • Why agile isn’t enough and how mobile DevOps allows you to release faster
  • How to listen to your users, collect feedback, and prioritize new features to ship better apps
  • How Xamarin Test Cloud and HockeyApp can help any organization get started with mobile DevOps and continuous everything

 

 

The post Webinar Recording | Continuous Everything: Why You Need Mobile DevOps appeared first on Xamarin Blog.

August 15, 2016 3:34 GMT

Yet Another Podcast #160 – Mobile Technology Overview – Sam Basu

Sam Basu is a technologist, author, speaker, Microsoft MVP, gadget-lover and Developer Advocate for Progress. With a long developer background, he now spends much of his time advocating modern web/mobile/cloud development platforms on Microsoft/Telerik stacks. His spare times call for travel, fast cars, cricket and culinary adventures with the family. You can find him on the internet as @samidip.

Square HeadshotNativeScript – https://www.nativescript.org/
Kendo UI – http://www.telerik.com/kendo-ui
Telerik UI for Xamarin – http://www.telerik.com/xamarin-ui
Telerik Platform – http://www.telerik.com/platform#overview

Screen Shot 2016-08-12 at 1.36.38 PM

 

 

 

 

August 13, 2016 2:49 GMT

My Web Journey

In a recent post, I launched what will be a series on web development.  What better way to get this started than to review how we got here?  And to do that, indulge me, I will tell you (briefly) my own story with the web.

At Demo ’94 I had the opportunity to see the new ‘program’ MosaicaExported_ - 1 (1).  I had been working with the Internet for a good while, but this blew me out of my seat.  Here was a graphic rich environment with hyperlinks, that they were giving away for free.  Wow.
I had been working on a commercial effort named Interchange that did all this and a lot more, but it wasn’t free and it wasn’t open standards.  Needless to say, we were dead in the water (see the first chapter of my book Beginning Object Oriented Design and Devlopment (1998)).

From 1998 to 2000 I programmed the web in HTML and C++.  In 2000 I discovered C# and never looked back.  Two years later Active Server Pages came along, and once again, changed everything.  That was the real beginning of my professional web programming.

In 2007 I went to Microsoft to work on the XAML and C# framework:  Silverlight, and stayed until it was officially pronounced dead in 2012.  I then turned to XAML programming and evangelism until 2014 when  I started work with Xamarin (also a XAML & C# development framework; this time for mobile apps).

In 2015 I went back to being independent* and have been dividing my time between Xamarin and web programming since.  I created a number of web-oriented courses for Pluralsight such as Programming JavaScript from Scratch, Programming HTML From Scratch, CSS3 From Scratch and One ASP.Net From Scratch.  I also wrote a couple Pluralsight courses on creating Web Applications from start to finish, such as Building Web Apps and Services with EF and Web API and a few others.

I learned Angular JS through the efforts of my good friends Ward Bell and John Papa among other patient experts, and presented on Testing Angular JS at Angle BrackAngular2ets.  But then I closed my eyes and when I opened them a moment later, everything had changed.

ASP.NET 4 was now ASP.NET Core, and AngularJS was now Angular 2.  And these were not incremental changes; they were fairly revolutionary.  So I’m swimming as fast as I can to catch up.

Fortunately, the top level of ASP.NET Core is an easy transition from ASP.NET 4, and Angular 2 is not only better than Angular JS, it is easier to learn because it makes more sense.

This year I’m presenting again at Angle Brackets / Dev Intersections**, which is a kick, and in Moscow I’ll be presenting on Angular 2 (!)

That’s my story, what’s yours?  Please use the comments to tell me about your own history with the web.  By creating a common starting ground, we can move forward more quickly.

 

————

* My friend Andy Knight once said “Going independent is trading the illusion of security for the illusion of independence.”

** For $50 off, use the discount word LIBERTY

August 12, 2016 4:19 GMT

Xamarin Dev Days: More Dates & More Cities!

With dozens of cities already announced, Xamarin Dev Days are active around the globe and we’re ready to announce even more cities all around the world! Come join your mobile developer community, brought to you by your local user groups and community leaders, for a full day of hands-on learning and training on how to build, test, and monitor native iOS, Android, and Windows apps with Xamarin.

XDD Redmond Photo

What are Dev Days?

XDD AgendaXamarin Dev Days are community run, hands-on learning experiences. More than just your average meetup, they are FREE, day-long events focused around learning how to deliver native iOS, Android, and Windows apps using existing skills, teams, and code.

After a morning of learning how to build beautiful, cloud-connected mobile apps with Xamarin, you’ll get a chance to put your new knowledge into practice with a hands-on workshop that walks you through the process of building your first cloud-connected, cross-platform mobile app. Xamarin experts will be there to help you get up and running, debug code, and answer any questions you may have.

 

New Xamarin Dev Days Cities!

9/10: Orlando, FL
9/17: Genk, Belgium
9/17: Prague, Czech Republic
9/23: Johannesburg, South Africa
9/24: Karachi, Pakistan
9/24: Warsaw, Poland
9/24: Santo Domingo, Domincan Republic
9/30: Cape Town, South Africa
10/1: Milwaukee, WI
10/1: Detroit, MI
10/1: Raleigh, NC
10/22: Miami, FL
10/22: Sante Fe, Argentina
10/24: Barcelona, Spain
10/28: Zurich, Switzerland
10/29: Munich, Germany
11/05: Singapore
11/05: Istanbul, Turkey
11/18: Rome, Italy

Use the map below to find an event near you or head over to our Xamarin Dev Days website for a full list of current Xamarin Dev Days cities around the world.

 

Get Xamarin Dev Days in Your City

If you didn’t see a city near you on the map but are interested in organizing an event locally, apply as a Xamarin Dev Days host! We’ll provide you with everything you need for a fantastic Dev Days event in your town, including all of the speaker content and lab walkthrough, a hosting checklist, and swag goodies to give away to all of your attendees.

Sponsoring Xamarin Dev Days

We’re working with tons of Xamarin Partners and community members’ companies around the world to help facilitate Xamarin Dev Days. If your company is interested in participating, apply to be a sponsor and get global recognition as a Xamarin Dev Days contributor, as well as access to our worldwide developer community.

The post Xamarin Dev Days: More Dates & More Cities! appeared first on Xamarin Blog.

August 08, 2016 5:38 GMT

Back to the Web – but where to start?

In my previous post I described my desire to revive my web programming skills and tune up to the latest frameworks.  The question is: which frameworks, and in

Illustration depicting signs with a confusion concept.what order?

This is a question that I struggled over for quite a while; checking in with friends with expertise in various aspects of web programming.

I’ve concluded a few things so far:

  • You can’t learn everything at once
  • You don’t need to learn everything at once
  • It is important to leverage what you already know

Given that, I intend, initially to focus on building enough of a back-end to serve my needs both for web applications and for my mobile work.

My second (fun) project will be Angular 2.  I spent a few weeks learning TypeScript and I’ll be using that for my Angular 2 programming.  (If you don’t know TypeScript and you want to do anything with Angular 2, stop reading this and go learn TypeScript now.)

For the back-end I intend to look at how ASP.NET Core wants you to build RESTful services.  For Angular 2, I will go through the Tour of Heroes (again) and then on through the documentation and the Pluralsight courses I mentioned in my previous post.

What I won’t tackle is all the rest of ASP.NET Core, nor Gulp, Grunt, nor any of the related technologies, except to the extent I absolutely need them, and then only as much as I need.

Tooling

The other required bit of work is to choose and learn the editor/IDE.  I’ll do my back end work in Visual Studio 2015 because I know it and it is a great environment for ASP.NET Core.

However, my tool of choice for Angular 2 is VS Code.  This editor, like Angular 2 is cross platform, and it is very clean, very fast, and nicely familiar.  I recommend John Papa’s course on VS Code if you want to come up to speed quickly.

Getting Started

If you are going to create applications in Angular 2 for the Tour of Heroes, or even just for your own tooling around, I highly recommend using the git repository to set up your dev environment.  This is all explained, in detail, here.

Briefly, the steps are:

  • Create a directory (let’s say my-proj)
  • Open a terminal or command window and enter
    git clone  https://github.com/angular/quickstart  my-proj
  • change directory to that project, get rid of the existing .git files, and if you want to create a local repository.
  • You are ready to go.

I shall report back as I dive deeper.

August 07, 2016 3:18 GMT

Join my journey back to the web

For 20 years, I’ve been doing web programming of one sort or another.  I worked through web forms and MVC and SPAs and so forth.  Then, about three years ago, I started to focus on Xamarin, and only keep an occasional eye on the web.  dontpanic

Well, it’s time to brush off those skills and guess what?  Everything has changed.  The new version of ASP.NET is so different, they didn’t give it the next number, they changed its name to ASP.NET Core!  And Angular has given way to Angular 2.  And on and on.

So… over the next couple months I’ll be bringing myself back up to full speed and I thought it would be fun to bring you with me, blogging about the things I find on the way.

I’ll be focusing, initially, on ASP.NET Core and Angular 2 and TypeScript.  If you want to follow along, I suggest the following initial resources:

And, of course, various Podcasts, Blogs and so forth.  I have been and will continue to cover related issues on my own Podcast as well.

My initial impression is that sorting out ASP.NET Core is somewhat confusing; it is hard to know what has carried over and what has not.  I’m sure this will sort itself out quickly.  Angular 2, on the other hand, is a delight, not least because Ward Bell and team has done such a tremendous job on the documentation.

As for TypeScript, if you are already a JavaScript programmer, the only hard part will be learning about type safety and objects.  If you are a C# programmer, then the difficult part will be learning the syntax differences and a bit about scripting.  If you are going to AngleBrackets/DevIntersections, check out my talk on TypeScript for C# Developers.

One difficulty in all of this, is deciding what to learn first.  My own experience to date says that you want to learn TypeScript fundamentals before tackling Angular 2, though learning TypeScript is not difficult.

If you have ADD, as I do, then learn them together, switching back and forth.  If that is not your style, then pick one and dive deep.  In this Blog I’ll be switching among ASP.NET Core, Angular 2, and Xamarin programming, sprinkled with bits and pieces of other technology that strike my fancy.

So, don’t panic, and come along for the fun.

-jesse

August 05, 2016 12:43 GMT

Using Speech Recognition in iOS 10

There's a lot of awesome stuff coming in iOS 10, but one of the things I'm most excited about is that now there's actually an API for doing speech recognition in your apps. It was sort of possible to do this previously through some hackery (I have a bit of experience there), but now Apple is finally making it easy to leverage their great dictation feature in any app. Let's take a look at how easy it is to plug dictation into an app.

Requesting Permission

Similar to other APIs in iOS such as location, your app much request authorization from the user before it can make use of this feature. First you're going to need two new properties in your Info.plist file:

<key>NSSpeechRecognitionUsageDescription</key>  
<string>For science</string>  
<key>NSMicrophoneUsageDescription</key>  
<string>For science</string>  

For this example there are two things you need to request explicit permission from the user in order to do:

  • use speech recognition
  • use and record the microphone

The descriptions you provide in here will be displayed in the prompt iOS presents to the user:

Permissions prompt

Basic Setup

We'll want to add some private members to the controller to track most of the moving parts of the dictation:

private readonly AVAudioEngine _audioEngine = new AVAudioEngine();  
private readonly SFSpeechRecognizer _speechRecognizer = new SFSpeechRecognizer();  
private SFSpeechAudioBufferRecognitionRequest _speechRequest;  
private SFSpeechRecognitionTask _currentSpeechTask;  

This is a mix of some pre-existing AVFoundation functionality and new additions to iOS 10 such as SFSpeechAudioBufferRecognitionRequest.

Next we need to actually trigger that prompt:

public override void ViewDidLoad()  
{
    base.ViewDidLoad();

    Dictate.Enabled = false;

    SFSpeechRecognizer.RequestAuthorization(status =>
    {
        if (status != SFSpeechRecognizerAuthorizationStatus.Authorized)
            return;

        _audioEngine.InputNode.InstallTapOnBus(
            bus: 0,
            bufferSize: 1024,
            format: _audioEngine.InputNode.GetBusOutputFormat(0),
            tapBlock: (buffer, when) => _speechRequest?.Append(buffer));
        _audioEngine.Prepare();

        InvokeOnMainThread(() => Dictate.Enabled = true);
    });
}

When the screen loads it will request authorization from the user, enabling or disabling a button in the UI based on the current authorization status. In a real application you would want to provide some more feedback to the user, of course. Once the user grants permission we also establish a tap on the microphone that appends the received buffer to the current speech request.

Side note: if you fail to set NSMicrophoneUsageDescription in your Info.plist file, attempting to access _audioEngine.InputNode here will cause your app to crash immediately in a way that you can't catch and that doesn't report any useful messages. Major hat tip to Larry O'Brien for helping me get to the bottom of that one, as it was driving me crazy.

Define the UI

For the sake of simplicity, the app's UI will be super simple:

UI

There's a button that will either start or stop the dictation, and a label that will display the output.

Implement Speech Recognition

Okay, now the fun part. First, let's wire up the button:

partial void onDictateTapped(UIButton sender)  
{
    if (_currentSpeechTask?.State == SFSpeechRecognitionTaskState.Running)
    {
        InvokeOnMainThread(() =>
           Dictate.SetTitle("Start Dictating", UIControlState.Normal));

        stopDictating();
    }
    else
    {
        InvokeOnMainThread(() =>
        {
            Dictate.SetTitle("Stop Dictating", UIControlState.Normal);
            DictationResults.Text = "Waiting for dictation...";
        });

        startDictating();
    }
}

With that in place we can now implement startDictating():

private void startDictating()  
{
    NSError error;
    _audioEngine.StartAndReturnError(out error);

    _speechRequest = new SFSpeechAudioBufferRecognitionRequest();
    _currentSpeechTask = _speechRecognizer.GetRecognitionTask(_speechRequest, (result, err) => InvokeOnMainThread(() =>
    {
        if (result == null) return;

        DictationResults.Text = result.BestTranscription.FormattedString;
        DictationResults.BackgroundColor = result.Final ? UIColor.Black : UIColor.Green;
        DictationResults.TextColor = UIColor.White;
    }));
}

In this method we create a new recognition request and speech task. When updates come in from the recognizer we update our label to display the text, and alter its background color based on whether dictation is still in progress or not.

Finally we just need to implement stopDictating():

private void stopDictating()  
{
    _audioEngine.Stop();
    _speechRequest?.EndAudio();
}

It's that easy! Running the app will look like this:

Final app

You can also provide a prerecorded file to the speech recognition APIs and have that turned into text as well, instead of recording audio live from the microphone.

Summary

That might have seemed like a lot, but most of it was just boilerplate, really. The actual code to tap into the microphone, record input, pass it into the speech recognizer, and display the results in real time as the user speaks really only took a few lines of code. I don't know about you, but I'm pretty excited about that.

August 04, 2016 6:30 GMT

Composable Customizations with Xamarin.Forms

In the early days of Xamarin.Forms, if you wanted to start customizing any of the built-in controls in ways beyond what were explicitly exposed on those controls, you probably found yourself creating a lot of custom renderers. Renderers can be a great way to hook into the Xamarin.Forms rendering pipeline and inject your own customizations, but it can quickly get unwieldy if you do it a lot, and is often a larger hammer than you would want to be swinging.

In more recent versions of Xamarin.Forms, the concepts of behaviors and effects were introduced that make these types of customizations much more approachable. In contrast to renderers, where you can only have a single implementation for any given control, behaviors and effects allow you to define customizations at a much more granular level. In addition, you can add any number of behaviors and effects to a control, meaning you can compose them together to get the outcome for which you're looking.

Read the rest of the article over at Visual Studio Magazine.

August 03, 2016 2:18 GMT

Yet Another Podcast #159 – Shawn Wildermuth

Shawn Wildermuth is a world-renowned speaker, and a world-class Pluralsight author.
shawn-head-2016-square-800He has been tinkering with computers and software since he got a Vic-20 back in the early ‘80s. As a Microsoft MVP since 2002, he’s also involved with Microsoft as an ASP.NET Insider and ClientDev Insider. You may have taken one of his more than twenty courses on Pluralsight including his latest: “Building a Web App with ASP.NET Core, MVC, EF and Angular”.

Shawn has authored eight books and innumerable articles on software development. You can also see him at one of the local and international conferences he’s spoken at including TechEd, Oredev, SDC, NDC, VSLive, DevIntersection, MIX, Devteach, DevConnections and Dev Reach. He is one of the Wilder Minds. You can reach him at his blog at http://wildermuth.com.

His Hello World tour has crossed the country and the world in service to his Hello World podcast.

Shawn has been a Microsoft MVP for 14 years, and a friend for two decades.  He is the very definition of a gentleman and a scholar.

 

 

August 02, 2016 8:18 GMT

The Code Review Blues

Code reviews. When incorporated as part of the development process, they may be carried out by a senior level professional (i.e. an architect, team lead, or dev manager), or by multiple developers on your team.  Sometimes you may go through rounds of peer reviews before the code is reviewed by a senior member for final approval.

Often reviews have been conducted with the developer and reviewer sitting side by side, having a discussion about the areas that could use improvement, identifying any use cases or logic that was missing.

Nowadays, just as with everything else, this communication has shifted to an online system, such as Github, which enable reviewers to highlight code and enter comments against it. Developers can reply to those comments if further explanations are needed to justify a coding approach. Additionally, they can make the requested changes and check it back in for another round of reviews.

Some people really enjoy participating in code reviews. Others find it worse than a visit to the dentist. I’ve been in both camps.

When it’s done well…

I have participated in many code reviews during my career, both as code author and reviewer. In the majority of those situations, it was a positive experience. I was fortunate enough to interact with reviewers that were supportive and encouraging. Often they provided constructive feedback on how I could improve the code. When that happened, I walked away from the process feeling more confident in myself and my skills because I learned something new that I would apply to my coding practice going forward.

In situations where I was reviewing someone else’s code, the developer was receptive to the feedback, and appreciated the encouraging remarks I would make about his/her coding efforts as well. These positive experiences compounded over time which brought the team together, and strengthened the working relationships among team members. It resulted in a happy, cohesive, and productive team.

When things go South…

There have been the rare occasions where the process was mired in friction, creating a rift on the team. In some cases, code reviews were used as a tool for the reviewer to chastise developers, exert authority, or cater to an obsessive compulsive nature over code styles. In other scenarios, the code author was simply unwilling to participate in the code review process in a constructive manner.

Let me explain.

Code Shaming

In one case, I worked on a team with an architect who used the code review process to scold developers for coding practices that did not align with his views. He decided to impose his will on the team if anyone disagreed or countered his code review suggestions, regardless of how sound the counter argument was. The more comments he added during the review process, the more his comments became aggressive in nature. Oftentimes, the comments were just repetitive pointing out the same “misdeeds” over and over again.

In this situation, there is no sense of collaboration, togetherness, team work, or respect for any other team member’s views. Team members that are subject to this form of code shaming end up feeling deflated and their self-confidence shaken. This is a situation that eventually drives down the team morale, and overall productivity suffers. Eventually, the team may experience a high turnover rate.

Extreme Code Formatting

In another scenario, a senior team member’s obsessive compulsive nature resulted in busy work for his team members. His main pet peeves were the use of tabs instead of spaces, opening brackets being on the same line as the method or property signature, and other trivial items that did not contribute to code quality. I understand the need for uniformity, but these are areas that waste the developer’s time. The good news here is that this problem is easily solved through the use of code formatting tools that will get the job done automatically when saving changes to your solution files.

If you are working with team members who strive for code formatting perfection, then I recommend that each member of the team make use of one of the many available IDE extensions available, such as Code Maid or Resharper.

Unreceptive to Feedback

As a code reviewer, I have also encountered negative experiences from a team member who was not open to receiving feedback. The code review process seemed to be a source of stress and annoyance for him. In one instance, I highlighted a potential audit issue as a result of his commit, and asked him to correct it.

What was the issue?

Rather than making a simple code change to an existing class, he decided it was more efficient to copy the code into a new class, make the necessary changes, and delete the original class. This resulted in the deletion of the source code history on that file. When I advised him that deleting source code history was a potential audit issue, he did not receive that feedback with an open mind.

Instead of participating in the code review process in a constructive manner, he shrugged off my feedback with responses like “Why does it matter?”, “Nobody cares about keeping the history on that one class anyway”, “You just want to be right”, and so on and so forth.

Considering the work being done was for a large financial institution, where audit trails are a high priority, this was a red flag and I could not let this one slide. Eventually, he conceded to make the change, but this event was the catalyst for another situation I was not expecting.

Merge Conflict Avoidance

On that same project, we were required to perform peer code reviews by commenting on each other’s pull requests. Once the code passed the review process, the reviewer would be responsible for merging the pull request to master.

This was an opportunity that one team member leveraged to his advantage in order to place the burden of dealing with any merge conflicts on the remaining team members. He refused to merge other pull requests unless his pull request was merged first. There was an instance where he insisted on his pull request being merged first when he did not even have a pull request submitted at the time. When I pointed that out, he tried to save face with a reply of: “It’s coming.” A day and a half later, he finally had a pull request to review, while the other pull request sat in limbo.

As the project progressed, this type of behaviour drove the morale of the team down to an all-time low and productivity stagnated.

The Problems (and some suggested solutions)

Yes, that’s problems, with an “s”. There isn’t one factor that contributes to the Code Review Blues. It’s a combination of many.

Different Expectations

The main source of friction during the code review process stems from team members’ differing expectations on the code review’s intended purpose and end result. At a minimum, code reviewers should verify the code is functional, scalable, extensible, maintainable, and secure.

The following tweet from @bliss_ai is a good starting point on questions you should ask yourself, and discuss with your team, as both code author and reviewer:

 

When introducing a code review process to your organization, it is ideal to gather your development team into a room to discuss how this will impact the team. This is also an opportunity to educate the team on effective code review practices, and provide proper training on how the code review tool should be used.

This is also an excellent opportunity to answer the following questions:

  1. What is the main purpose and desired end result for the code review process?
  2. What is the minimum set of criteria that must be met in order to pass a code review?
  3. How will the code review process change each team member’s day-to-day task assignments?
  4. What percentage of time will be allocated into the team’s project plan for code reviews?
  5. Will their participation as code reviewers be held to the same standard as their other deliverables (i.e. will the value they bring to the code review process be rewarded and recognized)?

This training should also be included in the new hire on-boarding process.

Poor Communication and/or Interpersonal Skills

Senior members that are in a position of authority may have been promoted through the ranks due to strong technical skills, but they might be a little rough around the edges when it comes to communication and/or interpersonal skills.  If code reviews with a specific member become a source of contention for the entire team, it might be time to recommend soft skills training for that team member.

If you’re not convinced that soft skills are worth investing in, take the time to read this short article, “Why Soft Skills Matter – Making Your Hard Skills Shine” by MindTools.

Misinterpretation

It’s never easy to critique someone else’s work nor to be on the receiving end of the type of scrutiny code reviews require.

If the feedback you provided is valid and communicated with good intentions, but not well received by the code author, this may be the cause of a deeper, underlying issue. A team member may be resistant to feedback on their code changes because they perceive it to be a personal attack.

If you find yourself getting into a heated exchange with someone who takes offense to the feedback provided, take a step back and analyze the form of communication being used. Think about the following points before you proceed with the review:

  1. Are you relying on an online code review tool as the sole mechanism to provide feedback? If so, is it possible that the tone of the feedback is being misconstrued by the code author?
  2. Do you start or end the review process with face-to-face communication?
  3. Do you also highlight areas that were done really well or is the feedback only focused on what needs to be changed?

In this situation, you may need to experiment with different communication and feedback styles to find an approach to which your colleague is open and receptive. If all else fails, seek advice from a senior level manager.

Final Thoughts

Code reviews are intended to start a conversation about code quality, where all parties emerge from the other side having learned something – whether it is about improving a section of code, adopting better coding practices, or reaching an understanding on the current approach taken.

Everyone should feel confident once the code review process has come to a close that the code submitted performs as it was intended while meeting a defined level of quality.

The code author and reviewer(s) should feel good about the work they are producing, should feel encouraged by the support they receive from each member on the team, and should come out of it with their self-respect and dignity intact.

 

*Special thanks to Donald Belcham and Shane Courtrille for reviewing and providing valuable feedback which contributed to the overall quality of this post.