0 Comments

pexels-photo-277803

When writing an app that only allows access to certain or all parts of the app when a user is logged in requires a login screen which can be presented to the user at every screen in the app I.e. as soon as he is required to login or re-login.

In this post you will see how to create a view that can be used to enter the username and password. Further we will look at how we can use this screen regardless of which screen is currently displayed to the user.

Writing a login view

Let’s consider a view as follows.

LoginScreen

It requires a username and password, the user can confirm his entry by hitting a button which will validate his entry.

After entering a correct login the user will be presented with the apps content. In our case a simple screen containing a logout button.

So far so good, but how will we ensure that the user only sees the content after she has logged in? How do we prevent the user form simply dismissing the page? Well let’s dive into this topic as next.

Login sites and Navigation

So implementing the view and even the business logic of a login site are quite straight forward but how do can we pop up the login view whenever the user is required to authenticate himself I.e. has to re-authenticate? And how do we prevent him from leaving the screen. Luckily all this can be solved by using the modal navigation backed in to Xamarin Forms. Utilizing a simple navigation service from a previous post, we can ensure invoke the navigation to the login page from any page or even when resuming the app or on start up:

Using modal navigation with a simple  navigation service allows us to implement a login dialog that can be pop over any view currently displayed and return the user to the sensitive content once he is properly authenticated.

No way back

Though modal pages do not provide the user with a software button in the navigation bar to return to the previous page. The dedicated OS back button on Android and Windows 10 can still be used by the user. To ensure the user can not leave the page via the OS button the OnBackButtonPressed method has to be override as follows:

Instant Login View navigation

When requiring the user to log in on the initial start up of the app or resume. Often it is desired to simply overlay the login view over the page that should be displayed when the user is successfully authenticated. Want we do not want is the user to ever see the landing page before being logged in. To achieve this effect we can want to insert our check before the page is displayed to the user and then navigate without animation to the login page:

Improve user input experience

When creating the user login what would be nice is if the user could simply navigate from the username to the password field via the enter button on the keyboard. After completing the password it could directly verify the username and password when pressing enter. This can be done in the code behind of the login view as follows:

Conclusion

In this blog post we saw how we can create a view for a login page and also implement the logic behind it. Through modal navigation we saw how we can “capture” a user on a view and prevent him from leaving the view before he has entered some valid credentials.

We then improved the UX by showing the login page instantly when resuming or starting the app. Plus improving the entry of username and password.

You can find a sample of the login view on GitHub.

0 Comments

pexels-photo-297755

If you have ever written a Xamarin Forms app and wanted to navigate from within a View Model to another page. Then you have come over the issue that the navigation logic usually resides in the view. Since every best practice blog post, course and video tells us that the view and business/control logic should be separate. We are often left with the question how to integrate a View Model based navigation.

What we want to do

The goal of this post is to show you how we can initiate a navigation call from the View Model. Without adding dependencies to your view or writing call back methods.

Navigation 101

In Xamarin Forms there are two fundamental ways of navigating between pages:

  • Push
  • Modal

Push navigation is the most straight forward way for navigating in an app. The main page in the App.xaml.cs is a NavigationPage which contains the main page displayed to the user:

When navigating to the next page, the page gets pushed onto the navigation stack. The user can then navigate back via Screen (iOS & Windows) or Hardware button (Android & Windows). Navigating back will dispose the current page, pop a page from the navigation stack and display it to the user.

When navigating to a page using Modal. The target page is displayed in a separate navigation context. This results in the behaviour that the user is no longer displayed with a software back button from the OS. The back navigation call differs from Push. Thus it requires invoking a different method of the Navigation Page.

Modal navigation is a great option to capture the user on a view. This is not generally what we intend to do with a user. But if the user has to login or the users consent is required (are you really sure...) filling out a form. Then modal navigation allows keeping the user on a page and handling the navigation via custom defined logic.

Note: Modal navigation is an iOS concept in it’s origins. Under Android and Windows the user has system buttons to navigate the app. If the user should not be able to leave the page and return to the previous page I.e. user has to login first. The developer will have to override the OnBackButtonPressed with a return true in the code behind of the view.

Navigation TL;DR;

We have two navigation methods in Xamarin.Forms. These are Push and Modal. Each has different ways of invoking the navigation. Which also applies to the back navigation.

Using a navigation service

In general the navigation service will have to contain a Navigation Page to handle the navigation stack. Further it needs to offer a Method for navigating to a page via push or modal navigation and allow navigating back.

The initialisation of the navigation service can now be done in the App.xaml.cs by registering all the views with a corresponding key.

In a view model we can now navigate to a page by providing the service with the key of the target page. If required we can also pass in a parameter. Since the parameter is of type object there are no limitations there.

As mentioned before modal navigation leaves the current navigation stack and displays the page on it’s own. If we want to navigate from a modal root page via push to a child page. The modal root page has to be in a Navigation Page itself. This is what the navigation service does automatically. It further removes the navigation header of the modal root page.

