July 01, 2016 4:55 GMT

Xamarin Developer Events in July

The Xamarin developer community is growing at an extraordinary rate with the help of some amazing user groups around the world. This month, there are tons of new and exciting events just around the corner, like Xamarin Dev Days! The time is now to fully engage in the newly open-sourced Xamarin SDKs and awesome tools provided to deliver beautiful native iOS, Android, and Windows apps. And best of all – Xamarin is now included in all editions of Visual Studio, including the free Visual Studio Community Edition!

Whether you’re brand new to Xamarin (welcome!) or are an experienced Xamarin developer looking to further your education on our newest features, these July events are a great place to find help and information on all of the latest and greatest from Xamarin:

Central Maryland .NET User Group (CMAP) 

  • Columbia, MD, July 5th
  • Xamarin! Build native iOS and Android apps with .NET. with Xamarin MVP, ED Snider

Seattle Mobile .NET Developers 

  • Seattle, WA, July 5th
  • Functional Programming for Mobile Apps with Xamarin MVP, Frank Krueger

Montreal Mobile .NET Developers 

  • Montreal, QC, July 6th
  • Cross Platform Localization Strategies with Xamarin MVP, Lori Lalonde

NCR Xamarin Developers in

  • Noida, India, July 9th
  • First Xamarin Meetup & Training Event

Dutch Mobile .NET Developers Group de

  • Hilversum, Netherlands, July 13th
  • Connected Azure Apps with Xamarin Evangelist, Mike James​ & Apps in Volume

Xamarin Monkey Hub 

  • São Paulo, Brazil, July 14th
  • Xamarin Evolve Recap

Bay .Net User Group 

  • San Francisco, CA, July 14th
  • Building iOS and Android apps in C# with Visual Studio by Xamarin, Craig Dunn

Xamarin Dev Days – Milan it

  • Milan, Italy, July 16th
  • Join your local developer community in Milan for a full day of sessions and hands-on learning

Xamarin Dev Days – Mexico City mx

  • Mexico City, Mexico, July 16th
  • Join your local developer community in Mexico City for a full day of sessions and hands-on learning

.NET DC User Group 

  • Washington, DC, July 19th
  • Xamarin! Build native iOS and Android apps with .NET. with Xamarin MVP, ED Snider

NYC Mobile .NET Developers 

  • New York City, NY, July 19th
  • UI Testing with Xamarin

Minnesota Enterprise Mobile User Group 

  • Minneapolis, MN, July 21st
  • Authenticating & Authorizing Xamarin Users in a Corporate Setting

Mobile CR .NET Developers cr

  • San Jose, Costa Rica, July 29th
  • Primer Xamarin Bootcamp Costa Rica: Desarrollo de apps móviles by Xamarin MVP, Esteban Solano G.

Xamarin Dev Days – Redmond 

  • Redmond, WA, July 30th
  • Join your local developer community in Redmond for a full day of sessions and hands-on learning

Find a Xamarin developer group in your area

Check out this map of all the Xamarin user groups around the world!

Screenshot 2016-06-01 10.51.19

Didn’t see a local developer group but are interested in getting one started?

We’re here to help! Here are some useful resources:

Also, don’t forget to scan the Xamarin Events Forum or developer.xamarin.com/ for even more Xamarin conferences, hackathons, and other events happening in your neck of the woods.

The post Xamarin Developer Events in July appeared first on Xamarin Blog.

July 01, 2016 3:17 GMT

Unit testing with Xamarin.Forms' DependencyService

Xamarin.Forms ships with a built-in Service Locator, called DependencyService, which allows us to register and resolve dependencies. Typically, we use this to enable accessing and invoking platform specific logic in our shared code. The DependencyService is very convenient and easy to use, but it does come with a limitation. Because the DependencyService is part of the Xamarin.Forms framework, it expects that the framework has been initialized prior to using it. This presents a problem when we're trying to unit test some code that uses the DependencyService.

Consider a typical cross platform view model class :

public class MainViewModel  
{
    public string Data { get; set; }
    public void LoadData()
    {
        var database = DependencyService.Get<ISQLite>();
        // Use the database
    }
}

If we wanted to write a unit test for this, it might look like this :

[TestFixture]
public class TestMainViewModel  
{
    [OneTimeSetUp]
    public void Setup()
    {
        // Use the testable stub for unit tests
        DependencyService.Register<ISQLite>(new MyFakeSqliteImplementation());
    }

    [Test]
    public void ViewModelShouldLoadData()
    {
        var vm = new MainViewModel();
        vm.LoadData();
        Assert.AreNotEqual(string.Empty, vm.Data);
    }
}

Unfortunately, if we try to access the DependencyService outside of an iOS/Android/Windows host project, we will receive an exception

You MUST call Xamarin.Forms.Init()

In our unit test, we haven't called Xamarin.Forms.Init() anywhere, and we can't call that method outside of a host. In order to properly unit test the application, we are going to have to make some architectural changes.

Solution #1

The first possible solution would be to move away from the Service Locator pattern completely, and instead architect our app using Dependency Injection. There are many benefits to Dependency Injection over Service Locators, but this usually comes down to developer preference. There are many DI containers that work with Xamarin and I encourgage you to try them out.

Solution #2

If we really want to continue using the Service Locator pattern, but we also want to unit test our code, we will have to abstract Xamarin.Forms' implementation of the pattern.

To begin with, we need to create a Service Locator interface in our shared code project. Notice that this simply provides a way for our shared code to request an object based on a generic key. There is no reference or dependency to Xamarin.Forms at all.

public interface IDependencyService  
{
    T Get<T>() where T : class;
}

Next, we will change our MainViewModel to take in an implementation of the IDependencyService as a parameter. There are now two constructors for the MainViewModel. In the normal case of running our app, we will instantiate and use a new DependencyServiceWrapper() object (see below), which will continue to use Xamarin.Forms' DependencyService object internally. The second constructor allows us to pass in any object that implements the IDependencyService interface, including mocking or stubbing it out for unit testing purposes.

public class MainViewModel  
{
    private readonly IDependencyService _dependencyService;

    public MainViewModel() : this(new DependencyServiceWrapper())
    {
    }

    public MainViewModel(IDependencyService dependencyService)
    {
        _dependencyService = dependencyService;
    }

    public string Data { get; set; }
    public void LoadData()
    {
        var database = _dependencyService.Get<ISQLite>();
        // Use the database
    }
}

The DependencyServiceWrapper class will simply delegate its calls to Xamarin.Forms' built-in DependencyService, giving us the same behavior as before while running the app on a host.

public class DependencyServiceWrapper : IDependencyService  
{
    public T Get<T> () where T : class
    {
        // The wrapper will simply pass everything through to the real Xamarin.Forms DependencyService class when not unit testing
        return DependencyService.Get<T> ();
    }
}

While unit testing, we can create a simple implementation of the interface to use. In this case, we're just going to use a Dictionary<Type, object> to store the implementations. Even though the IDependencyService interface only defined a Get() method, the stub implementation also provides a Register() method. Using the stub means that we never use the DependencyService class, and therefore never have to call Xamarin.Forms.Init() during a unit test.

public class DependencyServiceStub : IDependencyService  
{
    privet readonly Dictionary<Type, object> registeredServices = new Dictionary<Type, object>();

    public void Register<T>(object impl)
    {
        this.registeredServices[typeof(T)] = impl;
    }

    public T Get<T> () where T:class
    {
        return (T)registeredServices[typeof(T)];
    }
}

Finally, we can update our unit test to use the new DependencyServiceStub.

[TestFixture]
public class TestMainViewModel  
{
    IDependencyService _dependencyService;
    [OneTimeSetUp]
    public void Setup()
    {
        _dependencyService = new DependencyServiceStub ();
        // Use the testable stub for unit tests
        _dependencyService.Register<ISQLite>(new MyFakeSqliteImplementation());
    }

    [Test]
    public void ViewModelShouldLoadData()
    {
        var vm = new MainViewModel(_dependencyService);
        vm.LoadData();
        Assert.AreNotEqual(string.Empty, vm.Data);
    }
}
July 01, 2016 8:45 GMT

Xamarin.Forms Behaviors: RotateAction

Previously, I demonstrated using the EventHandlerBehavior and ScaleAction classes to run a scaling animation when an event occurs. The Behaviors Library for Xamarin.Forms has the notion of behaviors and actions. A behavior is attached to a control and listens for something to happen, such as an event firing. When the “something” happens, it triggers one or more actions, such as invoking a method or command. Actions are invoked by behaviors and executed on a selected control.

In this blog post, I’ll demonstrate using the EventHandlerBehavior and RotateAction classes to run a rotation animation when an event occurs.

Rotating a VisualElement when an Event Fires

The EventHandlerBehavior class listens for a specified event to occur, and executes one or more actions in response. It requires you to set an EventName property to the event that you want the behavior to listen to, and an Actions property to one or more actions that should be executed in response to the event firing. Note that the Actions property of the EventHandlerBehavior instance is set indirectly by creating the RotateAction instance as a child of the EventHandlerBehavior instance.

The RotateAction class performs a rotation animation, and allows the following optional properties to be set:

  • TargetObject – an object that is the VisualElement on which to run the animation. If this value is omitted the object the behavior is attached to will be set as the target on which to run the animation.
  • FinalAngle – a double that specifies the angle of the Rotation property to animate to. If this value is omitted the default value of 0.0 is used.
  • Axis – a RotationAxis that specifies whether to rotate on the X, Y, or Z axis. If this value is omitted the default value of Z is used.
  • Duration – an int that represents the length of the animation in milliseconds. If this value is omitted the default value of 250ms is used.
  • EasingFunction – an EasingFunction that specifies any velocity changes in the animation. If this value is omitted the default value of the Linear easing function is used.
  • IsRelative – a boolean that specifies whether to perform relative scaling. If this value is omitted the default value of false will be used. Relative rotation obtains the current Rotation property value for the start of the animation, and then rotates from that value to the value plus the value defined by the FinalAngle property.
  • Await – a boolean that represents whether the animation should be awaited, or whether it should be allowed to complete in the background. If this value is omitted the default value of false will be used.

The following code example demonstrates using the EventHandlerBehavior and RotateAction classes to implement a compound animation that concurrently rotates an Image control on the X, Y, and Z axes:

<Image x:Name="image" Source="monkey.png" Opacity="0" VerticalOptions="CenterAndExpand" />
<Button Text="Run Animation">
<Button.Behaviors>
<behaviors:EventHandlerBehavior EventName="Clicked">
<!-- Compound Animation -->
<behaviors:RotateAction TargetObject="{x:Reference image}"
Duration
="600000"
FinalAngle
="110520" />
<behaviors:RotateAction TargetObject="{x:Reference image}"
Duration
="600000"
FinalAngle
="90360"
Axis
="X" />
<behaviors:RotateAction TargetObject="{x:Reference image}"
Duration
="600000"
FinalAngle
="71640"
Axis
="Y" />
</behaviors:EventHandlerBehavior>
</Button.Behaviors>
</Button>

When the Button.Clicked event fires, three RotateAction instances are concurrently executed over 10 minutes (600000 milliseconds). Each RotateAction instance makes a different number of 360 degree rotations – 307 rotations on the Z axis (110520/360 = 307), 251 rotations on the X axis (90360/360 = 251), and 199 rotations on the Y axis (71640/360 = 199). These values are prime numbers, therefore ensuring that the rotations aren’t synchronized and hence won’t result in repetitive patterns.

The advantage of using the RotateAction is that it’s possible to invoke animations through XAML, rather than having to use C#. In addition, when combined with behaviors, a scaling animation can easily be invoked from XAML when a behavior occurs, such as an event firing, or when a piece of data changes.

The sample application that this code comes from can be downloaded from GitHub.

Summary

The RotateAction class allows rotation animations to be invoked through XAML when a behaviors occurs, such as an event firing, or when a piece of data changes.

June 30, 2016 8:08 GMT

Yet Another Podcast 155 – Humanitarian Toolbox with Bill Wagner

Bill Wagner is a Microsoft Senior Content Developer creating documents and learning htboxmaterials for developers learning the .net platform.  He is also the president and on the board of directors of the Humanitarian Toolbox.

Bill spoke with me about what the Humanitarian Toolbox is, and how developers can get involved in this tremendously important work.

 

 

June 30, 2016 4:52 GMT

Add a Backend to Your App in 10 Minutes

All mobile apps need a backend, and Azure App Service can help bring that backend to life. From simple no-code backends with Azure Easy Tables to fully-customizable ASP.NET Web API backends, Azure has options to help you build a backend to power your mobile app. Once you’ve built a backend for storing data, authenticating users, or sending push notifications, it’s important to be able to easily access it from our mobile apps. Today, we are excited to introduce a new library to help you create cloud-connected apps with Microsoft Azure.

Introducing App Service Helpers

App Service Helpers makes it as easy as possible to add a backend to your mobile application. In just four lines of code, you can create a cloud-connected mobile app with online/offline synchronization and automatic conflict handling, so that your app continues to function even if the user loses network connectivity. App Service Helpers also comes with a preconfigured Xamarin.Forms ViewModel, so that you can bind directly to your data without having to write any additional code.

Create a Cloud-Connected App in 10 Minutes

Even if you don’t have any experience with backend development, Azure and Azure App Service Helpers makes it super easy to get started!

1. Create an Azure Mobile App

There are many ways to create a backend with Azure, but the quickest way to get started is to use Azure Easy Tables. Easy Tables is a no-code backend, similar to Parse, that allows us to add basic data storage capabilities to our apps. To create a new Easy Table, follow the “Create a New Azure Mobile App,” “Add Data Connection,” and “Adding a New Table” sections from our blog post on getting started with Easy Tables. This will create a new no-code backend for your mobile app to pull server data down and push local data up.

2. Add App Service Helpers

Configuring data access in your mobile apps with App Service Helpers is easy. Simply add the App Service Helpers NuGet, initialize the library, pass in your Azure mobile app’s URL, register a data model as a table, and finalize the schema, as seen below:

using AppServiceHelpers;
// 1. Create a new EasyMobileServiceClient.
var client = EasyMobileServiceClient.Create();
// 2. Initialize the library with the URL of the Azure Mobile App you created in Step #1.
// Example: http://appservicehelpers.azurewebsites.net
client.Initialize("{Your_Mobile_App_Backend_Url_Here");
// 3. Register a model with the EasyMobileServiceClient to create a table.
client.RegisterTable();
// 4. Finalize the schema for our database. All table registrations must be done before this step.
client.FinalizeSchema();

That’s it! Only four lines of code, and App Service Helpers will create a local SQLite backing store and handle online/offline data synchronization for you.

3. Subclass App Service Helpers’ View Model

App Service Helpers for Xamarin.Forms includes a preconfigured view model that handles all communication with the EasyMobileServiceClient to help you get started fast. Add the App Service Helpers for Xamarin.Forms NuGet and subclass the BaseAzureViewModel:

using AppServiceHelpers.Forms
public class TodoItemsViewModel : BaseFormsViewModel
{
        public TodoItemsViewModel(IEasyMobileServiceClient client) : base (client) { }
}

BaseAzureViewModel has an Items property, which is an ObservableCollection that is automatically configured based on the model passed into the base class. For CRUD operations, the view model also provides asynchronous methods for adding, updating, and removing items from the table.

4. Data Bind to the View Model

We can now bind directly to the view model created in Step #3, including to a RefreshCommand to automatically handle pull-to-refresh from our table for us.


    
        
            
        
    

There you have it! In just ten minutes, we created a cloud-connected app that runs on iOS, Android, and Windows 10, that automatically manages online/offline synchronizations, conflict handling, and our cloud ViewModels on our behalf.

Download App Service Helpers Today

