December 2016

With Visual Studio for Mac, a lot of new project templates are now available to macOS developers. For example, you can now create an ASP.NET Core or a .NET Core console project directly on your Mac. Wow! But, in my opinion, one of the most interesting project template is the Connected App. With this template you’ll be able to create a complete solution with a Mobile app (iOS, Android and Windows or Xamarin.Forms) and a Backend app, an ASP.NET Core mobile project that will be hosted in an Azure Mobile Services app.

In this post we’ll see how we can create a Connected App and publish our backend to Azure by using GitHub as source control host. Yes, it is a Continuos Delivery system.

Step 1 | Create a GitHub Repository

First of all, you need to create a new GitHub repository. If you already have a GitHub repository, please go ahead. So, navigate to your GitHub page and on Repository tab click on New. After that, create a file to initialize your repository and, on desktop side, clone the repository by using your git client (like GitHub Desktop).

For a full guide, follow these steps:

Step 2 | Create a Connected App solution

After you have created and cloned the repository, open Visual Studio for Mac and create a new project in the local repository folder by using the Connected App template:

Now we have a complete solution, from frontend, the mobile apps, to backend, the web api app:

By using your git client, commit and push the project on GitHub.

Step 3 | Publish to Azure via GitHub

Finally we are now ready to publish the service to Azure. So, go to the Microsoft Azure portal, log-in into your account and create a new Mobile App.

Set up the Mobile Service with your preferred settings:

To connect our Mobile Service to GitHub, go to Deployment Options and choose GitHub as source.

Then you’ll be requested to authorize access to the GitHub account.

Finally, select the repository and the branch you’d like to use.

And you have done! Now Azure automatically start the deployment process and … BOOM! 

Yes! You got the following error:

Command: "D:\home\site\deployments\tools\deploy.cmd"
Handling ASP.NET Core Web Application deployment.
D:\home\site\repository\XConn\Droid\XConn.Droid.csproj(137,3): error MSB4019: The imported project "D:\Program Files (x86)\dotnet\sdk\1.0.0-preview3-004056\Xamarin\Android\Xamarin.Android.CSharp.targets" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.
D:\home\site\repository\XConn\iOS\XConn.iOS.csproj(163,3): error MSB4019: The imported project "D:\Program Files (x86)\dotnet\sdk\1.0.0-preview3-004056\Xamarin\iOS\Xamarin.iOS.CSharp.targets" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.
Failed exitCode=1, command=dotnet restore "XConn\XConn.sln"
An error has occurred during web site deployment.
\r\nD:\Program Files (x86)\SiteExtensions\Kudu\59.51212.2600\bin\Scripts\starter.cmd "D:\home\site\deployments\tools\deploy.cmd"

Step 4 | Publish with a Custom Deployment script

What happen? Just some background info. The deployment process is governed by Kudu, “the engine behind git/hg deployments, WebJobs, and various other features in Azure Web Sites”. In small words, Kudu scan the repository to find a project to publish. When done, it will generate a deployment script which first step is restoring NuGet packages from the solution.

Ah, the solution! The Connected App solution also include the Xamarin.iOS and Xamarin.Android project. Bingo! The deployment process is trying to solve and build the Xamarin packages on Azure Mobile Service, which is not allowed!

So, what we’ll do is to create a custom deployment script to restore, build and publish only the Mobile Service project. To do that we’ll use a .deployment file (check instruction here):

command = deploy.cmd

And this is the custom deployment script that you can customize by only replacing the project name:

@if "%SCM_TRACE_LEVEL%" NEQ "4" @echo off

:: ----------------------
:: KUDU Deployment Script
:: Version: 1.0.10
:: ----------------------

:: Prerequisites
:: -------------

:: Verify node.js installed
where node 2>nul >nul
  echo Missing node.js executable, please install node.js, if already installed make sure it can be reached from current environment.
  goto error

:: Setup
:: -----

setlocal enabledelayedexpansion

SET ARTIFACTS=%~dp0%..\artifacts





  :: Install kudu sync
  echo Installing Kudu Sync
  call npm install kudusync -g --silent
  IF !ERRORLEVEL! NEQ 0 goto error

  :: Locally just running "kuduSync" would also work
  SET KUDU_SYNC_CMD=%appdata%\npm\kuduSync.cmd
  SET DEPLOYMENT_TEMP=%temp%\___deployTemp%random%