Back navigation checks what back navigation is intended for the current page. A root page in a navigation stack is either the root page of the app or a root page in a modal navigation stack. In either case it will choose the appropriate back navigation method.
If the page is not the root page we simple navigate back to the previous page that was pushed onto the navigation stack.

Conclusion

Using the navigation service described in this blog post. It is possible to navigate from the view model to other pages. Doing so we do not add dependencies to the view stack e.g. Xamarin Forms. Nor do we have to write cumbersome call back methods for each navigation action over and over again.

I would like to thank Laurent Bugnion at this point who laid down the base of the described navigation service above in with his initial implementation of a Navigation Service for Xamarin Forms when using MVVM Light.

You can find a running sample on GitHub.

0 Comments

NetStandardLogo

The wait will soon be over and we will all be able to use .Net Standards for sharing all our code across .Net run-times. But for the current time we are still in a transition state, not all libraries support .Net Standard out of the box. One option would to rely on good old Portable Class Libraries (PCLs) for now. But the PCL comes with many restrictions compared to a .Net Standard library. Plus .Net Standard is where all the action is (and will be) happening. So it seems like a no brainer to choose .Net Standard as our library container to share code.

But what when we are using a library that does not support .Net Standard out of the box? For instance let’s say we want to use Reactive UI as our MVVM framework for a Xamarin.iOS and Xamarin.Android app. When trying to add Reactive UI version 7.4.0 (latest stable version as of writing) via NuGet to our .Net Standard Project. We get the following error message:

Error message that .Net Standard library is not among the supported .Net Frameworks of this NuGet package

The solution to our problem is to define the required targets in our .Net Standard Project. The targets which the Reactive UI NuGet package defines. We can edit a .Net Standard library by right clicking on it in Visual Studio and selecting Edit Project name:

Right-Click menu showing the edit option of a .Net Standard Project

Now we can define the targets by adding the PackageTargetFallback line to our DotNetStandard.Core.csproj file:

Providing the targets provides NuGet with the information needed to install the package. Rerunning the NuGet installation once more leads to a success Smile

Successfull installation of Reactive UI after changing the project

Conclusion

.Net Standard is the future of writing .Net Libraries which runs on multiple .Net runtime Environments.

Happy coding and don’t let those not-yet ported libraries stop you from achieving your goals!

0 Comments

PureLayout is a library for iOS developers that allows to create UI views in code behind with ease. With PureLayout.Net this option is now available for Xamarin.iOS.

Since PureLayout.Net is based on the idea of defining your UI in code you might be tempted, especially as a C# developer, to dismiss it as an utterly bad idea. Because defining UIs in code is such a no-no right? Well actually no, not under iOS. The standard approach under iOS is to use the Storyboard to define your UIs and your screen flow. This is great at first since it is very much like Windows Forms with all it’s drag and drop goodness. The problem arises in two areas:

  1. Having more then one person editing the Storyboard
  2. Sharing standard values such as Margins over the entire UI

TL;DR;Define your UIs in a reusable way that allows to share design standards and reduce duplication within UI work. Enable collaboration on UIs without the fear of merge conflicts by using PureLayout.Net. Which you will be able to use in no-time.

Since the storyboard is one large (generated) XML file. Any change to the UI is stored in a single location. In a larger project this will mean that whenever two or more people will want to make changes to the UI a merge conflict could arise. Should a merge conflict arise… Well to put it short you are out of luck. Since the XML gets generated it is not human friendly to merge. An error while merging will result in the entire UI of the app being in tatters. Now one could mitigate this problem to a certain degree by using XIBs. But those come with some extra glue code to get it running. Plus there is still this second point.

If you are working on a larger app, you will (want to) have some sort of a style guide. In it you will define a set of defined constants for your colours, margins, text sizes, fonts etc.. Going with the Storyboard or XIB designer will not provide you with a central coded style file. The only way to define and distribute the style is in a written text document such as a Word-, PDF-File or a Wiki page. This approach comes down to every one, who works on the UI, needing to know this document. The current version may I add and apply the styles. This can be a challenge to say the least.

All this can easily be avoided by using PureLayout.Net. - Which I hope does not come as surprise at this moment Winking smile

Where to get it

Simply add the NuGet package to your iOS project and you will be all set:

Install-Package PureLayout.Net

How to get started

A getting started guide can be found on the projects GitHub page.

Thank you

I would like to point out that PureLayout.Net is only a wrapper around the existing PureLayout library written Objective-C. Therefore a big thank you to Tyler Fox the creator and Mickey Reiss for currently maintaining the library.

Further I would like to thank Samuel Debruyn for helping me a lot on the topics of wrappers with his blog post.

0 Comments

Processed with VSCO with j2 preset