App Service Helpers is available for download from NuGet, and the complete source code is available on GitHub. To get started building cloud-connected mobile apps today, visit our quick start guide that will walk you through the process of creating a brand-new, cloud-connected Xamarin.Forms application. If you have any suggestions, issues, or feedback, we would love to hear from you on Twitter @pierceboggan or @MikeCodesDotNet, or on GitHub. To learn more about what Azure has to offer mobile developers, check out the latest episode of the Xamarin Podcast, where we share our experiences building cloud-connected mobile apps with Microsoft Azure.

The post Add a Backend to Your App in 10 Minutes appeared first on Xamarin Blog.

June 30, 2016 2:17 GMT

App-to-Market: Show Me the Money

Url for the article: https://visualstudiomagazine.com/articles/2016/06/29/app-to-market-show-me-the-money.aspx

More on This Topic:

Now that you've moved your idea to prototype and developed an actual minimum viable product that you can give to customers for some feedback, you're almost ready to take the next step and make some valuable time and monetary investments in it. It's time to talk about funding: Where to get it, how to get it, and how to use it.

Before we talk about funding, though, a few things you should know about the investors you go after and what makes technology startups riskier for those investors.

June 30, 2016 10:25 GMT

Xamarin.Forms Behaviors: ScaleAction

Previously, I demonstrated using the EventHandlerBehavior and TranslateAction classes to run a translation animation when an event occurs. The Behaviors Library for Xamarin.Forms has the notion of behaviors and actions. A behavior is attached to a control and listens for something to happen, such as an event firing. When the “something” happens, it triggers one or more actions, such as invoking a method or command. Actions are invoked by behaviors and executed on a selected control.

In this blog post, I’ll demonstrate using the EventHandlerBehavior and ScaleAction classes to run a scaling animation when an event occurs.

Scaling a VisualElement when an Event Fires

The EventHandlerBehavior class listens for a specified event to occur, and executes one or more actions in response. It requires you to set an EventName property to the event that you want the behavior to listen to, and an Actions property to one or more actions that should be executed in response to the event firing. Note that the Actions property of the EventHandlerBehavior instance is set indirectly by creating the ScaleAction instance as a child of the EventHandlerBehavior instance.

The ScaleAction class performs a scaling animation, which expands or contracts a VisualElement when invoked, and allows the following optional properties to be set:

  • TargetObject – an object that is the VisualElement on which to run the animation. If this value is omitted the object the behavior is attached to will be set as the target on which to run the animation.
  • FinalScale – a double that specifies the value of the Scale property to animate to. If this value is omitted the default value of 1 is used.
  • Duration – an int that represents the length of the animation in milliseconds. If this value is omitted the default value of 250ms is used.
  • EasingFunction – an EasingFunction that specifies any velocity changes in the animation. If this value is omitted the default value of the Linear easing function is used.
  • IsRelative – a boolean that specifies whether to perform relative scaling. If this value is omitted the default value of false will be used. Relative scaling obtains the current Scale property value for the start of the animation, and then scales from that value to the value plus the value defined by the FinalScale property.
  • Await – a boolean that represents whether the animation should be awaited, or whether it should be allowed to complete in the background. If this value is omitted the default value of false will be used.

The following code example demonstrates using the EventHandlerBehavior and ScaleAction classes to implement a scaling animation that expands and contracts an Image control when a Button is clicked:

<Image x:Name="image" Source="monkey.png" Opacity="0" VerticalOptions="CenterAndExpand" />
<Button Text="Run Animation">
<Button.Behaviors>
<behaviors:EventHandlerBehavior EventName="Clicked">
<behaviors:ScaleAction TargetObject="{x:Reference image}"
FinalScale
="2.0"
Duration
="3000"
EasingFunction
="SpringIn"
Await
="true"/>
<behaviors:ScaleAction TargetObject="{x:Reference image}"
FinalScale
="1.0"
Duration
="3000"
EasingFunction
="SpringOut" />
</behaviors:EventHandlerBehavior>
</Button.Behaviors>
</Button>

When the Button.Clicked event fires, two ScaleAction instances execute over 6 seconds. The first ScaleAction instance expands the Image instance to twice its size over 3 seconds (3000 milliseconds), and uses the SpringIn easing function to cause the animation to accelerate towards the end. Once the first ScaleAction instance has executed the second ScaleAction instance begins. This is because the first ScaleAction instance sets the Await property to true. The second ScaleAction instances causes the Image to contract back to its original size over 3 seconds (3000 milliseconds), and uses the SpringOut easing function to cause the animation to decelerate towards the end.

The advantage of using the ScaleAction is that it’s possible to invoke animations through XAML, rather than having to use C#. In addition, when combined with behaviors, a scaling animation can easily be invoked from XAML when a behavior occurs, such as event firing, or when a piece of data changes.

The sample application that this code comes from can be downloaded from GitHub.

Summary

The ScaleAction class allows scaling animations to be invoked through XAML when a behavior occurs, such as an event firing, or when a piece of data changes.

June 29, 2016 9:04 GMT

Me gusta, no me gusta, me gusta…

DSC_0001
Thinking

Hace poco más de un mes tuve la oportunidad de asistir a un evento de desarrollo de software donde me llamó mucho la atención una charla que mencionaba en su título “soft skills”. ¿Se podría traducir como habilidades sociales? El resto de ponencias trataban sobre tecnología pero en ésta era lo último que importaba: importaban las personas.

Me resulta curioso, y a veces desconcertante, que con el paso de los años la informática, mi pasión desde que soy chico, tiene más sentido para mí si lo que haga en relación involucra a las personas. Hoy en día, en mi trabajo, disfruto mucho yendo a la mesa de un compañero y preguntándole ¿te puedo ayudar en algo? Si tiene un problema, algo que le atasca, si puedo lo cojo para que él avance, e intento resolverlo. No me genera tanta ilusión el coger un problema técnico y enfangarme hasta los codos (que un poco también), como hacer que ésa persona tenga un momento de tranquilidad, pueda enfocarse en otro tema y, si he tenido “suerte”, volver al día siguiente con una solución a nuestro problema. Porque los problema en los equipos son tuyos y míos, de los dos. Esto lo aprendí de mi primer trabajo en Microsoft y me ha acompañado ya más de diez años…

Volviendo al tema, soft skills, “capacidades suaves” (qué romántico ¿no?), habilidades sociales. De todo lo que John Sonmez, la persona que lo impartía, habló, me dejó clavado en el asiento la siguiente afirmación:

Todo lo que te gusta en la vida dejará de gustarte

Quizá para ti que leas esto es de cajón, lo has pensado 1.000.000 de veces, o no te mueve nada por dentro. Para mí fue entre revelador y doloroso. ¿Cómo que todo lo que me gusta en mi vida dejará de gustarme? ¿Que la informática dejará de gustarme? ¿Que dejará de gustarme leer sobre Steve Jobs? ¿Incluso una pareja? Vamos no me jodas, pensé.

Lo siguiente que se me vino a la cabeza fue: ¿si todo lo que me gusta me puede dejar de gustar, por qué entonces me esforcé tanto en ser un buen novio, en hacer mi trabajo de puta madre, por qué he decidido levantarme todos los días a las 6 de la mañana para dedicar 1 hora a mis proyectos personales? Si todo me puede dejar de gustar, quizá no merezca tanto la pena el esfuerzo…

Digamos que aún, un mes y pico después, no tengo una estrategia clara para mí mismo respecto a esto. En 2015 conocí a un amigo de un amigo, una persona que me saca como unos veinte años que, en un momento hablando en privado, me regaló una joyita:

Marcos, ¿tú sabes qué he aprendido en la vida con mi edad? Que el truco está en el movimiento

Yo a veces tengo tantas cosas que me gustaría hacer que, todavía a veces me ocurre, acabo por no hacer ninguna de ellas, sólo porque no me decido, no las sé priorizar. Sin darme cuenta las ordeno por la vinculación emocional que me generan y, a veces, es mejor dejar las emociones a un lado. Últimamente estoy poniendo en práctica una técnica súper sencilla: cuando no sé que hacer, hago cualquier cosa. (La madre que me trajo porque la conozco hace años, pero la he usado más bien poco…) Paso de la ansiedad de no saber escoger, al disfrute de hacer algo. Sea cocinar, escribir esto que lees, u ordenar una estantería.

Cuando no sabes que todo te puede dejar de gustar, y algo te deja de gustar, le puedes coger hasta asco. A mí me ha pasado en algún momento con la informática. De tanto que me gustaba, de tanto tiempo que le dedicada, le cogí asco. Simplemente me vino bien entrelazarla con otras cosas, otros hobbies por ejemplo. Y me volvió a gustar.:-)

Por último, cuando estás en un momento en el que algo no te gusta, te estás dando cuenta además, y se genera una situación incómoda, lo mejor que me ha funcionado hasta el día de hoy es tirar de disciplina. Si tengo que seguir haciéndolo, el componente de disfrute, que está bajo mínimos, lo voy cambiando por el “hacerlo porque sí”, con la consciencia de que esto que me está pasando es normal, nos ocurre a todas las personas, y sigo con ello porque en el fondo sé que es algo bueno en mi vida. John Sonmez, además, es el consejo que dio en su charla: ser disciplinado.

Si eres capaz de aquello que te gusta vivirlo gota a gota quizá no te ocurra jamás todo esto. O quizá sí pero en cosas muy puntuales. Sea como sea, recuerda que todo aquello que te gusta hoy, te dejará de gustar en algún momento. Depende de ti, de mí, qué hagamos entonces. Si sigue teniendo sentido, sigue haciéndolo, y busca el disfrute en otra cosa. Lo que sea: vete a lavar el coche, que seguro tiene más polvo que la tele por detrás.

PD: Siempre que escribo estas cosas me imagino que habrá alguien que lo lea y se sentirá identificada/o. Si es tu caso, ¿eras consciente de esto, cómo lo gestionas? ¡Muchas gracias de antemano!


June 29, 2016 2:21 GMT

Xamarin Dev Days is Back and Coming to a Town Near You

After great success last year, we’re bringing Xamarin Dev Days back in 2016 and are working with our partners and community members to bring full day mobile development events to a town or city in your area!

What are Dev Days?

Xamarin Dev Days are an intense, hands-on learning experience. More than just your average hackathon, they are free, day-long community events focused around learning how to build native iOS, Android, and Windows apps with C#, Xamarin, and partner technology through valuable sessions from Xamarin, our partners, and your local developer community leaders.

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 hands-on labs, mini-hacks, and an opportunity to interact with your community. Xamarin experts will be there to help you get up and running, debug code, and have fun building mobile apps and experimenting with the latest mobile technology.

Today, we are very excited to announce the first round of global Xamarin Dev Days:

7/16 – Milan, Italy
7/16 – Mexico City, Mexico
7/23 – Jacksonville FL
7/30 – Redmond, WA
8/06 – Pune, India
8/13 – Boston, MA
8/20 – Madison, WI
8/20 – Sydney, Australia
8/27 – Amsterdam, Netherlands
9/10 – São Paulo, Brazil
9/17 – Lisbon, Portugal
9/24 – Curitiba, Brazil
11/12 – Kansas City, KS

Screen Shot 2016-06-28 at 15.19.34

More cities to come!

This is just the start for Xamarin Dev Days this year. We’re continuing to add more cities every week, but want to know where you want us to come next. Head on over to the Xamarin Dev Days website to see a current list of cities we have planned for this year.

Get a Xamarin Dev Days in Your City

If you didn’t see a city on the list near you but would be interested in organizing one of an event locally, apply as a host! We’ll provide you with everything you need for a fantastic Dev Days event in your town.

Sponsoring Xamarin Dev Days

We’re working with tons of Xamarin Partners and community members’ companies around the world to 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 and access to our world-wide developer community.

The post Xamarin Dev Days is Back and Coming to a Town Near You appeared first on Xamarin Blog.

June 27, 2016 6:14 GMT

Podcast: Building Connected Apps with Azure Mobile Apps

This week on the Xamarin Podcast, Pierce and I share our experiences in building connected apps with Azure Mobile Apps. We’ll walk you through the different options you have for mobile backends in Azure and take a look at other technologies, such as Microsoft Cognitive Services, Azure Functions, and Azure Search, that you can add to bring your mobile backend to the next level.

Subscribe or Download Today

Knowing the latest in .NET, C#, and Xamarin is easier than ever with the Xamarin Podcast! The Xamarin Podcast is available from iTunes, 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 building connected apps with Azure, and don’t forget to subscribe!

The post Podcast: Building Connected Apps with Azure Mobile Apps appeared first on Xamarin Blog.

June 24, 2016 8:02 GMT

How to be Successful with Mobile DevOps

The rise of smartphones and changing user behavior over the past seven years have forced organizations to start delivering more and more mobile solutions, with apps a big part of this. There are unique challenges when it comes to enterprise mobile app delivery, however. The ecosystem is fragmented, yet users continue to have high expectations. It’s the “age of the customer” as Forrester puts it, and enterprises need to not only live up to their expectations but exceed them in order to stay competitive.

“After an unsatisfactory experience with a mobile business app, 65% of users will abandon the app after two or fewer uses and 8% will abandon immediately.”
–Xamarin Mobile Business User Survey, 2015

Speed, quality, and continuous iteration are critical to the success of mobile apps, no matter if the audience is comprised of customers, internal employees, or business partners. DevOps can provide an efficient way to embrace this complex ecosystem and streamline mobile app delivery for building, testing, and continuously iterating. The concept of DevOps is not new, and companies have been implementing it for a few years now, but how do you take this to the mobile world and address the unique requirements there?

Download our Mobile DevOps Overview whitepaper to learn more about:

  • The unique challenges of enterprise mobile app delivery
  • Why you should consider implementing DevOps in your mobile lifecycle
  • The challenges with applying DevOps to mobile
  • How to implement DevOps in the mobile lifecycle and be successful with it
    • Why starting with people and culture is critical
    • Creating a living, breathing plan that you can constantly update based on market changes and user feedback
    • Being smart and efficient about how you build your apps
    • Taking into account all of the integrations that mobile apps have and planning ahead for easy scalability
    • Treating testing as an enabler of DevOps and not a bottleneck
    • Continuously iterating to keep up the quality of the apps, and keep users engaged

 

Get the white paper
 

The post How to be Successful with Mobile DevOps appeared first on Xamarin Blog.

June 22, 2016 8:16 GMT

Xamarin.Forms Shared Project XAML Headaches

At first I was going title this post Creating a Xamarin.Forms Shared Project App? Do This First! And the contents of that post were going to solve one of the problems that every developer faces when creating a Forms application using shared projects. Namely, that of referencing custom controls created in the shared project within XAML when running under both iOS and Android. Not too complicated a subject, as it’s a very easy fix … but as you may have guessed by the original title of the post – I have a tendency to forget to “implement the solution” right away. I figured by writing it down, I would never forget again – saving myself a moment of “what the ???” later.

But then this morning (about an hour ago as I type this) I found that the new Xamarin Studio 6 gives a workaround / solution to this … by default! Instead of having that let me off the hook and not writing at all – I still wanted to outline the problem and the quick solutions – both the one I was using and the one Xamarin Studio 6 provides.

The Problem

Whether you need to extend one of the built-in Xamarin.Forms controls, or create a brand new one altogether, an app of sufficient complexity will call for a custom control at some point. Once the control is built, in order to use it, you need to reference it in your XAML page. In order to do so, the following line is added to the XML attribute section for the content page or view:

xmlns:local="clr-namespace:DoThisFirst;assembly=DoThisFirst"

The

clr-namespace
specifies the namespace of where the control can be found, and the
assembly
is the DLL or EXE.

Pretty easy & simple.

Except when one is using a shared project. Shared projects do not emit a separate assembly when compiled (I’ve written about them previously, here and here). Instead the code is directly compiled into the platform project’s assembly.

Great, what’s the issue?

By default, when creating a new solution with Xamarin Studio, the assembly names that are emitted for iOS and Android are named differently. In the case of our “DoThisFirst” project, the assembly names are “DoThisFirst.iOS” and “DoThisFirst.Droid”.

