Add a stylish Navigation Drawer to your Xamarin.Android application

These hamburger menus do not only look neat, they also provide a great way of navigating through an application and display additional information or quick settings. Since Google itself uses them in nearly every application users expect one of them when swiping from the left side of the screen. In this post I want to show you how we can add a backward compatible material Navigation Drawer to our apps.XamarinNavigationDrawerDemo

Backwards compatibility

First make sure that our app is backward compatible. Do do so, add the Android Support Library v7 and Android Support Design Library to your project and make sure that your activity inherits from AppCompatActivity. Additionally we need to use a style that inherits from a Theme.AppCompat version like the Theme.AppCompat.Light.DarkActionBar theme. If you need help with this, check the demo code on GitHub.

Prepare you layout

Now we can add the Navigation Drawer to our layout. For this, we use android.support.v4.widget.DrawerLayout as our root layout and add all the content that we want to show inside of it. Beside the content we also add a android.support.design.widget.NavigationView element which will contain the flyout menu. The most important properties are the menu and headerLayout attributes which stands for exactly what you would expect: For the options that should be shown inside the navigation drawer you can define a menu just like you know it from the Action Bar. If you want to define a custom header for your drawer do it in an extra layout file and reference it. Afterwards our layout should look like this:

Hint: If you use a Toolbar, also add it inside the DrawerLayout. It needs to be the root element, otherwise the toolbar overlaps the layout and absorbs the touch events.

React on menu item selections

Once your layout is ready it is time to add some logic. The most obvious next step is reacting on item selections. For this, we simply need to add a listener to the NavigationView‘s NavigationItemSelected event inside the OnCreate method of our activity.

Add the drawer toggle button

When you start the app now, you will notice that we can already open the navigaion drawer by swiping from the left of the screen. If you also want to add this fancy drawer toggle button with the three transforming bars to your app keep on reading.

To add an ActionBarDrawerToggle  to the ActionBar, we need to define it inside the OnCreate method. Beside the context, the constuctor wants to know which DrawerLayout this button is for, which Toolbar it should be added to and where it can find the strings for the open and close mechanism. Once definded we can pair the button with the menu by calling the DrawerLayout‘s SetDrawerListener(ActionBarDrawerToggle) method and passing it the button. To make sure everything is connected correctly, we should call the SyncState() method right afterwards.

Now your app should have been enriched by a nice navigtion menu right where users would expect it. But make sure that there is an actual need for that overhead. A Navigation Drawer Menu might be an overkill if you just offer two options in it. You might want to consider using a classic Toolbar menu alternatively.

Do also check the full demo project on GitHub and feel free to ask your questions in the comments.

How I made my router and my Xbox One like each other

Recently I moved house, and one of the first things that were switched on and installed were my console and my internet router. Two weeks ago, I wanted to play Minecraft with a friend, but sadly the new router and the Xbox One weren’t very cooperative.

I tried narrowing down the issue. Standard solutions, like opening all of the ports listed in the official Xbox Support page, or enabling UPnP, didn’t do the trick. It seemed that the Xbox had a problem dealing with IPv6.
When testing the multiplayer connection, I got an error message: Cannot connect to Teredo IP Address

Teredo tunneling gives full IPv6 connectivity for IPv6-capable hosts that are on the IPv4 network, and have no native connection to an IPv6 network. Which was weird, because both my console and my network are IPv6-capable. It seems to be a known issue that the Xbox assumes the communication is going to be tunneled, without testing if there is even the need for it. If Teredo-tunneling is not possible, there is no way to play in multiplayer.

My router (Fritzbox 7360) blocks Teredo by default. So in order to enable that, I switched from View: Standard to View: Extended (which almost deserves a blogpost on it’s own, because the FritzOS UI is horrificly bad).

erweitert

Under the section Internet there is an option for Filter and Lists. So all I had to do is to remove the check next to – “Teredo Filter active“.

teredo

(It’s important to say that communication using Teredo is a security risk, and I personally don’t understand why Xbox uses it as a standard for all IPv6 networks)

This did the trick. Fun times were had!

My Visual Studio solution won’t build although it should. What can I do?