In the previous post we saw how methods i.e. functions can be implemented with PowerShell. Functions are not only a great way to structure code for reuse but also allow to create larger scripts. Whenever writing code that ends up in production it is always a must to ensure that the code runs as expected. When the Script is small or does not invoke any long running services we can do this quite simply by executing the script. However the more complex a script becomes or is integrated into long running processes the harder it becomes to ensure that the script is still running as intended after changes.

This is where automated Testing allows to ensure functional correctness without demanding any great user interaction to execute multiple test scenarios.

Writing automated Tests

PowerShell comes with it’s own testing framework called Pester. Which is the de facto standard PowerShell testing framework and comes with every installation of Windows 10. Pester follows a Behavior Driven Development (BDD) test-development style. I’ll leave it up to you to follow up on the difference between Test Driven Development (TDD) and BDD, for a framework it usually shows in a more human friendly description of the tests.
Let’s get started by having a look at what we want to do in a C# context.

For the C# samples we will be using the xUnit.net framework which follows the xUnit pattern. Let’s assume we have the following class we would like to test:

We could verify the functionality with the following test:

For PowerShell the same function could look like this:

And the corresponding test function looks like this:

From the structure there is a lot in common.

Note that Pester strongly nudges the developer to go along with a certain naming pattern for files. When a function is in a file called Something.ps1, the corresponding tests should be in the file Something.Tests.ps1.

When we execute the PowerShell test from the PowerShell IDE console pane we get the following result in the PowerShell Window.

Showing console output of the testrunner (executed in VS Code)

There are multiple assertions you can use within pester as one can see in the following overview:

  • Should Be
  • Should BeExactly
  • Should BeNullOrEmpty
  • Should Match
  • Should MatchExactly
  • Should Exist
  • Should Contain
  • Should ContainExactly
  • Should Throw


Mocking external dependencies

When writing automated tests one topic quickly arises and that is how to manage dependencies to the outside world. When writing automated tests we can separate them into different categories:

CategoryDescription
Unit TestsTesting the core logic of code. Tests that logic has been implemented according to specs and ensures that the core building blocks are working correctly. No dependencies to other code e.g. Modules in PowerShell. Should make up the majority of automated tests in a project.
Integration TestsTest a part of an application i.e. Script. Ensuring that the tested parts work together which may involve calling services outside of the script itself.
These tests are usually the easiest to implement but are more fragile than unit tests. An error might be caused by an other system or a logic error in the script. In large projects you should have more Unit Tests than Integration Tests.
System TestsTest entire use case scenarios end to end. These tests should run scenarios of the script e.g. “Setup new Web Server Instance”, “Setup new DB instance”. They usually take a long time to run and may require upfront work regarding infrastructure i.e. a staging/testing environment.
In general you should only test your core scenarios with System Tests. They usually take a lot of upfront investment to create the environments and also require a lot of maintenance since they have to be adapted once a change to the system is made.

Since PowerShell was mainly created for automating infrastructure tasks, most of the code you would write is interacting with one or multiple systems in one kind or the other. As long as our scripts are only reading we might not feel the need for mocking our services i.e. as long as they are not overly slow. But when we start writing to production systems we surely do want to be certain that our scripts run as intended. And this is where mocking comes in. Under C# there are multiple libraries for mocking external dependencies of a class. A very popular one (and my personal favorite) is Moq.

So let’s assume we want to mock an external dependency which returns us all the entries in a directory. We would write it something like this in C# (a bit lenthy I know...):

Now in PowerShell we would implment the function as follows:

And Pester provides a handy mocking functionality:

Not only is this a great way to test our code without having to actually be on the filesystem but it also shows how we could mock other dependencies such as a system clock (midnight testing anyone?), network calls etc. which for one will ensure that the script does not actually invoke any external sources. Another benefit you will most probably see is a speed up in execution time. Since everything is running from in memory (aka fast Winking smile) there is no network or disk delay. For further information and options on mocking check out the official documentation of Pester.

Executing the Tests

We can also execute the test from the command line with the following command:

Invoke-Pester

The command can be extended with parameters described here. While skimming through the parameters you may notice that they would provide the means to enable Continuous Integration (CI) for PowerShell Scripts. This is the case, we could add a Step to a Visual Studio Team Service (VSTS) or Team Foundation Server (TFS) build configuration by adding a PowerShell step with the following parameters:

If you already have a build server setup (you can get VSTS for free within minutes….), it is easy to setup a CI job for your scripts. And CI can be a real cure to sleep problems – so if I can have it this cheap the answer is yes please Smile

Summary

In this post we went through how to write tests with PowerShell and execute them. Further we saw how we can mock dependencies. We further looked at how tests can not only be executed during development but also how we can execute the tests in an automated build process i.e. Continuous Integration (CI) environment.

References

Check out my previous posts on how to get started with PowerShell for the C# developer:

You can find more detailed information about Pester on their Project Page.

External References