This means that we’re not able to use the following any longer, as it will not work across both platforms (or in this case neither) at the same time:

xmlns:local="clr-namespace:DoThisFirst;assembly=DoThisFirst"

The assembly running the code “DoThisFirst.iOS” or “DoThisFirst.Droid” do not match up with the “assembly” portion of the line above … a run time error (or compile time if XAML compilation is turned on) will occur. It’ll be a

System.IO.FileNotFoundException
.

How To Fix It?

Super, super simple. Change the output assembly’s name in both the Droid’s & iOS’ project options to be the same thing. This is done in Xamarin Studio through the project options -> build -> output node. And on iOS, make sure you do it for both the simulator & device platforms.

Project Options

Because if you would ever happen to ship an IPA off for testing without first running it on device, and the output name wasn’t correct – it’ll crash – and that would be embarrassing. Not that you would do that … but somebody might (as I look around nervously).

There’s also another way to fix this issue, and it’s the way I alluded to earlier in this post. That’s by omitting the assembly attribute from the declaration altogether. So it would now look like:

xmlns:local="clr-namespace:DoThisFirst"
. Xamarin Studio now creates this attribute for you when creating a new XAML content page, and to be honest, I didn’t know one could only declare the namespace and not the assembly. Pretty cool.

To be honest, I still prefer to specifically call out the assembly in addition to the namespace in the declaration, only if to be completely clear. But I was happily surprised to see the local namespace was added by default.

In Summary

Change those output assembly names when working with Xamarin.Forms shared projects! It’ll save you some headaches when working with custom controls. It will also make life easier if you ever need to start messing around with

System.Reflection.Assembly
and all the goodness that it supplies.

June 22, 2016 3:49 GMT

Adding Facial Recognition to Your Mobile Apps

2016-06-21_1746Whether it’s automatically tagging friends in our Facebook photos or “live filters” on Snapchat, facial recognition is increasingly becoming a large part of our everyday lives. Adding facial recognition to software in the past was extremely challenging, however. Now, though, Microsoft Cognitive Services makes it as easy as a few lines of code—for free.

Whether you’re building consumer or enterprise applications, there’s a Microsoft Cognitive Services API that will make your app more innovative and pleasant to use. In this blog post, you’ll learn how to add facial recognition with Microsoft Cognitive Services’s Face APIs to an employee directory app, so we can identify an unknown employee from a photo.

Introducing the Face APIs

Microsoft Cognitive Services lets you build apps with powerful algorithms in just a few lines of code, providing 22 APIs that use artificial intelligence and machine learning to do everything from OCR, to speech and facial recognition. APIs are broken down into five main groups: vision, speech, language, knowledge, and search. The Face APIs from Microsoft Cognitive Services allow you to detect human faces, organize people into groups, find similar faces, and identify previously-tagged faces in images.

Xamarin has grown a ton over the past few years, and sometimes it’s tough to know exactly who everyone is. The great thing about Microsoft Cognitive Services is it’s not only great for innovative apps, but for all types of apps, including apps built for the enterprise. In this blog post, let’s build an employee directory app that identifies an employee from a photo to help ensure I don’t get into an awkward situation at a company party if I don’t know someone I should.

To get started for free, visit the Microsoft Cognitive Services subscription page, and subscribe to the Face APIs. Once registered, you should have a free subscription to the Face APIs, including API keys.

Subscription page for the Face APIs, including API keys.

Download the starter code for the Xamarin employee directory app, which we’ll extend to use facial recognition to identify employees from a photo.

Identifying Employees with Facial Recognition

To identify a person in a photo, we must first train the facial recognition model. Identifying the person in a photo is as easy as these four steps:

  1. Create a person group.
  2. Add people with corresponding faces to that person group.
  3. Train the facial recognition model.
  4. Detect and identify the people in a photo.

Training the Facial Recognition Model

To get started, open EmployeesViewModel and add a new method named RegisterEmployees. We start off by creating a new person group, which is just a container for a group of people. After we’ve created a person group, we need to add people to that group. Each person also needs one or more faces from which we can identify them. Finally, we need to train the person group. This will identify the unique features of a each face that can later be used to identify a person.

async Task RegisterEmployees()
{
    var faceServiceClient = new FaceServiceClient("{FACE_API_SUBSCRIPTION_KEY}");
    // Step 1 - Create Person Group
    personGroup = Guid.NewGuid().ToString();
    await faceServiceClient.CreatePersonGroupAsync(personGroupId, "Xamarin Employees");
    // Step 2 - Add persons (and faces) to person group.
    foreach (var employee in Employees)
    {
        // Step 2a - Create a new person, identified by their name.
        var p = await faceServiceClient.CreatePersonAsync(personGroupId, employee.Name);
        // Step 3a - Add a face for that person.
        await faceServiceClient.AddPersonFaceAsync(personGroupId, p.PersonId, employee.PhotoUrl);
    }
    // Step 3 - Train facial recognition model.
    await faceServiceClient.TrainPersonGroupAsync(personGroupId);
}

In production, the process of creating a person group, adding people and faces, and training the model would probably be done on your backend. For example, when you provision a new employee on your backend, a new person (and corresponding face) would automatically be added and the model would be retrained.

Next, call RegisterEmployees from the constructor of the EmployeesViewModel to ensure that we are configuring our facial recognition model at startup. We’re now ready to identify employees!

Facial Detection and Identification

Now that we’ve properly trained our facial recognition model, we can use Microsoft Cognitive Services to identify a person from a photo. Because we’re using the MVVM pattern in our employee directory app, we can use commanding to respond to events on our user interface and execute code in our view model. Navigate to the ExecuteFindSimilarFaceCommandAsync method in EmployeesViewModel, which is a backing method for our command where we’ll write the logic to identify an employee.

First, we need to take a photo from which we can identify an employee. We can use the Media Plugin for Xamarin and Windows to take or select photos from shared code:

MediaFile photo;
await CrossMedia.Current.Initialize();
// Take or select a photo using the Media Plugin for Xamarin and Windows
if (CrossMedia.Current.IsCameraAvailable)
{
    photo = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
    {
        Directory = "Employee Directory",
        Name = "photo.jpg"
    });
} else {
    photo = await CrossMedia.Current.PickPhotoAsync();
}

Now that we have a photo, let’s pass that to Microsoft Cognitive Services to identify the employee:

using (var stream = photo.GetStream())
{
    var faceServiceClient = new FaceServiceClient("{FACE_API_SUBSCRIPTION_KEY}");
    // Step 4a - Detect the faces in this photo.
    var faces = await faceServiceClient.DetectAsync(stream);
    var faceIds = faces.Select(face => face.FaceId).ToArray();
    // Step 4b - Identify the person in the photo, based on the face.
    var results = await faceServiceClient.IdentifyAsync(personGroupId, faceIds);
    var result = results[0].Candidates[0].PersonId;
    // Step 4c - Fetch the person from the PersonId and display their name.
    var person = await faceServiceClient.GetPersonAsync(personGroupId, result);
    UserDialogs.Instance.ShowSuccess($"Person identified is {person.Name}.");
}

That’s it! All of our facial recognition logic is now complete. Jump over to EmployeesPage.xaml, where we’ll add a ToolbarItem to the navigation bar for users to click on to launch the camera and identify an employee:


     

We can now identify employees. The great thing about Xamarin.Forms is you can both build great mobile apps that run on iOS, Android, and Windows 10 mobile, but also desktop apps with Xamarin.Forms for UWP. Let’s identify a photo of me using the employee directory app and a Windows 10 laptop:



Wrapping Up

In this blog post, we used Microsoft Cognitive Service’s Face APIs to identify an unknown employee from our employee directory by taking or selecting a photo. To learn more about Microsoft Cognitive Services, watch the “Build ‘Smart’ into your app with Microsoft Cognitive Services” session from Xamarin Evolve 2016. For more examples of using Microsoft Cognitive Services to build smart mobile apps, and to download the complete code for this blog post, check out my smarter-apps GitHub repository.

The post Adding Facial Recognition to Your Mobile Apps appeared first on Xamarin Blog.

June 21, 2016 7:19 GMT

Making Your iOS Apps IPv6 Ready

On June 1, Apple started enforcing a new policy whereby all iOS applications must support IPv6-only network services in iOS 9. While Apple states that most apps will not need to be changed or updated, your app may be using a few libraries that need to be updated before you submit your next update.

NetworkFrameworks

Issues and Fixes

Here are some of the most common issues that you may have lingering in your code and how to fix them.

Hard Coded IP Addresses

All newly created IP Addresses will need to be IPv6 or converted to IPv6 if available. Our recommendation is to always use the hostname when possible, but if you are not able to, don’t fear, because it’s super simple with the .MapToIPv6() extension method. This is more of a quick fix, as you’ll never get a pure IPv6 connection; in this case you could also manually convert any IP to a byte array, or simply use IPAddress’s TryParse method to parse any IPv6 address. Additionally, check out some of the nifty methods in System.Net.Dns that can help resolve the IP Address for you if IPv6 is available or not. If you are using HttpClient, BasicHttpBinding, or WebRequests there are no changes needed unless using hard coded IP addresses as discussed above.

There may, of course, be certain older devices that can’t update to support IPv6 and as a developer you are forced to connect using IPv4. If you are stuck in this situation, you’ll have to mention it when submitting your app for review.

Sockets and AddressFamily

When creating .NET Sockets, you’re able to specify the AddressFamily as InterNetworkV6, which will ensure the socket is created using the IPv6 protocol.

Before:

var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

After:

var socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);

Additionally, you can opt not to pass an AddressFamily, in which case Socket will use Dual Mode.

Connectivity Plugin

The Connectivity Plugin for Xamarin and Windows relies on the core reachability sample that Apple created to help developers handle connection state in their app. Since its original release, the reachability sample has been updated and recently the Connectivity Plugin has been updated to be IPv6 compatible. Simply update to the latest release, 2.2.2, and your app will be ready to submit.

Learn More

Be sure to read through the IPv6-only networks announcement from Apple. And their guide on ensuring compatibility with DNS64/NAT64 networks to test an IPv6 network on your Mac.

The post Making Your iOS Apps IPv6 Ready appeared first on Xamarin Blog.

June 21, 2016 3:48 GMT

Golfing for the Peyback Foundation and Children's Hospital - Results

The Results of the Morning and Afternoon Rounds:

The Morning Results


The Afternoon Results


We had a long and winding day on Monday.  We went and scored the Morning and Afternoon portions of the Children's Hospital - Peyback Foundation Charity Golf Tournament.  Each portion was flighted.  Pictures were taken of each team while on the course.  The pictures were immediately uploaded to the scoring system for display on the scoreboard.  The flighting of each portion was performed by the application.  As each portion finished, the teams were placed into each flight.  Each team's scores were shown in the flight as well as the team pictures.

The scoring system is hosted in Azure.  The picture upload is done via an iPhone application written in C#/Xamarin.

I learned a few new things that I will work on and resolve the next time around.

June 20, 2016 9:35 GMT

Navigate and then send data back with Xamarin.Forms and MVVM Light

…By Jesse Liberty & Eric Grover

The Challenge : Fetch

Navigate to a second page, present an Editor (multi-linefetch entry) and then send the data back to the original page (and navigate back at the same time).

Behaviors, Commands and Messages, Oh my!

Behaviors will let us turn events into commands, commands will let us handle events in the view model, and messages will let us communicate from a ViewModel to another ViewModel or to a page.

We’ll combine all this with the power of MVVM Light.

Starting on the first page

We’re going to have two pages: firstPage and the notesPage.     NotesPage will have just two controls: an Editor and a button.  FirstPage will have a button to set things going.

Here’s the button on FirstPage:

    <Button Text="Notes" Command="{Binding NotesCommand}"
            TextColor="{StaticResource TextForegroundColor}"/>

Notice that the button refers to a command.  In the first page’s view model we need to handle that command.  To do so we’ll declare a backing variable and a RelayCommand property:

private RelayCommand notesCommand;

public RelayCommand NotesCommand => notesCommand ??
                     (notesCommand = new RelayCommand( GetNotes ));

That RelayCommand calls the GetNotes method,