IF DEFINED MSBUILD_PATH goto MsbuildPathDefined
SET MSBUILD_PATH=%ProgramFiles(x86)%\MSBuild\14.0\Bin\MSBuild.exe
:: Deployment
:: ----------

echo Handling ASP.NET Core Web Application deployment.

:: 1. Restore nuget packages
call :ExecuteCmd dotnet restore "XConn\MobileAppService\XConn.MobileAppService.csproj"
IF !ERRORLEVEL! NEQ 0 goto error

:: 2. Build and publish
call :ExecuteCmd dotnet publish "XConn\MobileAppService\XConn.MobileAppService.csproj" --framework netcoreapp1.0 --configuration Release --output "%DEPLOYMENT_TEMP%"
IF !ERRORLEVEL! NEQ 0 goto error

:: 3. KuduSync
call :ExecuteCmd "%KUDU_SYNC_CMD%" -v 50 -f "%DEPLOYMENT_TEMP%" -t "%DEPLOYMENT_TARGET%" -n "%NEXT_MANIFEST_PATH%" -p "%PREVIOUS_MANIFEST_PATH%" -i ".git;.hg;.deployment;deploy.cmd"
IF !ERRORLEVEL! NEQ 0 goto error

goto end

:: Execute command routine that will echo out when error
set _CMD_=%*
call %_CMD_%
if "%ERRORLEVEL%" NEQ "0" echo Failed exitCode=%ERRORLEVEL%, command=%_CMD_%
exit /b %ERRORLEVEL%

echo An error has occurred during web site deployment.
call :exitSetErrorLevel
call :exitFromFunction 2>nul

exit /b 1


echo Finished successfully.

Finally, you can publish the .deployment and deploy.cmd files to the root of the repository. Once done, the deployment process restart and now … the Mobile Service is up and running!

Happy coding!

Read more

Xamarin.Forms is a great way to abstract the local implementation. But, you know, sometimes you need to perform some small adjustments based on the underlying OS. Is this the case of the iOS Status Bar style.

Xamarin.Forms implements, in the NavigationRenderer, a way to automatically set the style (dark/default or light) by checking the Luminosity value of the BarTextColor property. Check the following code:

if (statusBarColorMode == StatusBarTextColorMode.DoNotAdjust || barTextColor.Luminosity <= 0.5)
	// Use dark text color for status bar
	UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.Default;
	// Use light text color for status bar
	UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.LightContent;

For full code, check the NavigationRenderer source on github Xamarin.Forms project.

Now, if in your code you set the BarTextColor to black, then the status bar style will be the Default (dark). Otherwise, the status bar style will be light (white).

So, if we want to set the BarTextColor, in a classic Xamarin.Forms App class constructor, we’ll have something like this:

public App()

	MainPage = new NavigationPage(new MainPage())
		BarBackgroundColor = Color.FromHex("#043596"),
		BarTextColor = Color.White

But, this is not enough.

In iOS, we have two ways to set the StatusBarStyle:

  • at application level
  • at view controller level

The default behavior is at view controller level. Since Xamarin.Forms sets the StatusBarStyle at application level, we need to set the related property in the Info.plist. So, open the info.plist file, go in the Source tab and add a new entry with this values:

Name = UIViewControllerBasedStatusBarAppearance
Type – boolean
Value – No

And we have done! Now start the app and check the result:

Nice and simple!

Read more

Windows Communication Foundation (WCF), the Microsoft framework for message exchange between systems, has come a long way since when it was called Indigo, about ten years ago.

In the last versions, all the efforts have gone in the direction to optimize and simplify development:

  • Simplified Generated Configuration Files
  • Contract-First Development
  • Add Service Reference From a Portable Subset Project
  • ASP.NET Compatibility Mode Default Changed
  • Streaming Improvements
  • New Transport Default Values
  • XmlDictionaryReaderQuotas
  • WCF Configuration Validation
  • XML Editor Tooltips
  • BasicHttpBinding Improvements

You can find all the details about this topics on the following page: WCF Simplification Features. If you are curious about what’s new in WCF 4.5, check this page.

In the next posts we’ll see some of the improvements and the impact in the everyday development.

Read more

This is the third post of the A little and simple Bindable (Horizontal) Scroll View saga. In the first post we saw how to implement a horizontal view with data binding capability. Then, in the second post, we have seen how to add an event to handle the tap gesture on list items.