Visual Studio is undoubtedly the best development environment you could get your hands on – but sometimes it can drives you crazy. Espacially in these cases where you know that a project should build but it doesn’t no matter how hard you try. What you can do is trying these tricks and tips. Maybe one of them helps.

Clean and Rebuild

The first thing you should try is to click on Build Clean solution and Build Rebuild solution. In 30% of the cases it already solves your problems.

Restart Visual Studio

May sound simple and stupid but believe me, the next 30% of errors will go away after a simple restart.

Restore all NuGet packages

Sometimes your NuGet packages get lost, corrupted or need to be resored. To fix that you can open the NuGet Package Manager for each Project by right clicking it’s References folder and select Manage NuGet packages. Here you can restore the missing packages.

Another smart way to archive and automatic restore whenever you build a solution is enabling the automatic NuGet package restore option that you can find by right clicking your solution folder in Visual Studio.

Regenerate the .suo file

Another thing to try, is to close VS and delete the hidden .suo file that is next to the .sln file in your solution’s folder. Don’t worry. It will be re-generated the next time you save or build. Note that deleting the .suo file will reset the startup project(s) of the solution.

Make sure, that all projects build

Right click on your solution in the solution explorer, go to Properties and select the Configuration Manager. Check if the checkboxes under Build are checked or not. If any or all of them are unchecked, then check them and try building again. If they are all checked you can also try to uncheck them, apply, check them again and apply again. Sounds weird, but sometimes it helps.

 

Beautify Chome’s JSON Viewer

If you use Google’s Chrome browser to test and develop web applications you might have noticed that the default JSON output is always unformatted. This can often lead to an output like this:

To avoid this mess, Gildas Lormeau published the Google Chrome Add-On JSONView. As soon as it gets installed, it automatically formats your JSON outputs and you can even fold it! That makes the output look way better and noticeable enriches your development environment. So give it a try!

jsonviewscreenshot

Add a documentation to your ASP.NET WebApi in 3 simple steps

A well documented API is a welcome part of every software project. Everyone wants a great documentation, bot nobody really wants to write one. Especially when creating an API which many different people should use, this aspect becomes very important. Furthermore many Scrum teams’ acceptance criteras contain a documentation requirement.

Your luck, that ASP.NET 4.5 comes with a build in API-Documentation functionality that you can implement in three very easy steps:

1. Add build-in ASP.NET WebApi Documentation

Microsoft provides a build-in documentation functionality with its WebApi. When creating a new WebApi Project in Visual Studio, the template already contains a documentation implementation. If you created the WebApi project from scratch, you can add it by loading the NuGet package Microsoft.AspNet.WebApi.HelpPage into your project.

Both ways will create an Areas/HelpPage folder, which contains a bunch of methods and classes that will do the documentation work for you. From now on you can access your documentation at the {YOUR_URL}/Help page.

2. Document your code properly

The smartest way to document your methods and classes in C# is the XML-Documentation approach, that comes with .NET 4.5. This documentation style looks like this in your code:

Hint: You can generate this XML-Documentation header by typing three slashes /// above a method or class.

By using this way of documentation, you do not only create a documentation for your Help page. This information is also used inside of Visual Studio to describe a method and its parameters when using code completion and Intelly Sense.

3. Enable documentation access

To give your Help page access to this documentation you need to enable the XML-Documentation output. By doing this, every time you build your project an XML file is generated that contains your documentation comments. To enable this, you need to select the proper checkbox in the project properties, that you can find at the Build tab.

enabledocumentation1

Hint: By enabling the XML-Documentation output, the compiler will send you a warning for every method or class that is undocumented. If you want to avoid that, add 1591 to the suppressed warnings as you can see in the screenshot above.

Now you only need to tell your HelpPage that you do have such a file and where it is located. To do so, open the HelpPageConfig.cs file, uncomment the following line and edit the MapPath:

Now you are ready to enjoy a fully featured documentation of your ASP.NET WebApi at the {YOUR_URL}/Help page.

Use expressions to build variable names in Angular.js

When working with HTML and JavaScript you sometimes have to do weird things to achieve a specific purpose. In my case one of these things was building a variable name with Angular expressions.