public void GetNotes()
{
  var navigateTo = typeof(NotesPage);
  var message = new NavigationMessage { NavigateTo = navigateTo };
  Messenger.Default.Send( message );

Here I’m sending a message to the page that I want to navigate to the NotesPage.  For this to work, I’ve registered this message in my BaseViewPage (from which all my other views derive).

       Messenger.Default.Register<NavigationMessage>(
         this,
         HandleNavigation);
 

 

Here’s the implementation for HandleNavigation…

public async void 
   HandleNavigation(NavigationMessage navigationMessage)
  {
    var target = 
        Activator.CreateInstance(navigationMessage.NavigateTo);
 
    await Navigation.PushAsync((ContentPage) target);
 
  }

Once we get to NotesPage we need a way to gather the info and send it back to FirstPage. Here’s the XAML:

<StackLayout>
 
    <Editor Text="{Binding Note, Mode=TwoWay}" 
              BackgroundColor="Aqua">
 
      <Editor.Behaviors>
        <behaviors:CompletedCommandBehavior 
                Command="{Binding EditorCompleted}"/>
      </Editor.Behaviors>
    </Editor>
    
    <Button Text="Save"/>
 
  </StackLayout>

As you can see, this code depends on a CompletedCommandBehavior. One of the principal jobs of a behavior is to help turn an event into a command.  Check out this excellent article by David Britch

Before we dive into behaviors, let’s look at what is happening in  NotesViewModel. We start by creating a private  property Note

 
 
  private string note;
  public string Note
  {
    get { return note; }
    set { Set( ( ) => Note, ref note, value ); }
  }

We then create a public RelayCommand property

private RelayCommand editorCompleted;
public RelayCommand EditorCompleted => editorCompleted ??
     (editorCompleted = new RelayCommand( NotifyEditorCompleted ));

Notice that the method it is tied to is NotifyEditorCompleted.  Here is that method,

private void NotifyEditorCompleted()
{
 
  var navBack = new NavigationBackMessageWithText();
  navBack.MessageText = Note;
  Messenger.Default.Send(navBack);
}

So, when the editor fires its completed event we instantiate a NavigationBackMessageWithText, set its MessageText to the contents of Note, and then use MVVM Light’s Messenger to send that message.

Key is that we must register for that message in the calling page’s view model (!).   This is classic publish/subscribe.  Our base page subscribes to this message for the pages, and PageOneViewModel subscribes to it as well.

Messenger.Default.Register<NavigationBackMessageWithText>
  (
    this,
    HandleNavigationBack
  );

Here’s the implementation of HandleNavigationBack,

public void HandleNavigationBack(
           NavigationBackMessageWithText message)
  {
    note = message.MessageText;
  }

Creating the Behavior

Let’s return to the behavior, and take apart the one we created for this task.  First, we create the BindableProperty, which we name CommandProperty

public static readonly BindableProperty CommandProperty =
         BindableProperty.Create( 
"Command", typeof( ICommand ), 
typeof( CompletedCommandBehavior ), null );

We then created a property for the Editor itself which we’ll call AssociatedObject.  This will be needed to set the binding context of our behavior to the binding context of the page it is used in,

public Editor AssociatedObject { get; set; }

Now we create our Command property.  Notice that it is of type ICommand,

public ICommand Command
{
  get { return (ICommand) GetValue(CommandProperty); }
  set {  SetValue(CommandProperty, value);}
}

We have three jobs left in creating this behavior,

  1. Handle attaching and detaching the Completed event
  2. Handle the work we want to do when the Editor fires its Completed event
  3. Handle the Binding Context

We attach and detach the Completed event by overriding the OnAttachedTo and the OnDetachingFrom methods,

protected override void OnAttachedTo( Editor bindable )
   {
     base.OnAttachedTo(bindable);
     AssociatedObject = bindable;
      bindable.Completed += HandleEditorCompleted;
      bindable.BindingContextChanged += OnBindingContextChanged;
   }

 
   protected override void OnDetachingFrom( Editor bindable )
   {
     base.OnDetachingFrom(bindable);
     bindable.Completed -= HandleEditorCompleted;
     AssociatedObject = null;
 
   }

Notice that we also register for the BindingContextChanged event.  We’ll manage that in just a moment.   Here is the code for executing our command when the EditorCompleted event is raised,

private void HandleEditorCompleted(object o, EventArgs e)
{
  this.Command.Execute(null);
}

That was easy.  Now, here’s the code for managing the BindingContextChanged event which passes through to the overridden OnBindingContextChanged method,

void OnBindingContextChanged( object sender, EventArgs e )
  {
    OnBindingContextChanged( );
  }
 
  protected override void OnBindingContextChanged( )
  {
    base.OnBindingContextChanged( );
    BindingContext = AssociatedObject.BindingContext;
  }

Notice that we’ve tied the BindingContext of the Behavior to the binding context of the Editor control.

Note, the button in the Notes page is just a way to cause the focus to move away from the text entry field.  It isn’t wired up to a command.
That’s it! The only tricky parts are creating the message handling and creating the behavior and both of these are well documented on the web.

June 20, 2016 6:05 GMT

Podcast: WWDC 2016 Recap

This week on the Xamarin Podcast, Pierce and I cover everything you need to know as a mobile developer from Apple’s WWDC 2016, including new additions and upgrades to iOS, macOS, watchOS, and tvOS.

Subscribe or Download Today

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

The post Podcast: WWDC 2016 Recap appeared first on Xamarin Blog.

June 20, 2016 2:31 GMT

Alexa, Is My Infrastructure on Fire?

I recently broke down and purchased an Amazon Echo after hearing enough good things about it, and also seeing how straightforward it looked to develop for it. It's no secret that I'm a big fan of Datadog, so naturally I felt like I needed to mix the two. I've previously covered exposing Datadog metrics through Hubot, so I figured I'd try to do something similar for the Echo.

I decided to create and host the skill through an AWS Lambda function which made it really easy to get started and deploy. There's plenty of documentation around on creating skills in Lambda so I won't really get into that part here. I also went with the Serverless framework to simplify the development and deployment processes, but that's not actually too important to the implementation here. Ultimately it's just a simple Lambda function tied to an Alexa skill.

At present, it exposes the current CPU levels of any hosts in your account. For example, saying:

Alexa, ask Datadog to check the CPU

will result in a response along the lines of:

Here are the current CPU loads. Gregs MacBook Pro is at 7%. Gregs iMac is at 4%

I think that's pretty awesome, so let's take a look at how to implement it.

Defining the Interaction Model

First we need to definte the skill's interaction model in Amazon's developer console.

Intent Schema

The intent schema is the primary manifest of what your skill can do, and how users will interact with it. For this skill we'll keep it simple and just expose a single intent for querying:

{
  "intents": [
    {
      "intent": "QueryIntent",
      "slots": [
        {
          "name": "Query",
          "type": "QUERY_LIST"
        }
      ]
    }
  ]
}

Eventually it would be great to build this out further and make the skill more conversational and interesting, but this is a sufficient starting point.

Custom Slot Types

In the intent schema you may have noticed the QUERY_LIST type, so now we need to actually define that. This is a custom slot that defines a list of the types of queries we can do. For now it will just contain a single value:

Type Values
QUERY_LIST cpu

This provides a nice place to expose more formal query types as the skill gets extended.

Sample Utterances

Finally, we need to give Amazon a list of sample utterances for the skill in order to teach it how each intent can be interacted with. We'll give it a few different ways to be invoked:

QueryIntent query {Query}  
QueryIntent check {Query}  
QueryIntent to query {Query}  
QueryIntent to check {Query}  
QueryIntent to query the {Query}  
QueryIntent to check the {Query}  

Implementing the Skill

With all that configuration out of the way, let's look at the code involved in implementing the skill. Just like in that Hubot plugin I created, we'll leverage the dogapi package to query the Datadog API. I'll only include the interesting bits in this post, but the full sample can be found on GitHub.

Talking to Datadog

First, let's build out a function to query CPU values from Datadog:

import dogapi from 'dogapi';  
import Promise from 'bluebird';

const queryDatadog = Promise.promisify(dogapi.metric.query);

function queryCPU() {  
  const now = parseInt(new Date().getTime() / 1000);
  const then = now - 300;
  const query = 'system.cpu.user{*}by{host}';

  return queryDatadog(then, now, query)
    .then(res => res.series.map(reading => ({
      name: reading.scope
                   .replace(/^host:/i, '')
                   .replace(/(\..*$)/i, '')
                   .replace(/\W/g, ' '),
      value: reading.pointlist[reading.pointlist.length - 1][1]
    })));
}

Here I'm making use of bluebird, which is a great Promise library that comes with a lot of useful functionality, on top of being very performant. I definitely recommend using this as a replacement for native Promises when working with AWS Lambda functions, as it performs much better and has a significantly lower memory footprint.

There's not too much to the implementation here. It goes out to Datadog, grabs the latest CPU reading for each host, and then does a little processing on the host name to make it more speech-friendly.

Processing the Intent

When a request comes in for the QueryIntent we defined earlier in the schema, we'll need to process that. Here's an example of the type of data that will come in with our intent:

{
  "session": {
    "sessionId": "SessionId.908e5538-9a5e-4201-b20b-0ed7cc6761bb",
    "application": {
      "applicationId": "amzn1.echo-sdk-ams.app.a5cc355a-042d-4fdc-aabe-afe711657217"
    },
    "attributes": {},
    "user": {
      "userId": "amzn1.ask.account.AFP3ZWPOS2BGJR7OWJZ3DHPKMOMNWY4AY66FUR7ILBWANIHQN73QG6UY2L643DAVVTC3PB2PVHFZK5MHTXAE2T2FZOUVC7KVMZIYIB7YBARDE3AUU6WBMM7AYTZBFPK5NSXAIC5KJIVRZNGIRYPZCP2A4XPVFVI3JF3ZU5PKQ3PJDBTPKTNS7WI23SDK4ISXWOXDHMMLQ5FLLTI"
    },
    "new": true
  },
  "request": {
    "type": "IntentRequest",
    "requestId": "EdwRequestId.f01bc54b-6d75-4354-a478-08ec5b3cfed1",
    "timestamp": "2016-06-20T00:11:14Z",
    "intent": {
      "name": "QueryIntent",
      "slots": {
        "Query": {
          "name": "Query",
          "value": "CPU"
        }
      }
    },
    "locale": "en-US"
  },
  "version": "1.0"
}

Based on that, we can easily implement a function to pull the query value out of the intent and sent it over to Datadog:

function processIntent(intentRequest, session) {  
  const intent = intentRequest.intent;

  if (intent.name === 'QueryIntent') {
    const querySlot = intent.slots.Query;

    if (querySlot.value && querySlot.value.toLowerCase() === 'cpu') {
      return queryCPU().then(readings => {
        const hostSpeechFragments = readings.map(reading =>
          `${reading.name} is at ${reading.value}%`).join('. ');
        const speechOutput = `Here are the current CPU loads. ${hostSpeechFragments}`;

        return buildSpeechletResponse(
          'CPU Load', 
          speechOutput,
          null, 
          true);
      });
    }
  }

  return Promise.resolve(buildSpeechletResponse(
    'Datadog Query',
    'Sorry, I don\'t know that query',
    null,
    true
  ));
}

Most of that code is around validation and parsing. Once it gets a list of CPU readings it turns them into something readable and forms a spoken response based on them. The buildSpeechletResponse function referenced here is a simple helper method that formats things the way the Alexa API expects them. The code for that method can be found in the helpers file. If we get a query value other than CPU we simply respond saying that we don't understand that query.

The true at the end of the buildSpeechletResponse signature denotes that each response will end the session with the user. In a more interesting implementation you can imagine keeping the session open and making things more conversational, but for now we'll keep things as a single operation.

The Handler

Finally, we need to tie it all together and process the incoming request to our Lambda function:

module.exports.handler = function(event, context, callback) {  
  dogapi.initialize({
    api_key: process.env.DATADOG_API_KEY,
    app_key: process.env.DATADOG_APP_KEY
  });

  if (event.request.type === 'IntentRequest') {
    processIntent(event.request, event.session)
      .then(speechletResponse =>
        context.succeed(buildResponse({}, speechletResponse)));
  }
};

When a request comes in, we initialize dogapi with our API and app keys, and process the intent. You can specify your own keys by adding them as Serverless variables, such as through the _meta/variables/s-variables-dev.json file, in this format:

{
  "datadogApiKey": "your-api-key-here",
  "datadogAppKey": "your-app-key-here"
}

That's it! The full source for this sample is available on GitHub. It may look like a lot but really it's very simple to set up Alexa skills, especially when you use AWS Lambda to define them. With just a few lines of code and configuration you can add interactive speech-driven APIs to anything.

Alexa, is that cool or what?

June 20, 2016 1:34 GMT

Xamarin.Forms Behaviors: TranslateAction

Previously, I demonstrated using the EventHandlerBehavior and FadeAction classes to run a fade animation when an event occurs. The Behaviors Library for Xamarin.Forms has the notion of behaviors and actions. A behavior is attached to a control and listens for something to happen, such as an event firing. When the “something” happens, it triggers one or more actions, such as invoking a method or command. Actions are invoked by behaviors and executed on a selected control.

In this blog post, I’ll demonstrate using the EventHandlerBehavior and TranslateAction classes to run a translation animation when an event occurs.

Translating a VisualElement when an Event Fires

The EventHandlerBehavior class listens for a specified event to occur, and executes one or more actions in response. It requires you to set an EventName property to the event that you want the behavior to listen to, and an Actions property to one or more actions that should be executed in response to the event firing. Note that the Actions property of the EventHandlerBehavior instance is set indirectly by creating the TranslateAction instance as a child of the EventHandlerBehavior instance.

The TranslateAction class performs a translation animation, which moves a VisualElement, when invoked, and allows the following optional properties to be set:

  • TargetObject – an object that is the VisualElement on which to run the animation. If this value is omitted the object the behavior is attached to will be set as the target on which to run the animation.
  • X – a double that specifies the number of pixels to move the TargetObject horizontally. If this value is omitted the default value of 1 is used.
  • Y – a double that specifies the number of pixels to move the TargetObject vertically. If this value is omitted the default value of 1 is used.
  • Duration – an int that represents the length of the animation in milliseconds. If this value is omitted the default value of 250ms is used.
  • EasingFunction – an EasingFunction that specifies any velocity changes in the animation. If this value is omitted the default value of the linear easing function is used.
  • Await – a boolean that represents whether the animation should be awaited, or whether it should be allowed to complete in the background. If this value is omitted the default value of false is used.

The following code example demonstrates using the EventHandlerBehavior and TranslateAction classes to implement a compound animation that moves an Image control around the screen when a Button is clicked:

<Image x:Name="image" Source="monkey.png" Opacity="0" VerticalOptions="CenterAndExpand" />
<Button Text="Run Animation">
<Button.Behaviors>
<behaviors:EventHandlerBehavior EventName="Clicked">
<behaviors:TranslateAction TargetObject="{x:Reference image}"
X
="-100"
Y
="0"
Duration
="1000"
Await
="true" />
<behaviors:TranslateAction TargetObject="{x:Reference image}"
X
="-100"
Y
="-100"
Duration
="1000"
Await
="true" />
<behaviors:TranslateAction TargetObject="{x:Reference image}"
X
="100"
Y
="100"
Duration
="1000"
Await
="true" />
<behaviors:TranslateAction TargetObject="{x:Reference image}"
X
="0"
Y
="100"
Duration
="1000"
Await
="true" />
<behaviors:TranslateAction TargetObject="{x:Reference image}"
X
="0"
Y
="0"
Duration
="1000"
Await
="true" />
</behaviors:EventHandlerBehavior>
</Button.Behaviors>
</Button>

When the Button.Clicked event fires, a series of TranslateAction instances creates a compound animation, which is a sequential combination of animations. Specifically, an Image is translated around the screen over 5 seconds (5000 milliseconds). The translation of the Image uses five translation animations, with the Await property of each TranslateAction instance indicating that each animation executes sequentially. Therefore, subsequent animation methods execute after the previous method has completed,

The advantage of using the TranslateAction is that it’s possible to invoke animations through XAML, rather than having to use C#. In addition, when combined with behaviors, a translation animation can easily be invoked from XAML when a behavior occurs, such as an event firing, or a when a piece of data changes.

The sample application that this code comes from can be downloaded from GitHub.

Summary

The TranslateAction class allows translation animations to be invoked through XAML when a behavior occurs, such as an event firing, or when a piece of data changes.

June 20, 2016 6:05 GMT

Si no lo tengo me lo invento

Seguimos con más patrones. En este caso: ¿cómo respondemos ante las necesidades? Solemos tener dos opciones: compramos algo que la solucione o nos inventamos algo que haga lo mismo. No quiero entrar en el punto de vista del consumismo sino de la felicidad. Pero ¿se puede ser feliz resolviendo necesidades?

Los términos necesidad y problema a veces están tan cerca en nuestro día a día que actuámos (al menos a mí me pasa) con la solución más rápida: comprar. Se me rompe X, me compro otro. El acto de comprar comienza por la búsqueda, que disfrutamos como cuando éramos niños y caía en nuestras manos el catálogo de juguetes de El Corte Inglés. Seleccionamos n opciones y vamos bajando hasta llegar a dos o tres que, ante nuestra falta de decisión, dejamos decidir a lo que yo llamo los factores limitantes: disponibilidad, precio, qué opina mi colega, etc. Compramos uno, disfrutamos el efecto papel de regalo, los primeros días de novedad y, vuelta a la normalidad.

Como tengo la enorme suerte de rodearme de gente que inventa más que compra, a veces me pregunto: vaya, ¿y si me hubiese buscado una alternativa? Las alternativas, las invenciones, tienen una cosa mala: como te compares con otro, la has liado. Las únicas comparaciones buenas son contigo misma/o ayer. En cambio, todo lo demás es bueno:

  • Como has decidido buscar una alternativa, acabas de reforzar tu autoestima y tu poder de decisión. Me lo podría comprar, pero no lo voy a hacer. Has sido capaz de decir NO, enhorabuena
  • Si vas a buscar una alternativa, ¡tienes que ser creativa/o! Empezarás por definir muy claramente qué necesitas exactamente y cuándo lo necesitas. Con ésto claro, comenzarás con el proceso creativo
  • Sentirás miedo. Porque dependerá en la mayor parte de ti que salga adelante, porque no es lo normal, porque quizá no sepas por dónde empezar. Empieza por cualquier sitio en ése caso, da igual, confía. Confía mucho en ti. A mi me ayuda hacerme esta pregunta: ¿por qué yo no voy a poder si los demás sí?
  • Disfruta el proceso. A diferencia de la compra ahora disfrutas desde el boceto inicial en tu cabeza. Sin darte cuenta, es como si cayeses en que tienes fichas de LEGO a tu alrededor y toda la ilusión por hacer una figura de la cual no hay instrucciones. Pero sabes qué quieres que resuelva la figura
  • Aprenderás un montón. Quizá no te des cuenta pero estás aprendiendo haciendo. Mejor que leerlo, que verlo, es hacerlo. Así es además como mejor captamos la información los seres humanos
  • Lo valorarás más. Es una parte muy emocional de uno mismo, pero queremos más aquello que nos ha hecho esforzarnos. Y es curioso porque no funcionamos igual con el dinero: yo p.e. no valoro más aquello que más [dinero] me ha costado. Quizá los primeros días sí, pero acaba normalizándose. Y no lo fuerzo eh. En cambio, veo algo que hice después de años y ¡madre mía! hasta me puedo emocionar
  • Con lo que compras no te emocionas, con lo que fabricas sí. Y esto es un regalo para ti misma/o el día de mañana. Te estás preparando una cajita con un mensaje de amor para que la abras cuando quieras
  • Aunque menos importante, a veces me da vergüenza decir a alguien que me he comprado algo. En cambio, estoy deseando encontrarme a alguien para enseñarle lo que me he hecho

No quería llevar esto por el consumismo, si compramos más de lo que necesitamos o de si compramos por comprar. Las personas en las que estoy pensando ahora mismo no creo sinceramente que a voluntad se construyan sus propias cosas por huír del consumismo. De verdad creo que lo hacen porque saben, sin ser conscientes quizá, que una vía les hace más feliz que la otra. Y por desgracia muchas veces ayuda no tener dinero, no poder permitírtelo.

Tampoco vamos a pretender que todo todo ahora me lo haga yo, no se trata de eso, pero ¿y si probase con una sola cosa? ¿Te animas a ser más feliz?

img_0038
-Dedicado a dos Jose que me inspiran muchísimo, uno de L a V, otro de V a D


June 19, 2016 12:00 GMT

Access Git Information from MSBuild and Code

Why use git information

Regardless of how you generate your version numbers, it’s quite useful to embed the git repository information in an assembly (and/or its version information), such as the branch and commit that generated it. It can be invaluable in troubleshooting issues with a shipped product, and are opaque enough that they don’t typically represent a secret you would care to hide. Logging code inside your app/library could also trace this information, so that error logs or crash reports could include this information too, further facilitating troubleshooting.

In addition, if you’re using GitFlow, GitHubFlow or some other variation, your branches or tags may also have additional meaning with regards to versioning, and thus may also be relevant information you might want to consume as assembly metadata or directly from code.

Retrieving and using the information

There is of course an infinite number of ways to do this, from powershell that generate text files with the info, to MSBuild targets that generate JSON files, continuous integration servers automatically patching files for you or manually updating a version specifier somewhere in your source tree and having a pre-build process patch everything locally.

In many cases I’ve seen in the wild, these are intended to be consumed from build scripts that patch AssemblyInfo.cs files automatically and that’s about it. Maybe expose some environment variable that you can consume in some way too from those build scripts. Others would provide format strings and customization hooks to tweak how the version numbers or assembly info is generated, requiring some learning on the way. I’ve done so myself too at some point with SemanticGit. In the case of GitVersion, it goes to the extreme of being awfully complicated.

I came to the conclusion that for .NET/MSBuild based projects, simple MSBuild properties populated automatically (such as $(GitBranch), $(GitCommit), $(GitSha) and the like) coupled with source code exposure of the values via generated constants, strikes the perfect balance of simplicity and flexibility.

Thus, GitInfo was born.

When you install the package in your project that lives in a git repo, you automatically get the following MSBuild properties, ready to be consumed by any target that depends on the provided GitInfo target:

  • $(GitRoot): the root directory (without trailing slash) of the git repository. It’s smart enough to also work for submodules, properly returning the containing repository root, not the submodule’s.
  • $(GitBranch): the branch being built
  • $(GitCommit): the short (7 chars) commit sha being built
  • $(GitSha): the full commit sha being built

That may be all the information you need if you’re not leveraging the commits for versioning information. If so, in addition to consuming this from MSBuild properties you can also consume it from from code (C# and VB projects only for now). For this, GitInfo leverages a fairly common pattern in the .NET framework, which is to create a class named ThisAssembly that holds these values as constants.

For projects with a supported language, GitInfo will generate a partial class named ThisAssembly in the intermediate output directory, like the following:

namespace Contoso
{
	/// <summary>Provides access to the current assembly information.</summary>
	partial class ThisAssembly
	{
		/// <summary>Provides access to the git information for the current assembly.</summary>
		public partial class Git
		{
			/// <summary>Branch: master</summary>
			public const string Branch = "master";

			/// <summary>Commit: 5335c2f</summary>
			public const string Commit = "5335c2f";

			/// <summary>Sha: 5335c2f914b56ddd3dab4c0c71b44aa0e070f059</summary>
			public const string Sha = "5335c2f914b56ddd3dab4c0c71b44aa0e070f059";
			...
	}
}

Notice how the generated values are also exposed as the member summary, so that from anywhere in your codebase, you can easily find out what the current values are by just hovering on any code consuming ThisAssembly.Git.Branch for example.

Once thing you don’t want is this fancy addition ruining your carefully tunned incremental builds, so I’ve been extremely vigilant of that aspect too. The targets have been carefully crafted with proper Inputs/Outputs and smart caching of the git information (you can peek at the GitInfo.cache file in the intermediate output directory) and refreshing it only when the current git HEAD changes (i.e. you create a new commit, switch branches, pull commits, create a tag, etc.).

Additionally, this information is (by default) exposed as assembly metadata too via AssemblyMetadataAttributes which are new in .NET 4.5, as follows:

[assembly: System.Reflection.AssemblyMetadata("GitInfo.Branch", Contoso.ThisAssembly.Git.Branch)]
[assembly: System.Reflection.AssemblyMetadata("GitInfo.Commit", Contoso.ThisAssembly.Git.Commit)]
[assembly: System.Reflection.AssemblyMetadata("GitInfo.Sha", Contoso.ThisAssembly.Git.Sha)]

Leveraging git information for product versioning

It’s quite common to derive a product version number from a branch or tag name plus the number of commits since the branch/tag was created, SemVer style. The idea being that if the branch is named ‘v3.0.0’ and there have been 40 commits to it since it was branched, then the version number is ‘v3.0.40’. Pretty straightforward and very useful, since now you can locally build any branch and commit (or tag) and generate a fully equivalent product (including version!) from what a continuous integration server would generate. The same technique is usually applied to a version file in the repository root, which is updated after branching for a release (this is how most of us do it at Xamarin, for example).

Git can easily tell you how many commits you have made since you created a tag or branch or since you last commited to a particular file. This means that all the information to create an automatic version number based on the combination of a SemVer-named tag/branches (or a version file contents) plus commits on top of it them readily available. All we need to do is automate its extraction and expose that information to your code so you can build up whatever version numbers you wish.

Rather than providing MSBuild properties or scripts with format strings you have to learn in order to put together your version numbers, GitInfo simply exposes the determined version-related values via MSBuild and code constants (through ThisAssembly.Git.BaseVersion and ThisAssembly.Git.SemVer) so you can freely build the version number you want by just concatenating the values yourself.

GitInfo exposes two version structures:

  • BaseVersion: this is the base version determined from the branch, tag or version file contents. It’s expected to be a SemVer-like format, and it’s exposed as its individual components Major, Minor and Patch, following SemVer naming conventions.
  • SemVer: this is the determined version obtained by adding the number of commits on top of the branch/tag/file, plus any pre-release labels specified in the base version (i.e. -pre, -beta). It’s also exposed in its individual components Major, Minor and Patch but also adds Label (i.e. pre or beta), DashLabel (i.e. -pre or -beta) and Source (which can be Branch, Tag or File). The DashLabel allows for easily composing a semver string regardless of whether there was a pre-release label or not, since it defaults to an empty string if no label was found.

In MSBuild, any target that depends on the provided GitVersion target can access the following properties for the above values:

  • $(GitBaseVersion)
  • $(GitBaseVersionSource)
  • $(GitBaseVersionMajor)
  • $(GitBaseVersionMinor)
  • $(GitBaseVersionPatch)
  • $(GitCommits)
  • $(GitTag)
  • $(GitBaseTag)
  • $(GitSemVerMajor)
  • $(GitSemVerMinor)
  • $(GitSemVerPatch)
  • $(GitSemVerLabel)
  • $(GitSemVerDashLabel)
  • $(GitSemVerSource)

The difference between GitTag and GitBaseTag is apparent in these two sample values from an actual repo:

  • GitTag: v0.2.63-145-g5335c2f
  • GitBaseTag: v0.2.63

Code like the following is emitted for the ThisAssembly partial class:

  partial class ThisAssembly
  {
    /// <summary>Provides access to the git information for the current assembly.</summary>
    public partial class Git
    {
      /// <summary>Branch: master</summary>
      public const string Branch = "master";

      /// <summary>Commit: 5335c2f</summary>
      public const string Commit = "5335c2f";

      /// <summary>Sha: 5335c2f914b56ddd3dab4c0c71b44aa0e070f059</summary>
      public const string Sha = "5335c2f914b56ddd3dab4c0c71b44aa0e070f059";

      /// <summary>Commits on top of base version: 145</summary>
      public const string Commits = "145";

      /// <summary>Tag: v0.2.63-145-g5335c2f</summary>
      public const string Tag = "v0.2.63-145-g5335c2f";

      /// <summary>Base tag: v0.2.63</summary>
      public const string BaseTag = "v0.2.63";

      /// <summary>Provides access to the base version information used to determine the <see cref="SemVer" />.</summary>      
      public partial class BaseVersion
      {
        /// <summary>Major: 0</summary>
        public const string Major = "0";

        /// <summary>Minor: 2</summary>
        public const string Minor = "2";

        /// <summary>Patch: 63</summary>
        public const string Patch = "63";
      }

      /// <summary>Provides access to SemVer information for the current assembly.</summary>
      public partial class SemVer
      {
        /// <summary>Major: 0</summary>
        public const string Major = "0";

        /// <summary>Minor: 2</summary>
        public const string Minor = "2";

        /// <summary>Patch: 208</summary>
        public const string Patch = "208";

        /// <summary>Label: </summary>
        public const string Label = "";

        /// <summary>Label with dash prefix: </summary>
        public const string DashLabel = "";

        /// <summary>Source: Tag</summary>
        public const string Source = "Tag";
      }
	}
  }

The generated ThisAssembly file is in the intermediate output directory in a file named ThisAssembly.GitInfo.g.cs (or .vb).

Note that GitInfo hasn’t generated a single [AssemblyVersion] attribute :). That is intentional! With the above information, you can trivially create one yourself, share it however you like (linked files, shared asset project, common targets imported from all your projects, etc.) among your projects. For example, in Xamarin for Visual Studio, we have a GlobalAssemblyInfo.cs like the following:

// AssemblyVersion = full version info, since it's used to determine agents versions
[assembly: AssemblyVersion(Xamarin.ThisAssembly.Version)]
// FileVersion = release-like simple version (i.e. 3.11.2 for cycle 5, SR2).
[assembly: AssemblyFileVersion(Xamarin.ThisAssembly.SimpleVersion)]
// InformationalVersion = full version + branch + commit sha.
[assembly: AssemblyInformationalVersion(Xamarin.ThisAssembly.InformationalVersion)]

namespace Xamarin
{
	partial class ThisAssembly
	{
		/// <summary>
		/// Simple release-like version number, like 4.0.1 for a cycle 5, SR1 build.
		/// </summary>
		public const string SimpleVersion = Git.BaseVersion.Major + "." + Git.BaseVersion.Minor + "." + Git.BaseVersion.Patch;

		/// <summary>
		/// Full version, including commits since base version file, like 4.0.1.598
		/// </summary>
		public const string Version = SimpleVersion + "." + Git.Commits;
		
		/// <summary>
		/// Full version, plus branch and commit short sha, like 4.0.1.598-cycle6+39cf84e
		/// </summary>
		public const string InformationalVersion = Version + "-" + Git.Branch + "+" + Git.Commit;
    }
}

You can of course just use the values directly in the version attributes, rather than having separate constants, for simplicity:

[assembly: AssemblyVersion (ThisAssembly.Git.SemVer.Major + "." + ThisAssembly.Git.SemVer.Minor + "." + ThisAssembly.Git.SemVer.Patch)]
[assembly: AssemblyInformationalVersion (
	ThisAssembly.Git.SemVer.Major + "." +
	ThisAssembly.Git.SemVer.Minor + "." +
	ThisAssembly.Git.SemVer.Patch + "-" +
	ThisAssembly.Git.Branch + "+" +
	ThisAssembly.Git.Commit)]
// i..e ^: 1.0.2-master+c218617

Extending the generated ThisAssembly class with the formatted version strings is quite useful however, since you can avoid repeating that formatting across your codebase if you happen to consume it elsewhere, such as in logging.

Installation

Being a NuGet package, it’s trivial:

Install-Package GitInfo

If a base version can’t be determined, a warning will be issued and the version values will default to 0.1.0.

Customizations

Right after installation, a readme will open up showing the available customization points via MSBuild, copied here as of this writing:

  $(GitThisAssembly): set to 'false' to prevent assembly 
                      metadata and constants generation.

  $(GitThisAssemblyMetadata): set to 'false' to prevent assembly 
                              metadata generation only. Defaults 
                              to 'false'.
	
  $(ThisAssemblyNamespace): allows overriding the namespace
                            for the ThisAssembly class.
                            Defaults to the global namespace.
											
  $(GitDefaultBranch): determines the base branch used to 
                       calculate commits on top of current branch.
                       Defaults to 'master'.
	
  $(GitVersionFile): determines the name of a file in the Git 
                     repository root used to provide the base 
                     version info.
                     Defaults to 'GitInfo.txt'.
										 
  $(GitInfoReportImportance): allows rendering all the retrieved
                              git information with the specified
                              message importance ('high', 
                              'normal' or 'low').
                              Defaults to 'low'.

  $(GitIgnoreBranchVersion) and $(GitIgnoreTagVersion): determines 
                            whether the branch and tags (if any) 
                            will be used to find a base version.
                            Defaults to empty value (no ignoring).

I find $(GitInfoReportImportance) particularly useful in release builds:

<PropertyGroup>
    <GitInfoReportImportance Condition="'$(Configuration)' == 'Release'">high</GitInfoReportImportance>
</PropertyGroup>

Which causes the following msbuild log entry:

GitInfoReport:
  Git Info:
    GitRoot:              C:/Contoso
    GitBranch:            master
    GitCommit:            39cf84e
    GitSha:               39cf84eb9027ca669c8aa6cb4fe5f238009d42ba
    GitBaseVersion:       99.0.0
    GitBaseVersionSource: C:\Contoso\Contoso.Version
    GitBaseVersionMajor:  99
    GitBaseVersionMinor:  0
    GitBaseVersionPatch:  0
    GitCommits:           2611
    GitTag:
    GitBaseTag:
    GitSemVerMajor:       99
    GitSemVerMinor:       0
    GitSemVerPatch:       2611
    GitSemVerLabel:
    GitSemVerDashLabel:
    GitSemVerSource:      File

This is nice especially if you just do it on the main build script for a project, which can of course also benefit from GitInfo even without being a regular project containing code: it just needs to import the targets and make its targets depend on GitInfoReport!

But to me the best part is that all of the behavior is implemented in a single .targets file, with plain native MSBuild with no custom tasks, even adding the commits to the base patch so it makes for an interesting read if you’re looking to learn some MSBuild tricks too :).

Happy MSBuilding!

June 17, 2016 7:25 GMT

Contest: Add the Latest in Xamarin.Forms

At Xamarin Evolve 2016 we announced that Xamarin.Forms is now open source and introduced a brand new Xamarin.Forms Previewer that renders a live preview of a page side-by-side with the corresponding XAML markup, directly within your Xamarin Studio environment. Xamarin.Forms has also had tons of new features added in the last several months to help you build great mobile apps even faster, including the introduction of DataPages, native control embedding, URL navigation, and a CarouselView control.

In this contest, we invite you to try out the latest-and-greatest in Xamarin.Forms by adding a Xamarin.Forms 2.* feature to your application to receive a Xamarin code monkey!

How to Enter

  1. Add one of the Xamarin.Forms 2.* features below to your app:
  2. Take a screenshot of the new feature(s) implemented in code alongside your app running on a simulator/emulator, and tweet it with the hashtag #XamarinForms and the Xamarin.Forms 2.* feature added.
  3. Sample tweet:


Rules

All submissions must be made by Monday, June 27 at 12:00 pm EDT. A valid entry consists of a tweet containing the hashtag #XamarinForms and mentioning @XamarinHQ, along with a screenshot of a Xamarin.Forms 2.* feature being implemented (picture must contain associated code and feature running in app). Each valid entry will receive a plush Xamarin code monkey, one entry per person. To be eligible, you must follow @XamarinHQ on Twitter to enable us to DM you for private-follow up. There is no purchase necessary to enter the “Add the Latest in Xamarin.Forms” contest.

The post Contest: Add the Latest in Xamarin.Forms appeared first on Xamarin Blog.

June 16, 2016 7:23 GMT

Mobile DevOps at Coca-Cola Bottling Co. Consolidated

Mobile-optimized DevOps has never been easier, and it’s setting Xamarin customers apart. With demanding users and high stakes delivery timelines, Coca-Cola Bottling Co. Consolidated’s (CCBCC) DevOps processes help its developers create apps that users love for their ease of use and business stakeholders love for their impact on sales.

Here, Tarandeep Kaur, Sr. ISS Application Architect, shares her experiences and advice in a peek behind the scenes at CCBCC’s DevOps process

Meet Coca-Cola Bottling Co. Consolidated: End-to-End with 100% C# and .NET

Picture2
Based in North Carolina, CCBCC is the largest independent Coca-Cola bottling distributor in the US, with $1.5B+ in annual revenue and a large field salesforce and customer network. To better serve their sales teams and customers, CCBCC used Xamarin, Visual Studio, Visual Studio Team Services, and Azure to get their Marketplace iPad app into users’ hands in just four months by managing the entire DevOps cycle in C#.

Tell us a little bit about your company and role—have you always been a developer?

As the largest independent Coca-Cola bottler in the US, we make, package, and deliver soft drinks to stores, restaurants, entertainment venues, offices, and college campuses, focusing primarily on the Southeast and Mid-Atlantic regions.

Personally, I’ve been a hands-on developer for eight years, and I’ve been working on mobile projects for about two years. I’m an Application Architect, responsible for technical design, code development processes, and the overall software development lifecycle for our products. I work closely with our development and QA teams, as well as business partners and external vendors.

Tell us about your app. How does it fit into your company’s mobile strategy?

Our Marketplace app is an iOS iPad tool that our field team uses when visiting customers. We designed the app to support our constantly evolving sales and marketing space, as well as facilitate better customer engagement.

Giving our field staff mobile access is especially critical, as they’re often in areas with limited connectivity, and Marketplace makes them efficient from anywhere. Our employees are free to access the systems they need to work without being chained to desktops or hard-wired internet, making them happier and more productive.

Why did you choose Xamarin and Visual Studio to build your apps?

We chose Xamarin because it allowed us to use our in-house C# skills and .NET talent for cross-platform mobile development. Since we knew C#, we were able to minimize the mobile learning curve and expedite development and delivery.

We were able to ship our app—from design to deploy—in just four months. Without Xamarin and Visual Studio, this would have taken much longer due to a huge learning curve for our in-house team.

How did you get up to speed with cross-platform mobile development?

We relied heavily on online resources and augmented our team with a couple of Xamarin developers, who acted as mentors for the rest of the team.

What is the most compelling or exciting aspect of your app (design feature, functionality, etc)? Why?

The intuitive, easy-to-use design has been very valuable for our field reps, with the majority of users able to use the app with little or no training.

What do you think about when you hear “native app”? How did Xamarin and Visual Studio help you accomplish your definition of “native”?

“Native App” usually indicates better performance and a consistent look and feel. Xamarin (specifically Xamarin.Forms) met this definition, allowing us to code in C#, while still maintaining that native look and feel, as well as optimize performance at all times.

For example, using the iOS API was remarkably simple, and we easily incorporated native APIs, like Maps.

Did you integrate with any other services or systems? How did that affect your productivity?

We integrated with Visual Studio Team Service, Raygun, and Slack. We implemented a code review process early on, and the Slack integration helped us stay up to date, even while working across varied geographical locations. We also used Visual Studio Team Service to manage our Agile workflow.

What have your users said about your app? Your manager?

It’s been very well received. Our field users have described the app as “slick,” “intuitive,” “fast,” and “polished.”

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

Not being tied to a particular platform is a priceless skill and ability for me, our team, and developers everywhere. Xamarin brings mobile development within reach for the large C# and .NET developer base, without the added time and cost of learning traditional native development platform-specific languages.
 
Read more about mobile-optimized development here.

The post Mobile DevOps at Coca-Cola Bottling Co. Consolidated appeared first on Xamarin Blog.

June 15, 2016 1:46 GMT

The App Instrumentation Tour Rolls On

In case you haven't noticed, I've been rambling a lot lately on the topic of app monitoring and instrumentation, including a visit to Jesse Liberty's podcast as well as my session at Xamarin Evolve.

For whatever reason I've been allowed to keep rambling about it since then, so I have some more links to share!

dotnetConf

I was invited to speak at dotnetConf, which was an awesome virtual conference involving many great folks from Microsoft in addition to many others from around the community. There was a ton of great content, so I definitely encourage you to go check it out. I did a session named Monitoring Your Mobile Apps in the Wild, which was based on the previously mentioned session I did at Evolve.

.NET Rocks!

It's always a blast to talk to Carl and Richard, so it was an honor to be invited back to chat about this stuff. The episode, titled Instrumenting Mobile Apps with Greg Shackles

Gone Mobile

Okay, so this one is my own podcast and I'm cheating a little. Yesterday we published an episode with John-Daniel Trask of Raygun, talking about their new Real User Monitoring solution for the web and mobile apps called Pulse. The subject matter is right in line with all of this so I figured I'd give it an extra shout out.

Gone Mobile 34: Raygun Pulse with John-Daniel Trask

June 14, 2016 7:00 GMT

Gone Mobile 34: Raygun Pulse with John-Daniel Trask

In this episode we’re joined by John-Daniel Trask, founder and CEO of Raygun, to talk about Pulse - their Real User Monitoring solution for web and mobile apps.

Hosts: Greg Shackles, Jon Dick

Guest: John-Daniel Trask

Links:

Thanks to our Sponsors!

http://raygun.com

Raygun Pulse is now available for mobile - Real user monitoring for your mobile apps! Get deep detail into how your mobile applications are performing for your users.

June 13, 2016 5:02 GMT

Continuous integration/continuous delivery for your Xamarin app with VSTS and HockeyApp &amp;#8211; Part 2

In my previous post I have talked about how to create a build definition with VSTS and setup your Mac build agent yourself.

In this post I will extend that build definition so we can publish our app automatically to HockeyApp. Also I will explain how you can do the same for your Android app, a bit about versioning your app (with many thanks to Richard Woollcott) and talk about other options like Bitrise and AppVeyor.

First, lets deliver our app to HockeyApp so we can distribute it to our fans.

Continuous delivery with HockeyApp

First let me start with some bad news.

If you've worked with Insights, you're gonna have a bad time
If you’ve worked with Insights, you’re gonna have a bad time

Right now HockeyApp is targeting only hard crashes, which mean; unhandled exceptions.
So no fancy graphs, no reporting your handled exceptions, minor user tracking, etc. Also the SDK isn’t ready for forms and it’s structure isn’t great right now.

I’ve been told that the SDK will be updated in a few weeks from now so that’s something, but HockeyApp will not reach feature parity with Insights on the short term.

The other thing has to do with distributing your app with HockeyApp. For iOS you will need to collect your targeted users UUID/UDID.
It isn’t a deal breaker, HockeyApp even helps you with collecting it from your users, but it is kind of a bump because you still have to go back to Apple, import the UUIDs, generate a mobileprovision file and get that back to HockeyApp.

So far for the cons. Now there are a lot of pros as well! So let’s just have a look at how we can send our app over to HockeyApp right from VSTS.

Extending the build definition

There are actually two ways of doing this, add a final step to your build definition or go to the release bit of your VSTS environment.

Both will effectively do the same, but with the release path you will have more control over when a version is released. You can also let someone sign off on the release first, etc. I will describe how to release with the release options in VSTS.

First let’s go back to our build definition. As you can see I have extended it a little since my previous post.

Build definition
Build definition

Most interesting here is the first one: Version assemblies.

You want to keep a good record of which versions are being sent out to your testers or even the app store. This is crucial to know when a bug has occurred, one of the first questions will be ‘what version are you running?’. Also, if you have some experience in developing software you’ve probably forgotten to increase the version number as well. So if we’re automating things, why not this as well?

Because Xamarin apps are still iOS, Android and UWP apps when it comes to it, you’ll have to do some different action here depending on which platform you are building. In this case, iOS, needs to update the version number in the info.plist file. This can be done by a simple regex. After fiddling somewhat myself I came across this post: Versioning by Richard Woollcott which perfectly describes it for all platforms. Many thanks!

Also I’ve added a step to delete previous .ipa files. I’m not sure if I screwed something up with configuring but all my builds now go into timestamped subfolders, which effectively leave me with a lot of ipa files. To make sure I get the right one uploaded to HockeyApp I just clear out my artifacts folder of all ipa’s before building a new one.

The Test Cloud step is disabled, I transferred it to a separate build definition.

The last step is one of the most interesting here to make the whole thing work. With this you pack up your ipa (or apk if your doing Android) and publish it as an artifact. You can also take your dSYM file and include that as well, that will give your stacktraces a lot more useful information in HockeyApp.
Of course, doing Android and UWP you’ll need the equivalents of these files.

You can grab any file you want by specifying the right wildcards to access them.

Publish build artifacts
Publish build artifacts

With the Artifact type field you can determine where the artifacts are put. If you use Server it will transport them back to the main build server (probably the TFS web portal you’re looking at right now), or you can choose fileshare and specify a share path where to put them. Of course then you need to have enough rights on the filesystem to do so.

After you save this everything is now ready to be deployed! So save it and head over to the Release tab up top.

Release definition

Creating a release is very similar to the build definition. Here you can also define steps that have to be executed in order to create a release.

Creating a release definition
Creating a release definition

Click on the big plus in the left column to create a new one. Mine will be Boodschappie iOS. Again, Boodschappie is a project I’m working on to be released soon.

When you did click it you can again select from some templates, which are only two at the moment of writing and both have to do with Azure. Since we’re not going to deploy our app to Azure, choose the empty template at the bottom and click Next.
Now we need to specify which build definition this release corresponds to, so a release cannot exist without a build definition.

Creating a release definition
Creating a release definition

Also, like creating a build definition you can here check the Continuous Integration box, which will cause to create a release every time you checkin code.
Whether or not that is something you want is up to you. There are some methods to determine if a release has to be made (by specifying a specific branch) or who will get the created release. We will get to that in a little bit.

After you have configured everything here simply click Create and your release definition will be ready in a second.

Release environments

If you didn’t notice before; constructing the release definition looks very much alike building your build definition. The same goes for adding steps to the definition, which are actually called tasks for release. There is however one bigger difference. On the left where you are to add your release steps you see an extra column. This is for your environments.

Defining the release definition
Defining the release definition

Just like steps you can add environments by clicking the plus button. With this (seemingly simple) functionality you get a lot of control over your release process.

An environment is the platform where you want to release your app to. This can be anything from a zip with your WPF assemblies, your web application deployment package or your ipa file for your iOS app. Because of the variety of different projects you can use this with an environment can be anything as well; Azure, HockeyApp or a file share to name some. Not only can you determine the actual platform to release to, but you can also put in place a mechanism where you assign approvers which can decide whether or not the result of your build is good enough to release to the next environment.

So with this you have a powerful tool to make sure your build goes to your testers first, before they send it over to a UAT environment. Or, release it to a Azure staging slot, run some (automated) tests to see if the application can be reached and acts how it should and only then release it to production. Sweet!

Releasing to HockeyApp

However.. We’re not going to do all of this advanced stuff for now, we’re just going to keep to one environment which gets approved automatically. This is actually the default setting for an environment so just keep it like that for now and click on the Add tasks button.

While you are automatically are directed to the Deploy tab, notice that all other steps tasks are also available to you. You can run some additional tasks if you would like to. Although HockeyApp is part of Microsoft nowadays, the HockeyApp task isn’t in the default task list yet. But not to worry! Microsoft has created a marketplace for everything that has to do with building and releasing. So click the little ‘Don’t see what you need?’ link and find the HockeyApp extension.
It should be pretty self-explanatory.

Adding release tasks
Adding release tasks

After that find it in the list and click Add.

Now this step requires some more configuring than the ones before. Let’s have a look.

Configuring HockeyApp release task
Configuring HockeyApp release task

It starts of hard, you need to specify a HockeyApp connection. Whoa! We don’t have that!
Now I am going to assume that you have created a HockeyApp account by now. You should also have created a app. Although it is easiest by supplying a ipa or apk file you can also do it manually. Now note the API key in your account settings and the App ID in your app dashboard.

Now to create a connection have a look at this HockeyApp documentation page. After you have done this successfully it should be listed in the dropdown under HockeyApp connection. Fill in the App ID in the next box and the hardest part is over already!

The last thing we need to do here is enter a path to your ipa file (or apk if you’re using this for your Andoid app). Because our release definition is bound to a build definition, remember that the file path here follows the structure of the artifact we have dropped from there. In fact that probably makes our life a lot easier because the artifact probably contains only one ipa file we can get away with **\*.ipa which sends any ipa files over to HockeyApp.

Also, for the sake of readable error reports supply your dSYM file in case of an iOS release. Remember; this needs to be in your artifact as well if you want to send it over to HockeyApp!

The rest of the fields are worth a look as well. You can also insert release notes right from your project with a file, notify our (HockeyApp) users and also let the system determine which users get this release by configuring tags and/or teams and/or users. Note; these are HockeyApp entities! Have a play with it!

When you’re all done click Save, name your release appropriately and give it a go. To do this you need to have a successful build from the associated build definition. Now click Release and Create Release.

Creating our first release
Creating our first release

Now you just need to select the articaft you want to use from that build and click Create. Now you will be taken back to the fancy logging screen which makes you look like a hacker. Closely examine the output to see if all goes well. Like creating a build it will probably take a few tries before you get it right.

But if all did go well you should get an e-mail from your HockeyApp account which informs you that there is a new version available! Woohoo!

Now what is with this Bitrise?

VSTS is awesome, it is complete and if you’re working with all Microsoft products why not stick with them?

The only showstopper here is that you will need to provide your own Mac or pay for a MacInTheCloud, and I promised you free stuff! This is where Bitrise comes in.

Bitrise.io is awesome! It does everything VSTS does (in terms of building and releasing) and more! I’m not going through describing the whole process here because I’m surprised that you haven’t been bored reading all this stuff by now as it is If there is enough request I’ll do it in a separate post.

But the account you can create there is completely free and they also provide the Mac needed to build your iOS app! Awesomesauce!
Just like VSTS you can completely assemble your own build and release process. And they also have a ‘marketplace’ kind of repository with build steps. Which is actually more complete than the VSTS one right now.

Missing a step? You can easily create them yourself as well!

There are of course some restrictions to the free account, but as a single developer you should be OK for a while so go check it out. Another alternative is AppVeyor. They offer free accounts for all open-source projects. But here iOS apps aren’t supported as a whole unfortunately.

Concluding

As you can read there is a lot going on in CI/DI world and Microsoft now has a complete suite available to help you inspect the build quality of your apps and release it into the wild! I didn’t even cover testing yet but if you get to play with this be sure to check out Test Cloud which is a powerful tool as well.

If you are one of the lucky guys to understand Dutch, then have look at this webcast I did recenlty about the same subject!

Any questions can be redirect to my mailbox or @jfversluis on Twitter.

Thanks for reading!

June 12, 2016 4:22 GMT

La mala-vergüenza

Con los años he descubierto un patrón curioso que es súper potente unido al “ir al mínimo” de la semana pasada: algunas personas que triunfan, que les va bien, habían perdido antes la vergüenza. No la vergüenza buena de la educación, sino la mala, la “freno de mano”.

Desde chicos aprendemos que el sacrificio, en el tiempo, trae recompensa. Si estudias mucho tendrás buenas notas, si tienes buenas notas podrás elegir mejor qué hacer con 18 años (y las ideas claras, por supuesto), si decides ir a la Universidad y estudias mucho tendrás un buen trabajo, etc. Todo está ligado al sacrificio previo. Que no está mal ojo, pero falta algo. Conozco a personas, empezando por mí, que se sacrifican en exceso pero aún así les falta algo.

Nadie te habla de la vergüenza. Cuando tenía 18 años y entré en la Universidad conocí a personas que compartían mis mismos gustos. En concreto, acabé pasando mucho tiempo con un grupo que -ahora sé- habían perdido la vergüenza. Nos aventuramos a “dar charlas”, en plan informal, sobre cosas que aprendíamos en nuestro tiempo libre. Ni teníamos conocimiento suficiente, ni capacidades educativas, tampoco sabíamos hablar en público, ni otras muchas cosas. Pero no teníamos vergüenza. La pasión que traíamos cada uno rompía ése elástico una y otra vez. Éramos osados.

Lo más curioso era que yo sí era vergonzoso. Para mí no sabía nunca lo suficiente como para ponerme delante de 15-20 personas y contarles qué aprendí la tarde anterior. Lo fantástico fue que me rodeé de personas que me empujaron a atreverme. Cogieron la base del Principio de Pareto (probablemente ni lo conocíamos por aquel entonces) y me transmitieron que con un 20% de esfuerzo en el aprendizaje (¿recuerdas el valor de ir al mínimo?) el otro 80% puede ser usado para sacarle partido, y más si lo dedicas a los demás.

¿Sabías que probablemente sepas el inglés mínimo como para mantener una vídeo-llamada para tu próximo trabajo? 20-80, mira Michael Robinson. ¿Te has dado cuenta ya de que eres capaz de tomar tus propias decisiones sobre temas vitales? 20-80, no te hace falta evaluar hiperminuciosamente cada posibilidad, la vas a cagar igual, a veces pasa, nos pasa a todos. La siguiente saldrá mejor. ¿Por qué no le envías un WhatsApp a esa persona que te gusta, y le dices que te gustaría verla? Quizá aún no sea el momento, estás en ello, mañana verás, etc. 20-80.

04-05-2015-Por-qué-es-importante-usar-el-freno-de-mano

Si algo en tu vida te bloquea para ser más feliz, o quieres ayudar a alguien que aprecias mucho, agarra la palanca del freno, pulsa el botón y bájala. Tienes demasiada mala-vergüenza. Y si te rodeas de personas que ya la bajaron te estás haciendo un gran favor a ti misma/o. Quizá ni tú sepas que estás bloqueada/o.

Si uno los puntos hacia detrás, hoy por ejemplo tengo el trabajo que tengo gracias a aquellas “charlas” que dimos.

PD: Por cierto, por curiosidad, ¿a qué le tienes vergüenza tú, o cómo se la perdiste? Seguro que aprendo algo. ¡Gracias de antemano!


June 12, 2016 1:00 GMT

NuGet Support in Xamarin Studio 6.0

Xamarin Studio 6.0 was released last week and it includes a lot of new features, such as a new dark theme and Roslyn integration. This release also includes some improvements made to the NuGet support.

Add Packages Dialog - Dark Theme

New Features

  • Support NuGet packages targeting tvOS.
  • Support updating pre-release NuGet packages.
  • Show updates available for pre-release NuGet packages.
  • Remember Show pre-release Packages setting in Add Packages dialog.
  • Error dialog displayed if NuGet.Config file cannot be read.

More information on all the changes in Xamarin Studio 6.0 can be found in the release notes.

Support NuGet packages targeting watchOS

A new Xamarin.WatchOS target framework is now supported which allows NuGet packages to contain assemblies for watchOS.

Support updating pre-release NuGet packages

Previously it was not possible to update a pre-release NuGet package to a later pre-release from the Solution window, only updates to stable NuGet packages were supported. The only way to update to a later pre-release NuGet package was to use the Add Packages dialog.

Now an individual pre-release NuGet package can be updated by right clicking and selecting Update. When all packages in a project or solution are updated then pre-release NuGet packages will be updated to a later pre-release version if they are available.

Show updates available for pre-release NuGet packages

Previously Xamarin Studio would only show stable NuGet package updates as being available if a pre-release NuGet package was installed. Now Xamarin Studio will check for updates for pre-release NuGet packages as well as stable packages and display this information in the Solution window.

Pre-release NuGet package updates in Solution window

Only if an installed NuGet package is a pre-release version will pre-release updates be shown as available in the Solution window. Xamarin Studio will not check for pre-release updates for stable NuGet package versions that are installed.

Remember Show pre-release Packages setting in Add Packages dialog

The Show pre-release Packages check box setting will now be remembered in the Add Packages dialog on a per solution basis.

Error dialog displayed if the NuGet.Config file cannot be read

Previously if the NuGet.Config file could not be read the error would be silently logged, but not reported, and Xamarin Studio would then switch to using the default official NuGet package source. Now an error dialog is shown indicating that there was a problem reading the NuGet.Config file.

Bug Fixes

Support NuGet packages that use icons from local files

A NuGet package can now use an icon, which will be shown in the Add Packages dialog, taken from the local file system using a file url. Previously this would fail with an invalid cast exception.

Incorrect update count displayed after updating NuGet packages.

When an update caused a NuGet package to be uninstalled the Packages folder in the Solution window would show an incorrect count for the available updates.

NuGet restore and update not working for workspaces

With a workspace opened, or multiple solutions opened in Xamarin Studio, then restoring and updating NuGet packages would only work for one of the solutions.

Unable to add Google Play Services packages

The Xamarin.Android.Support.v7.AppCompat NuGet package depends on a single version of the Xamarin.Android.Support.v4 NuGet package. When a Xamarin Google Play Services NuGet package is installed that depends on a higher version of the Xamarin.Android.Support.v4 NuGet package the install would fail to find a version of the AppCompat NuGet package that is compatible. An error similar to the following would be displayed in the Package Console window:

Could not add Xamarin.GooglePlayServices.Ads.
Updating 'Xamarin.Android.Support.v4 23.1.1.0' to
'Xamarin.Android.Support.v4 23.1.1.1' failed. Unable to find a version
of 'Xamarin.Android.Support.v7.AppCompat' that is compatible with
'Xamarin.Android.Support.v4 23.1.1.1'.

The problem was that the AppCompat NuGet package is not involved in the initial NuGet package resolution using the remote package source so it is initially not considered for installation into the packages directory. When a package reference is then added to the packages.config file a search for a compatible AppCompat package was only using the local solution’s packages directory which fails causing the install to fail.

To fix this the local solution packages directory is used first when looking for a compatible AppCompat NuGet package and will fallback to using the configured remote package sources if no suitable package is found in this directory. To handle a package being added to the packages.config at this point, after the original NuGet packages have already been downloaded to the solution’s packages directory, Xamarin Studio will detect a package is added to the packages.config file and install the NuGet package if it is not already in the local solution packages directory.

Incorrect package version being installed

When installing a NuGet package using the Google Play Services dialog a package version is not specified by the dialog. If the NuGet package being installed was found in the local machine’s NuGet cache it would be used instead of the latest version from the official NuGet gallery at nuget.org. This could result in a lower version being installed than expected.

MSBuild property files (.props) not being added at correct project location

Installing a NuGet package that included an MSBuild .props file would add an Import element for the .props at the end of the project file (.csproj) instead of at the start. The .props files are now added to the project file as the first child element inside the project’s root element.

June 10, 2016 7:47 GMT

WWDC Remote Viewing Protips

I attended the 2015 WWDC and made these notes afterwards. Aside from the specifics re. the Apple Watch and AppleTV, they may be of value to those who are considering streaming sessions next week:

WWDC: Post-show Streaming is the Key to Value

From an editorial perspective, one thing that is clear about WWDC is that the main audience for the sessions is not the developers in attendance, but the much more diverse, more diffuse, and more transient on-line audience that will view the videos over the next months and even years.

WWDC Session Videos are great as overviews, poor as references

What I’ve come to realize is that WWDC sessions are great as overviews, but poor for depth. They are very much worth watching when you’re new to a framework, they’re somewhat worth watching if you haven’t programmed in the framework lately (you might see some class you hadn’t appreciated), but they are not the place to discover a way out of some corner-case or programming limitation.

Microsoft explicitly labels the depth of their conference talks as being 100-, 200-, or 300-level, and 300-level content at WWDC was vanishingly rare. (As I write this, I can only speak to the talks I physically attended, but several talks definitely promised more depth than they delivered.)

I wonder if this is an artifact of The Dog That Didn’t Bark aka Apple TV. It must have been pulled very late. Both Xcode and Apple’s Developer Site, which had to be updated to support the new OS betas, are littered with Apple TV references. Perhaps it was the case that some of these talks were put together quickly. (Although you wouldn’t guess it from the universally well-practiced speakers.)

The real keynote was the Platform State of the Union

Monday’s keynote was covered by news vans and live blogs and all that crap. There was, perhaps, 5 minutes of developer content in this 2.5-hour stemwinder. From the audience, anyway, the music stuff was awkward to the point of embarrassment.

Skip it and watch [Platform State of the Union] instead. This was the true developer’s keynote and contains an excellent overview of El Capitan, iOS 9, and watchOS. (By the way, the witty kids pronounce “watchOS” so that it rhymes with “nachos.”)

The Shocking Secret You Can Use to Determine Which Videos to Stream

Is that a proper 21st century headline?

Anyway, here’s the key: many sessions followed a standard naming practice:

— “Introduction to…” talks are 100-level (if that) “tables of content.” They hardly have any code on screen, but contain references to other videos that provide the 200- or 300-level content. If you’ve ever programmed in the namespace before, you can skip these talks.

— “What’s New In…” talks are 100-level “Release Notes.” There may be some code, but what you’re really looking for here are the new classes and general new capabilities. This is the video with which you should start if you have programmed in the framework before, even if you’re pretty comfortable. Again, all of these talks are good at referencing other, more substantive, talks. This is my main recommended tactic for finding deep content on frameworks with which you are familiar: it’s much more effective than guessing from session titles and descriptions.

— Beware talks that have the words “tips”, “tricks,” or “practices.” These were the talks that disappointed me. Such words traditionally mean 300-level content. If you’re an attendee and you’re budgeting precious in-conference time to “tricks” and “practices,” that’s a strong indicator that you’re familiar with the framework and are encountering its limitations and corner cases. But at WWDC, these sessions appear to be more focused on the newcomer or relatively inexperienced framework user.

June 10, 2016 10:23 GMT

Xamarin.Forms Behaviors: FadeAction

Previously, I mentioned that I’d added a number of new actions to the Behaviors Library for Xamarin.Forms, to support animations. The library has the notion of behaviors and actions. A behavior is attached to a control and listens for something to happen, such as an event firing. When the “something” happens, it triggers one or more actions, such as invoking a method or command. Actions are invoked by behaviors and executed on a selected control.

In this blog post, I’ll demonstrate using the EventHandlerBehavior and FadeAction classes to run a fade animation when an event occurs.

Fading a VisualElement when an Event Fires

The EventHandlerBehavior class listens for a specified event to occur, and executes one or more actions in response. It requires you to set an EventName property to the event that you want the behavior to listen to, and an Actions property to one or more actions that should be executed in response to the event firing. Note that the Actions property of the EventHandlerBehavior instance is set indirectly by creating the FadeAction instance as a child of the EventHandlerBehavior instance.

The FadeAction class performs a fade animation when invoked, and allows the following optional properties to be set:

  • TargetObject – an object that is the VisualElement on which to run the animation. If this value is omitted the object the behavior is attached to will be set as the target on which to run the animation.
  • FinalOpacity – a double that specifies the value of the Opacity property to fade to. If this value is omitted the default value of 1 is used.
  • Duration – an int that represents the length of the animation in milliseconds. If this value is omitted the default value of 250ms is used.
  • EasingFunction – an EasingFunction that specifies any velocity changes in the animation. If this value is omitted the default value of the linear easing function is used.
  • Await – a boolean that represents whether the animation should be awaited, or whether it should be allowed to complete in the background. If this value is omitted the default value of false is used.

The following code example shows an example of using the EventHandlerBehavior and FadeAction classes to fade in an Image control when a Button is clicked:

<Image x:Name="image" Source="monkey.png" Opacity="0" VerticalOptions="CenterAndExpand" />
<Button Text="Run Animation">
<Button.Behaviors>
<behaviors:EventHandlerBehavior EventName="Clicked">
<behaviors:FadeAction TargetObject="{x:Reference image}"
FinalOpacity
="1.0"
Duration
="2000"
Await
="true" />
</behaviors:EventHandlerBehavior>
</Button.Behaviors>
</Button>

When the Button.Clicked event fires, the FadeAction fades in the Image instance over 2 seconds (2000 milliseconds), and the animation is awaited. This means that if there were subsequent animations defined, they would only execute after the fade animation has completed,

The advantage of using the FadeAction is that it’s possible to invoke animations through XAML, rather than having to use C#. In addition, when combined with behaviors, a fade animation can easily be invoked from XAML when a behavior occurs, such as an event firing, or a when a piece of data changes.

The sample application that this code comes from can be downloaded from GitHub.

Summary

The FadeAction class allows fade animations to be invoked through XAML when a behavior occurs, such as an event firing, or when a piece of data changes.

June 09, 2016 11:22 GMT

Xamarin Evolve Redux

Xamarin Evolve was over a month ago … and I’m first getting around to writing about it now?!? Well, what can I say – it’s a busy world out there! But there were enough announcements and enough cool events that happened that I still wanted to comment on them – even though it’s well after the fact! So let’s dive into the big news that came out of Evolve …

I Spoke!!

Ok – my session on developing apps for AppleTV and tvOS may not have been the biggest news to come out of Evolve, but it was pretty exciting for me. The whole behind the scenes operation at a major conference is really unbelievable, from the knowledgable people that work to pull it off, to the amount of equipment – truly a sight to behold. So I want to send a thank you to Xamarin for having me speak, it was a great opportunity, and I can’t wait until next time!

And yes, I will have a series of blog posts coming on tvOS development using our favorite language … C#! But in the meantime – check out my session above!! (And if you can’t get enough, I’ll be giving the same session at That Conference in August!)

The Other News

Many other announcements were made during the opening day’s keynote at Evolve, which is also posted on YouTube. I won’t go through every single announcement, but I will touch one some of the ones that I think will made day to day life much easier for Xamarin developers. Starting with the big one…

Xamarin.Forms XAML Previewer

If you’re doing any sort of Forms work with XAML, odds are you’ve been waiting for this tool for a long time now! It takes the XAML for your page and live renders it side-by-side … in design time!

xaml_previewer

As of right now this feature is only in Alpha (so you’ll have to live a bit on the wild side in order to use it), and it doesn’t support Shared Projects. But those will be remedied soon. It should be noted there is another great tool out there called Gorilla Player, which does the same thing, but actually renders it in simulator/emulator or device. They are worth checking out as well.

Xamarin.Forms Native Embedding

nativeembed

This doesn’t seem like a big deal until you think about it a little. Native embedding allows one to stick actual Xamarin.iOS or Xamarin.Android code for controls smack dab into the middle of Xamarin.Forms code!
And of course, one of the first benefits that comes to mind is that it will greatly ease the pain of working with custom renders!

Visual Studio iOS Simulator Remoting

This one is readily apparent as to its usefulness … now we’re able to run the iOS simulator from Visual Studio … on Windows. Not just launch it, but run it. That means if your hardware supports touch – the simulator will also support touch, and that’s more than you get out of the Mac side of things. I have yet to try this one yet as I use a Mac for day-to-day development work. However, I thought this was a big enough announcement that I wanted to mention it.

Test Cloud Live

The last thing I wanted to touch one is called Test Cloud live. The premise behind this is simple – you can connect to a specific device running within Xamarin’s Test Cloud and debug there. Live. From Xamarin Studio. A customer calls and has issues with a particular model of phone, instead of writing UI tests (you know you should … but …) you can connect it your code to TC and debug on device as if you had a physical one in hand. That’s cool and something I want to explore further in a future blog post.

The Non-Tech Stuff

Most, if not all, of the conferences I have gone to have a friendly vibe to them. Some are super welcoming, and no matter who you are or who you know, you’re going to have a great time. Others are friendly enough, but it feels like you need to know somebody in order to be “let in” and fully experience it. Xamarin Evolve is definitely the former. Everybody there is talking mobile development, and everybody is interested in what each other is doing. There are plenty of Xamarins walking around, all willing to stop and talk either about the problem you can’t solve, or just to say hi. The overall welcoming, friendly vibe is definitely cool. But let’s not forget about some of the intangibles – such as networking, meeting people you’ve only talked to on GitHub or Twitter. And of course – all the free food, drinks and no waiting for rides at Harry Potter world!

June 05, 2016 6:02 GMT

ASP.NET Core 1.0 RC2 support in Xamarin Studio

Xamarin Studio and MonoDevelop now have support for ASP.NET Core 1.0 RC2 with an alpha release of the .NET Core addin.

ASP.NET Core web project in Solution window

This is an update of the original DNX addin which adds support for .NET Core RC2 and also, thanks to David Karlaš, adds support for debugging .NET Core applications on the Mac.

Features

  • Debugging .NET Core applications with the .NET Core CLR on Mac.
  • Project templates for console, library and web applications
  • Code completion
  • NuGet integration
  • Solution window integration

Supports

  • MonoDevelop and Xamarin Studio 6.0 (build 5166). (Note that 6.1 is not yet supported)
  • .NET Core 1.0 RC2.

Installing .NET Core SDK

The .NET Core SDK needs to be installed separately before using the .NET Core addin. Detailed installation instructions can be found on Microsoft’s .NET Core web site.

Installing the addin

The addin is currently available from MonoDevelop’s Add-in Repository in the alpha channel. In Xamarin Studio open the Add-in Manager and select the Gallery tab. Click the repository drop down and if Xamarin Studio Add-in Repository (Alpha Channel) is not displayed then click Manage Repositories. In the window that opens tick the check box next to Xamarin Studio Add-in Repository (Alpha Channel) and then click the Close button.

.NET Core addin selected in Addin Manager dialog

Select the .NET Core addin and then click the Install button.

After installing the .NET Core addin you will need to restart Xamarin Studio before the project templates are available in the New Project dialog.

Creating a .NET Core project

There are three project templates available for .NET Core in the New Project dialog.

New ASP.NET 5 project templates

Debugging

Thanks to David Karlaš there is a support for debugging .NET Core applications when running on the .NET Core CLR if you have the VSCode Debugger addin installed.

Debugging a .NET Core application

The VSCode Debugger addin is currently available from MonoDevelop’s Add-in Repository on the alpha channel.

Debugging .NET Core console and web projects that target the full .NET framework is supported on all platforms. The .NET Core command line tool (dotnet.exe) will create an executable when targeting the full .NET Framework which can be debugged in Xamarin Studio. On Windows the x86 version of the .NET Core SDK needs be installed since Xamarin Studio currently cannot debug x64 applications on Windows.

Source Code

The source code for the addin is available on GitHub.

June 05, 2016 4:07 GMT

El valor de ir al mínimo con aquello que sueñas sin querer

Este fin de semana estuvimos mis amigos y yo hablando de la [conocida para algunos] ecuación de la felicidad:

gif.latex

Las personas más felices, según ésto, son aquellas que acercan el numerador al denominador. Bien reduciendo el 1º, bien aumentando el 2º.

A mi me ocurre que, por definición, el 1º suele estar muy por encima del 2º. Las personas que nacimos en España entre los 80 y los 90, nos solemos encontrar  en ésa tesitura: abuelos que mal-vivieron la Guerra Civil, padres que sobre-vivieron hasta la Transición e hijos que nacieron en el auge: “le daremos a nuestros hijos todo aquello que no hayamos podido tener nosotros”. Resultado: personas que esperamos todo y más pero tenemos mucho menos de éso. Mucho / poco, infelicidad.

“La culpa es de mis padres, ya me podrían haber educado en la humildad”. Error. Los padres lo hacen lo mejor que pueden. No hay más. A nuestros hijos les daremos todo lo que podamos. Lo que también intentaremos es amueblarles la cabeza de modo que sepan gestionar racionalmente sus vidas.

“Entonces, nada que hacer, como me han educado así, así me quedo”. Sí y no. Sí porque hay una parte de abundancia en el interior acomodada desde que eres pequeño que cuesta eliminarla. Y no porque aún siendo difícil eliminarla, puedes corregirla poco a poco.

Una persona a la que aprecio mucho me dijo hace años:

En tu caso tienes que ir al mínimo en lo que hagas

Un ejemplo: siempre me ha gustado ver bailar hip-hop/funky a los demás. La música R&B me da ese qué-sé-yo-que-yo-qué-sé que me hace sentir bien cuando la escucho, de buen rollo, con ganas de comenzar algo que tenga que hacer a continuación. A veces me doy cuenta que, de forma inconsciente, me imagino bailando de forma increíble, haciendo una coreografía rodeada con otros bailarines, como aquel que lleva toda su vida bailando, y se dedica en cuerpo y alma al baile.

Pero yo no soy bailarín. Ni soy asiduo a las discotecas donde quizá podría más ponerlo en práctica. Me apunté a una academia y sólo estuve 1 ó 2 meses. Porque requiere tiempo ensayar. Y el tiempo es algo que comienza a escasear con los 30. Y tampoco, si pienso en serio qué quiero ser de mayor, me veo bailando R&B, la verdad.

En cambio, me sigue encantado escuchar la misma música, y ver a los que saben bailar. Lo sigo haciendo. Es mi forma de “ir al mínimo”. La forma de acercar expectativas a realidad. Y ser más feliz al final.

¿Alguna vez te has parado a pensar esto? ¿Serías capaz de reconocer aquellos pensamientos que te sitúan sin esfuerzo más allá de donde es lógico? Dedícale 5 mins y piénsalo. Cuando encuentres alguno, ve al mínimo. Y, si quieres llegar más lejos, da un pasito.

Esta mañana era feliz parándome a ver el papel que juega cada uno de los integrates de este grupo acapella:


June 03, 2016 1:11 GMT

Continuous integration/continuous delivery for your Xamarin app with VSTS and HockeyApp &amp;#8211; Part 1

Continuous delivery is the new agile

This is a quote a saw on Twitter by Sander Hoogendoorn and it seems that he is kind of right. Continuous Integration (CI) and Continuous Delivery (DI) are rapidly becoming more and more popular and together with that there are a lot of tools to support you with that. And rightly; it’s freaking awesome stuff!

But how does it work for your Xamarin app? What tools are available and how do I get my own pipeline set up? And what will it cost me as a simple, single developer? I will answer all of these questions and explain you how to do it! And yes, you can do it completely for free!

In this post… And what is not.

There are several ways to set you up. As a Microsoft developer I’m going to assume that you already (know how to) use Visual Studio Team Services (VSTS formerly known as Visual Studio Online). Since Microsoft has acquired HockeyApp and Xamarin, they now have all the tools to supply you with a fully featured CI/DI pipeline. Ultimately it would look like this.

VSTS CI/DI Pipeline
VSTS CI/DI Pipeline

In the bottom left corner is you, typing your awesome code like a boss. And when you’re done, you check it in, this will trigger a automatic build to check if your code runs not just on your machine and integrates with the code of other developers which work on the same project.
If that succeeds you can have some unit tests run over them and send your app over to Test Cloud to have it tested on physical devices. If so far everything still everything is ok you can either send it directly to the store or first distribute it to HockeyApp so it will go to (beta) testers.

In this post I will describe how to setup VSTS so your build will trigger automatically and send it over to HockeyApp. As a bonus I will describe how to setup your spare Mac as a build agent, which you will need if you want to build and deploy your iOS apps.

In other posts later on I will describe how to do it using Bitrise.io which does not require you to provide your own Mac. And maybe even AppVeyor. I will probably mention these to tell you about some differences among them.

So what is not in this post is triggering any kind of tests. Simply because it is too large a subject to just mention it here sideways, also something I will focus on later.

First; checking in

It all starts with your check in. To make this all work it is easiest to use Git as a source control provider. This is all nicely integrated in VSTS nowadays so that shouldn’t be a problem, but it is something to consider when you create a new project. You cannot convert from one to another later on, so get it right from the start or be prepared to lose all your history.

Let’s go into our visualstudio.com account, go into the project you want to unleash the magic on (in my case Boodschappie, which is an app I’m developing right now for groceries management) and hit the green plus button on the left side.

Add build definition
Add build definition

Like you would expect from a Microsoft product you’ll get a screen where you can choose from several templates which already do most of the work for you. If you’d want to you can start with an empty one. While you go through the list you notice that there is a Xamarin.Android and Xamarin.iOS, no Xamarin.UWP and no Xamarin.Forms.

This is perfectly plausible. Remember; Xamarin.Forms is an addition to regular Xamarin.iOS, Xamarin.Android and Xamarin.UWP apps. So when it comes down to building and distributing your apps they are still separate apps. Let’s focus on the iOS app first, so select the Xamarin.iOS template and click Next.

Already we have arrived at the last step of creating are build config! That wasn’t so hard! Here you can configure where you want your source to come from. You probably want to stick with the first option but as you can see you can also use a GitHub or even other repository sources. Also you can specify which repository and branch is to be used.

Build definition repository
Build definition repository

There is also a checkbox for ‘Continuous integration’ this means the build definition will fire every time you do a checkin of your code.

Last but not least you can configure your Default agent queue. Agent.. whaaaaat..?

For now just click Create and read about build agents below.

Build agents

A build agent in the term for a server which is listening to your TFS server until its services are requested. The services of a build agent are to build you code! For on-premise TFS service in a small business it is/was usually enough to install an agent directly on your TFS server and build it there. For larger corporations it could be necessary to have multiple build agents so that if one is busy, another can take over.

Now with Microsoft supporting a lot of different platforms there is a new use-case for having different build agents. A build agent on Windows does not have the capability to build iOS projects. Simply because Apple is keeping the lid on the iOS SKDs and have them only running on Mac hardware with XCode.

So you would need a separate build agent for building your iOS projects. I will explain how to do this further on, it’s pretty easy to do nowadays, but you do have to have a spare Mac!

If you don’t then another alternative could be MacInCloud. Basically what they do is rent you a Mac which you can use for your build needs. Prices start at one dollar per hour by pay-as-you-go to about 30 dollars per month to have a build agent which suits your need. I do not have any hands on experience so I cannot tell you about the speeds, but if it is any comparison, my on-premise Mac build agent working with VSTS is surprisingly quick!

If you do have any experience with MacInCloud please share!

Configuring the build definition

Ok, so we have created a build definition. If you go into it you’ll see that there are already some steps in there, and judging by those red markings it isn’t very happy.

Build agent steps
Build agent steps

The first and last steps are easy and not completely relevant any more. Since Xamarin licenses are free now I think these will disappear over time. Actually, try to leave them out if you’re feeling adventurous en let me know what happens

Any way, just input your Xamarin account in there for now. You shouldn’t feel comfortable with just entering your password in there plain text, so let’s find out how to go about that.

(Secure) build variables

Go to the Variables tab at the top of the screen. There are already some values in there. Click the Add variable button at the bottom of the list to add a new one.
Name it appropriately, in this case something like ‘XamarinPassword’ should do and enter your password in the Value field. Now click the tiny lock after the Value field. Your password Value field should transform into a password box. Now you can use this variable in your build step and you don’t have to share your password with everyone. Awesome!

This can be used for all kinds of values you want to be variable! Secure or not.
Also, you can use them in any build step that you create. So use them to refer to certain files or paths, passwords, version numbers, etc. If you get the hang of this you’ll see the use for it.

Also it is good to know that there are a lot of variables already built-in which can give you all kinds of information about the build being err… built. Check out that list and some more information here.

Finishing the build definition

So lets go back to the Build tab and go into the Activate and Deactivate step. Now instead of your password enter $(XamarinPassword). Awesome!

Alright, now for the hard stuff. The actual build step.

Xamarin iOS build step
Xamarin iOS build step

Actually the only thing we really have to do here is specify the solution that has to be built. Click the browse button at the end of the input field to choose one from your repository.

There are some more options you can configure which shouldn’t be a stranger to you if you have looked at creating an app package before. I am going to assume you have.
Most important here is probably the Signing & Provisioning part. You can provide a p12 certificate file and .mobileprovision which are used to sign and provision this ipa. This is iOS specific. For your Android project you will have to do something with a keystore here.
You can also use your app identifiers, which will require you to have the neccesary certifications and provisioning profiles on your Mac build agent. Also, if you have these settings in you project file already, there is no need to override them here. Again, then you will have to have the required configuration on the Mac you’re building this on.

The final step is to run the test project through Test Cloud. As said before, I am going to leave this out for now but it is very important to have your tests in place!
Firstly because Test Cloud is just awesome. Secondly so you can keep track of the quality of your app. If you want to do this, just configure it the way you know how. If you’ll do this later, easiest is to uncheck the Enabled checkbox and enable it when you’re ready.

On this end everything is ready to go!  Now we just need that build agent.

Installing the Mac build agent

Now that we have our build definition ready, we are going to need our build agent ready to do work.

I was able to try this out with a simple Mac mini which was lying around, the specs are from a few years back, it’s nothing fancy, it doesn’t even have a SSD yet. Still, performance is pretty good! It doesn’t have to do very hard work so some basic hardware is already enough.

If you don’t want to use it for anything else (which I would recommend), just wipe it and clean install the latest Mac OS version. Also install XCode and Xamarin. I didn’t have any other use for my Mac other than building stuff so I also setup TeamViewer with unattended access so I now just have a Mac somewhere in a closet with a power and network cable and that’s it.

Last thing you have to do to get things running is installing the build agent. This can easily be done from VSTS on your Mac. Go into your dashboard and click the configuration (gear) icon in the upper-right corner. This is something that can work a bit confusing.
If you click it from a project you’re in you’ll get a different configuration then when you click it from you overall VSTS dashboard. So if you don’t see the Agent Pools tab, check the upper-left of the screen and click your username. The path should say ‘Control Panel > Username‘ not ‘Control Panel > Username Project‘. See the screenshot underneath.

Ok, so go into the Agent Pools tab.

Agent pools

Agent Pools
Agent Pools

If you haven’t setup a build agent before you’re screen is probably blank here.
The Hosted pool is pretty awesome. This pool is provided by Microsoft with basic (shared) build agents in Azure which provide in your basic building needs. Most of your .Net projects can build on them out of the box.

If you have specific needs, you can setup your own pool, or pools. You can arrange them whatever you like. Group them by capabilities, geographical location, color, whatever you want! But since you will probably have just one just put it in the default pool.

 

For setting up the rest of your agent check out this link by Rene van Osnabrugge which knows a awful lot about ALM, so let him explain it best to you!

Queueing your first build

After you have this up and running go back to your build definition and try to queue your first build!
You’ll feel like a downright hacker doing so because all of the letters scrolling over your screen. It will probably take you some times before you get it right. Examine the log closely to see what goes wrong and what you could do to fix it.

If you encounter any problems that you can’t solve by yourself, let me know! I’ll be glad to help.

I think I have to conclude for now here and create another post for the second half! So let me know how this works out for you, then I’ll be back for a second part telling you how to get this build to HockeyApp!