In this post, we’ll see how to add the Command pattern to the TLScrollView and get working one of the most used way to catch the user UI interaction directly into the ViewModel.

Adding the Command and CommandParameter properties to the TLScrollView

The first step is to add two bindable properties: SelectedCommand and SelectedCommandParameter.

public static readonly BindableProperty SelectedCommandProperty =
	BindableProperty.Create("SelectedCommand", typeof(ICommand), typeof(TLScrollView), null);

public ICommand SelectedCommand
	get { return (ICommand)GetValue(SelectedCommandProperty); }
	set { SetValue(SelectedCommandProperty, value); }

public static readonly BindableProperty SelectedCommandParameterProperty =
	BindableProperty.Create("SelectedCommandParameter", typeof(object), typeof(TLScrollView), null);

public object SelectedCommandParameter
	get { return GetValue(SelectedCommandParameterProperty); }
	set { SetValue(SelectedCommandParameterProperty, value); }

The first one will be used to reference the Command object instance, the event handler into the view model, while the second one is the instance parameter that will be passed to the event handler.

After that, we need to modify the TLScrollView Render method to use the new SelectedCommand and SelectedCommandParameter properties, if used:

var command = SelectedCommand ?? new Command((obj) =>
	var args = new ItemTappedEventArgs(ItemsSource, item);
	ItemSelected?.Invoke(this, args);
var commandParameter = SelectedCommandParameter ?? item;

var viewCell = ItemTemplate.CreateContent() as ViewCell;
viewCell.View.BindingContext = item;
viewCell.View.GestureRecognizers.Add(new TapGestureRecognizer
	Command = command,
	CommandParameter = commandParameter,
	NumberOfTapsRequired = 1

Use the Command pattern to get the selected item

To use the Command pattern in our solution, we need to add a property in our viewmodel that will be binded to the UI control:

public ICommand ItemSelected { get; set; }

and then initialize it with an event handler in the viewmodel’s constructor:

public MyViewModel()
	ItemSelected = new Command(arg => DoSomething());

finally we can bind the SelectedCommand property to the ItemSelected property:

<controls:TLScrollView Orientation="Horizontal" ItemsSource="{Binding Items}" SelectedCommand="{Binding ItemSelected}" HeightRequest="100">

Use my ViewModelBase

One step further is to minimize coding by using my ViewModelBase implementation. After extending your custom ViewModel with my ViewModelBase, you can simply write a method with the name ItemSelected and the _ExecuteCommand suffix:

public void ItemSelected_ExecuteCommand(object args)

After that, you need to add square brackets around the ItemSelected name in your XAML SelectedCommand assignment definition:

SelectedCommand="{Binding [ItemSelected]}"

Nice and really simple. As usual, you can find full code with sample on my github repository.

Read more

A long time ago, in the first post, I wrote about the TLScrollView, a way to create a simple, horizontal and bindable list of items in Xamarin.Forms. The final result is something like the horizontal views on Apple App Store app.

After receiving some feedback, users ask for a way to handle the tap gesture on the items. We have two possible approaches: the first one is by using the classic ItemSelected event handlers, and the second one by using the Command pattern, typical solution in MVVM.

In this post we’ll explore the first approach.

Adding an ItemSelected handler to the TLScrollView

So, first of all, we need to add an ItemSelected event, a delegate of type EventHandler to the TLScrollView:

public event EventHandler<ItemTappedEventArgs> ItemSelected;

Now, in the Render method, we can add the following line in the for..each cycle, just after settings the BindingContext of the ViewCell:

viewCell.View.GestureRecognizers.Add(new TapGestureRecognizer
	Command = new Command((obj) =>
		var args = new ItemTappedEventArgs(ItemsSource, item);
		ItemTapped?.Invoke(this, args);
	NumberOfTapsRequired = 1

Now, in your XAML, you can define the handler in this way:

<controls:XScrollView Orientation="Horizontal" ItemsSource="{Binding Items}" ItemSelected="Handle_ItemSelected" HeightRequest="100">

then you can implement your handle:

void Handle_ItemSelected(object sender, Xamarin.Forms.ItemTappedEventArgs e)
	// your code

That’s really simple! But if you want build a code in line with the Separation of Concern, typical principles of MVVM, a SelectedCommand property should be the best way.

I’ll show the step neeeded to add the command pattern to the TLScrollView in the next post of this series.

Full code is available here

Read more