While generating a form via ng-repeat, I also had to generate the name of the input element. For verification, I wanted to add a CSS class to the input whenever it gets marked as invalid. To access it, I had to use the form.element pattern wherefore I wrote something like this, trying to generate the variable name with an expression.

Wrong:

The code above does not only cause errors, it also is invalid HTML so I had to find another way. The solution is replacing the double curly braces with simple square brackets so that the final code looked like this:

Correct:

This works perfectly and is also valid HTML code. I hope that helps and spares your nerves. If you are looking for another working example, you can take a look at this JSFiddle repository, where I created a tiny demo project to play around with.

Hey Git, why don’t you ignore my recently added .gitignore paths?

In projects with a Git source control you often need to tell your repository to ignore changes to specific files that you don’t want to upload to the server and spread them over to other team members. Typical examples are usually IDE related settings or publish information. For this approach, Git provides the .gitignore file where users can enter paths to those files they want to have ignored by the repository. But sometimes this does not seem to work.

In most cases the .gitignore does not work for the same reason: The files you want to ignore have already been added to the repository once. Since then, Git watches about their changes, no matter if they have been added to the .gitignore afterwards or not. To ignore already added files afterwards we need to help ourselves by using a trick.

The shortest way to archive this is removing all files from the git repository and adding them immediately afterwards. This sounds like a huge intervention but is is not that heavy as it seems.

Important: Please commit all outstanding changes to the repository before doing this. Otherwise they will get lost.

Now your .gitignore is working as it should be and you get rid of unwanted files and folders in your repository.

Get rid of cables and Remote Debug your Android device!

Cables are a companion of our everyday life but a necessary evil. I personally avoid using them wherever it is possible and even charge my phone wireless. As a mobile developer you always have a bunch of cables in you bag but the time may come where we do not need them anymore. Remote Debugging could be one step into this direction.

Since Android Lollypop it is possible to deploy your apps via Wifi to your device and debug them there. It can look like magic, when your phone gets remote controlled and states app by his own but is is definately not.

Important: To archive this, your development machine and Android device need to be in the same local network, of course!

Prepare your phone

set_remote_debuggingdeveloper_settingsTo enable Remote Debugging on your phone, you need at least Android 5.0. Go to Settings, select Developer Options and enable the Android Debugging and ADB over network options. That’s it! All you need to do is remember the displayed IP Address, we will need it later.

Setup your PC

Using a Windows Machine you first have to add the location of your Android Platform Tools to the PATH environment variable. These platform tools come with the Android SDK so the path to add ususally looks like this C:\Program Files (x86)\Android\android-sdk\platform-tools.

Afterwards you should be able to access the ADB via command line. To test this, you can simply type adb version. If this works you can connect your device by hitting adb connect followed by the IP Address that your device displayes inside the debug options.
adb_connect

Now you are ready to debug over network and should now see your device listed in the debug target selection of your development environment. Have fun debugging you apps on a real device without any cables and remember to switch debugging off at your phone when you are finished. Otherwise it will kill your battery.

Introduction to UI Tests with Xamarin

One of the things one should never say when delivering an app to a customer- “It was working fine on my device”. To avoid such embarrassment and to make sure the users see what was planned for them to see, test should be written.
I wrote a simple Buzzword Bingo App, called “Bullshit Bingo”, to try and demonstrate how easy it is to write an Acceptance Test with Xamarin.UITests.

About the app:

Bullshit Bingo is game with one simple objective – collect 5 phrases either in a row or in a column. It has 2 Activities – a MainActivity, that holds the controls to start the game, and a GameActivity, that shows the actual bingo card the user interacts with.

Setup:

When I created my Xamarin.Android Solution, it came with two projects – BullshitBingo and BullshitBingo.UITests. In UITests there is a sample Tests.cs file, where the magic happens.

Each UI test should follow 3 simple steps: Arrange, Act, Assert:

  1. Setup your test, initialize things needed at a later point
  2. Do some actions, interact with the app
  3. Make sure you got the right result.

In order for Xamarin.UITests to know what to run in the project, the classes need to be annotated as [TestFixture] and the methods as [Test].

For this demo, I wanted to test only the winning conditions of the app, so I had to make sure the tests were autonomous. To do that, I defined a method, to run Before Each Test to reset the app to it’s original state:

REPL is a great tool to explore the UI and view details about all elements displayed in the current view. It helps to generate a sequence of actions to be used in the test later.

REPL

So my test for the horizontal winning condition looked like this:

I found out, that when it comes to switching between activities, it’s better to wait until the elements from the new activity are loaded with app.WaitForElement() and not rely on UITest to do that for me. In 5 out of 10 runs the test tried to tap on an element that didn’t exist.

TL,DR: Test are important, use Xamarin.UITest, it’s very easy, see the Introduction to UITest for a reference to all possible user interface interactions IApp has to offer.

Upload your UI Tests to the Xamarin Test Cloud

Whenever app development gets more serious and your code becomes more complex, testing your application automatically is a step you need to go to survive. Xamarin provides two neat ways to write UI Tests for your applications. Calabash is a framework you can write tests in Ruby with and Xamarin.UITests provides everything you need to build test cases in C# the NUnit way. Whichever framework you choose, you can write tests for your application very easily and run them on an emulator or local device.

With both ways you can cover a managable range of devices which might not be enough to test how your applications perform in the real world. Especially when developing for Android, fragmentation is your daily companion and is not to be underestimated. Your application may run fine on all of your test devices and emulators but crashes on 80% of the rest.

Xamarin Test Cloud

This is, where Xamarin Test Cloud comes into play. It provides you a way to upload your app and tests to a huge farm of more than 1000 real devices and let them run there. Afterwards you will get a detailed test report of every single device including screenshots and Stack Traces for a comprehensive overview of which devices run your application nicely and which don’t.

I will not cover how to create these test cases in this blog post. If you are interested in the tests, take a look at the sample code at GitHub. What I want to show you today is how to upload your tests to the Xamarin Test Cloud and test your app on tons of devices in minutes.

Preparations

To use the Xamarin Test Cloud you need at least version 5.9 of Xamarin Studio and a Test Cloud subscription. If you already subscribe to one of the Xamarin Platform plans you can start immediately due all of theminclude 60 monthly device minutes which should be enough for our demo. If you have neither, you can at least take a look at the demo accout.

Uploading your test

To upload your project to the Xamarin Test Cloud, simply right click on the tests and select “Run in Test Cloud”. The following steps run almost automatically and your application and tests are going to be uploaded into the cloud.

UploadUITests

Important: Make sure, that you have changed your build configuration to Release and that it does not use the shared Mono runtime and supports the x86 ABI.

As soon as this is finished, your browser pops up and asks you to define your test environment. Basically this is where you can select the devices that should run your test. You can sure between several filters and pre-selections here. I personally liked the “Top 20 devices” option that selects the devices with most market share for you. Make sure that you also add some low end devices to test your application under extreme conditions.

DeviceSelection

Warning: Keep an eye on your remaining test hours! By selecting 30 devices and letting the tests run for only two minutes, your 60 device minutes that come with your Xamarin Platform subscription are already burned. When creating serious test scenarios, you should consider buying a dedicated Test Cloud subscription.

When all tests have finished you can take a look at the results dashboard where you can see how the tests performed on each device. For every single device you can follow each test and the screenshots that have been taken. This provides you insights of how your design works on the device. If a test fails you can also take a look at the Stack Trace and find out, why it crashed.

TestResults

This is how I found out that my demo Pollen application seems to have a memory leak when loading the list of pollen with their images which causes crashes on weaker devices, which I never recognized when testing on my emulators and local devices.

Conclusion

Summarizing it up, Xamarin Test Cloud provides a really attractive way to test your apps on a wide variety of devices within a few minutes. Mobile developers know the pain of fragmentation and no one loves deploying their tests to dozens of physical devices the manual way. And let’s be honest, buying 50 different physical devices is much more expensive than one of these Test Cloud subscriptions!

I hope I managed to make Xamarin Test Cloud tempting for you. If you already have a Xamarin subscription it is definitely worth a closer look. Try it yourself – it might be the child you always wanted! Please also feel free to take a look at the tests in the sample code!