Iphone App and Azure Web Api


In this post, I would like to share with you How to develop a native cross platform mobile application that interacts with Azure Web service.

I. Requirement.

As an account manager, I would like to request a mobile application that allows connecting to Azure web service to add, update, delete and view user accounts remotely.

The user account information need be captured as below:

  • First name: the first name of user
  • Last name: the last name of user
  • Account: the account of the user that can be used to login to our systems.
  • Description

II. Build Azure service

1. Configuration Azure Web app and SQL Database.

  • First, I will create an Azure SQL Database named AzureMobileDemo with Basic pricing tier because this is just a sample database for demonstration purpose so no need a powerful one.
  • And then create new Web App + SQL named HBDMobileService in Azure with App server plan is F1 Free and lets it connect to AzureMobileDemo database that created in the previous step.

    Until now, we shall have an HBDMobileServer that connecting to AzureMobileDemo SQL database on the Azure portal. The Application Settings should be shown as below. Please ensure that the connection name is DefaultConnection if not just click on the connection string and rename it. Because we will config this name into the WebApi project later on next section.

2. Develop Web API

Below are tool and libraries I’m using for this project.

  • Tool: Visual Studio 2017
  • Framework: .NetCore 1.1
  • Libraries: EntityFrameworkCore
  • Project Type: Web API

A new Web API project named AzureMobileService had been implemented as the class diagram below.

There is a UserController had been created which exposed all needed actions:

  • Get all users in the database.
  • Get user by primary key.
  • Add new user.
  • Update the existing user.
  • Delete the existing user by primary.

This controller will user MobileDbContect to interact with Database. MobileDbContext is an instance of DbContext in EntityFrameWorkCore that’s using User as data model to transfer the information.

Please note that the name of connection string needs to be provided in the Startup class as below.

As I’m using code first in this project and wishing to execute the database migration automatically when applicate start in the Staging or Production environment. So, I updated the Startup.Configure method as below.

3. Deploy AzureMobileService to Azure.

Before deploying AzureMobileService to Azure we need config the publish profile for this project. The publish setting can be downloaded from HBDMobileService as screenshot bellow.

Right click on the AzureMobileService and click on publish, select import profile and then click create profile button to import the publish profile file. After imported, the Publish configuration should be shown as bellow.

Now, click the Publish button to deploy the web service to your Azure portal. After deployed you can use Postman to verify the Web API to ensure it’s working properly.

Take note the Site URL in the screen shot above we will need it for the iPhone application on next section.

III. Build iPhone application

As the Visual studio 2017 already interested with Xamarin and able to develop a cross-flat form application that can be run on IOS, Android and Window Phone. However, if you want to build an IOS app on Window you still need to link Visual Studio with a Mac that installed XCode and Xamarin. So for simply, I will using Visual Studio for Mac to develop it instead and below is tool and libraries were used to develop this project.

  • Tool: Visual Studio for Mac
  • Framework: .NetCore 1.1
  • Libraries: Xamarin Forms
  • Project Type: Multiplatform – Connected App (Forms)
Open visual studio and create a new solution named AzureDemo the visual studio will create 4 projects:
  • AzureDemo: this is the main project we will implement the views and the logic of the app.
  • AzureDemo.Droid: this project will port the AzureDemo to Android application.
  • AzureDemo.iOS: similar with Droid project, this project will be port the AzureDemo to an iOS application.
  • AzureDemo.Service: this project can be removed as we already develop the Azure service above. The reason I’m using Window to develop the Azure service because Visual Studio for Mac is still previewed version and it is not fully supported Azure deployment.

The implementation of AzureDemo as below:

 There are 3 Views had been implemented:
  • UsersPage: Display the list of users.
  • UserDetailPage: Display details information of Use.
  • NewUserPage: Allow to add new or Edit User information.

The screenshots on iOS

The screenshots on Android

Before running the source code you should update the AzureMobileAppUrl in App class with your Azure service url mentioned above.

IV. Source code

  • Download source code here
  • Report issue here

As you see in the current Web Api source code all APIs are opening for everyone without any restriction. This is bad idea that any application can access your production data. So the recommendation is using Filtering to secure your Web Api? I will post a separate topic to discusing How to secure the Web Api soon.

In these projects, I’m trying to keep the source code as simple as possible for those who want to start learning Azure and Mobile development can catch up easily.

Please feel free to comment your opinion or email to me via [email protected]

Coding for Unit Testing.


This topic is discussed the class designation for unit testable. If you were started to write the unit test for your classes recently, definitely you may face the problem that some classes can’t be writing the unit test or alot of time has been spen for the single unit test. Why your class is not testable or it is not easy to write the unit test? Is you class is depending on many classes that can’t mockable?.  So this topic will consolidate the patterns to implement a class that can be written unit test easily and efficiently.

Why should we write unit tests?

  • Writing tests forces, you to make your code testable by refactoring the code. These topics will focus on two types of dependency-breaking refactoring below:

1. Refactoring to allow injection of fake implementations of those abstract or interfaces.

2. Abstracting concrete objects into interfaces or abstract to allow replacing underlying implementation.

  • The unit tests are really just the documentation of how your code should behave. If you cannot tell from looking at the code what it is trying to do, which is a problem in itself, you at least have the unit tests to tell you the story. Because it isn’t easy to remember all the edge cases after six months?

If the answers above if not enough to convince you to start writing unit tests, then I hope the 12 reasons to write Unit Test here will satisfy you.

 The recommendation of a Unit Test.

A unit test should have the following properties:

  • It should be automated and repeatable.
  • It should be easy to implement.
  • It should be fully isolated (runs independently of other tests).
  • When it fails, it should be easy to detect what was expected and determine how to pinpoint the problem.

Many people confuse the act of testing their software with the concept of a unit test. To start off, ask yourself the following questions about the tests you’ve written up to now:

  • Can I run and get results from a unit test I wrote two weeks or months or years ago?
  • Can any member of my team run and get results from unit tests I wrote two months ago?
  • Can I run all the unit tests I’ve written in no more than a few minutes?
  • Can I write a basic test in no more than a few minutes?

I. Refactoring to allow injection of fake implementations.

The helper class for the SQL connection will be implemented as a demonstration for this topic. Let’s review the code of SqlHelper below. The constructor will receive a connection string and create a SqlConnection instance with that connection string.

The expectation, when writing the unit test for the constructor method is to create an instance of this class with a connection string and then call the Open method, the State property should be Open.

The test method can be written as below.

This test case will be passed as long as the SQL connection string is correct and code coverage is 100%. However, this test is dependent on SQL Server. So if your SQL server is not available for some reason or running this test case in CI server with different SQL Server instance. The test case will fail because it can’t connect to the real SQL Server.

Review the code above, we saw that the State property is actually returning the value of State value of SqlConnection and the Open method is called the Open method of SqlConnection. However, The purpose of this unit test is checking for SqlHelper class instead of SqlConnection.

So the unit test can be written to produce the following steps:

  • Create SqlHelper with non-empty string.
  • Call Open method.
  • Verify that the Open method of SqlConnection is called.
  • Verify the State property is Open.
  • Verify that the State property of SqlConnection is called.

However, SqlHelper is creating SqlConnetion instance inside the constructor directly. So that we can’t create a mock of SqlConnection and pass into SqlHelper. Thus, We will use the Shims of MSFakes to redirect the method calling to a custom method as below. (Refer here)

The unit Test with MSFakes.

This unit test is cover 100% of the code and not require the SQL Server as the Open method has been redirected to a fake method one. However, The MSFakes is only available in an Enterprise Visual Studio edition.

How can we write the unit test using Moq instead of MSFahes? Currently, The design of SqlHelper isn’t able to use Moq to create a mock of IDbConnection and pass it in.

Let’s refactor the SqlHelper class that can use Moq to mock the dependency objects.

1. The constructor parameter factoring.

The concept of constructor parameter factoring is asking all dependency objects at the constructor parameters of your class instead created it inside.

So the constructor method with an IDbConnection parameter was added. This method will set the IDbConnection to the Connection property. Why the parameter is IDbConnection but the required object is SqlConnection. Because Moq framework can’t mock the sealed class.

By using this constructor, we can create a mock of IDbConnection and pass into SqlHelper class. So the unit test with Moq can be written as below.

The unit tests with Moq.

This unit test is working as expected, but the code coverage is 73,33% only. Because constructor method with ConnectionString parameter hadn’t been tested.

One more unit test to verify constructor method with connection string of SqlHelper:

  • Create an instance of SqlHelper with dummy connection string.
  • Verify the Connection property is not be NULL and the type is SqlConnection.

The code coverage again with both above unit tests is 100%.

2. The virtual method factoring.

The concept of virtual method factoring is all new() methods should be wrapped into virtual methods. Because the virtual method can be overwritten by the Mock Framework.

As SqlHelper above, it’s able to write the unit test with Moq and the code’s coverage is 100%. However, there is a constructor method still create a SqlConnection directly.

So a new protected virtual method named BuildConnection has been added. This method just creates and return a SqlConnection instance. Then the connection string constructor method will call BuildConnection instead of creating SqlConnection directly.

Moreover, The new unit test method may be writen as below:

  • Create the mock of SqlHelper.
  • Overwrite the BuildConnection method to returns the mock of IDbConnection.
  • Verify the method call.

This unit test will cover 70.59% of your code coverage.


Unstill now, we have 3 unit tests using Moq framework and 1 unit test using MSFakes. That cover 100% of SqlHelper code coverage.


  1. SqlHelper_RealInstance_VerifyConnectionProperty_Test.
  2. SqlHelper_Constructor_WithMockIDbConnection_Test.
  3. SqlHelper_Constructor_WithConnectionString_Test.


  1. SqlHelper_Contructor_WithMsFakes_Test.


II. Abstracting concrete objects into interfaces or abstract class.

This pattern is recommended that your classes should be inherited an interface or abstract class. By this way, the mock framework can create a fake object of your class from derived interface or abstract class.

The SqlHelper above will be extracted to an interface as following. All necessary methods and properties are defined in the interface.

The interface.

The SqlHelper class.

Download source code here.

Agree that coding the Unit test is quite challenging. However, If you want to keep the code coverage around 70% is not too hard. I have some HBD projects here that have the code coverage around 70% you would take a look.

Hope this topic help when you’re going to implement your application intended for unit testing purpose.


What Is ReadOnlyCollection In .Net 4.5?


As you know, the new interfaces  IReadOnlyCollection<T>, IReadOnlyDictionary<T>  and IReadOnlyList<T>  had been added to DotNet4.5. The purpose of these interfaces is providing the generic read-only collection. For that purpose, the DotNet framework also provided the implementation of these interfaces: the  ReadOnlyCollection<T> was inherited IReadOnlyList<T> , and ReadOnlyDictionary<T>  was inherited IReadOnlyDictionary<T>.

The IReadOnlyList<T>  is just an additional that inherited from IReadOnlyCollection<T>  with indexing added.


What is different between Array and ReadOnlyList?

As of now, may you have a question that why do we need these type when we already have Array? However, the purpose of these types already tells via the name. They will provide a read-only collection of item T that is not allowed to add a new item or replace the existing with the other one. As the following code, we will show you the difference between Array and ReadOnlyCollection.


What is difference List<T>.AsReadOnly()  and List<T>.ToArray() ?

Let’s create the huge list of M items.

So what happens when we call list.ToArray()? the framework will create an array with exactly the same size with the list and copy all items in the list to that array by looping on each item of the collection. This behavior quite expensive when working on a huge list.

However, when calling list.AsReadOnly(). It will create the new instance of ReadOnlyCollection and pass the current list into that instance without any loop.


What ReadOnlyCollection does when passing a list as constructor parameter?

Review a part of ReadOnlyCollection’s implementation below, we understand exactly what ReadOnlyCollection does with the passing list. The ReadOnlyCollection just wrapped the passing list inside instead of copied every item of the list.

So The ReadOnlyCollection is a wrapper for any collection that implements IList<T> . It does not copy elements from the IList. Instead, it adds a level of indirection that reduces possible changes.

The ReadOnlyDictionary is working the same way for any collection that implements IDictionary<TKey, TValue> .


When should we use ReadOnlyCollection and ReadOnlyDictionary?

This is just an example to answer the question above.

Readonly Collection Sample

Looks at the diagram above shows you that the Configuration management component is sharing the config collections at cross Biz and DAL layers.

As you know Biz and Dal layers can be added in as many as the application required. So how can we warranty that the config collections are consistent in all layers and none of them can modify the sharing configuration collection? In this case, ReadOnlyCollection and ReadOnlyDictionay are useful. So that Configuration management can load the config values from Db, Json file or the other providers and wrap them into a read-only collection accordingly and provide to the consumer components.

The right way to use IReadOnlyCollection

Let’s review the piece of code below. Both properties are returning the IReadOnlyCollection. However, the second property is more dangerous than the first one because the developer can cast it back to the List instance and add the value in without any exception. However, the first property is completely read-only and there is no way to add the value in.

The generic List instance is implemented the IReadOnlyCollection that why we can return the List as IReadOnlyCollection. However, it is not the right way to do so I would recommend using the first property implementation for the IReadOnlyCollection.

This is the extension method to wrap an IEnumerable to the IReadOnlyCollection I had been written in HBD.Framework.  You might want to take a look.

I hope this helps to answer the question why IReadOnlyCollection had been added to .Net 4.5.

Consolidation For Microsoft Test And Microsoft Fakes


What’s new for MS Test?

The Unit Testing Framework (MSTest) describes Microsoft’s suite of unit testing tools as integrated into some versions of Visual Studio 2005 and later.

Similar to NUnit, MSTest is allowed to develop the Unit Test for your projects. From the NUnit 3.0 and latest MSTest will support to test Async methods, added platform support for Windows 10 and Metro application. However, the difference between MSTest and NUnit is MSTest is supported to test SSDT project also (Will discuss this feature in the separate topic).
Below are similarities between MSTest and NUnit syntax.

MSTest Attribute NUnit Attribute Purpose
[TestMethod] [Test] Identifies of an individual unit test
[TestClass] [TestFixture] Identifies of a class of unit tests, all Tests, and Initializations/Clean Ups must appear after this declaration.
[ClassInitialize] [TestFixtureSetUp] Identifies a method which should be called a single time prior to executing any test in the Test Class/Test Fixture
[ClassCleanup] [TestFixtureTearDown] Identifies a method in to be called a single time following the execution of the last test in a TestClass/TestFixture
[TestInitialize] [SetUp] Identifies a method to be executed each time before a TestMethod/Test is executed.
[TestCleanUp] [TearDown] Identifies a method to be executed each time after a TestMethod/Test has executed.
[AssemblyInitialize]  N/A Identifies a method to be called a single time upon before running any tests in a Test Assembly.
[AssemblyCleanUp]  N/A Identifies a method to be called a single time upon after running all tests in a Test Assembly.
[TestCategory] [Category] Identifies a group name of a test method. So the test methods can be grouped by group name.
[Ignore] [Ignore] Identifies that this unit test will be ignored when run the group of unit test methods.

Learn more about NUnit here and MSTest here.

What’s MS Fakes?

Fakes come in two flavors:

Stubs Shims
Create a fake object for an interface or class.
It can implement all properties and methods and an interface. However, only virtual properties and methods of a class can be overwritten.
Modifies the compiled code of your application at run time so that instead of making a specified method call, it runs the shim code that your test provides. Shims can be used to replace calls to assemblies that you cannot modify, such .NET assemblies.
Performance Depend on the custom methods that have been implemented for testing purpose. Slower because they rewrite your code at run time.
Static methods, sealed types Cannot be used for static methods, non-virtual methods, sealed virtual methods, methods in sealed types, and so on. Can be used for all kinds of types.
Internal types Both stubs and shims can be used with internal types that are made accessible by using the assembly attribute InternalsVisibleToAttribute.
Private Method Can only replace visible methods. Can replaces calls to private methods if all the types on the method signature are visible
Interfaces and abstract methods. Stubs provide implementations of interfaces and abstract methods that can be used in testing Shims can’t instrument interfaces and abstract methods because they don’t have method bodies.

Below diagram shows you the functionality of each flavor on your unit testing behavior.

Fakes replace other components


What’s Difference between MSFakes and Moq?

Shims and Moq.

MSFakes is only available on Visual Studio to Premium or Ultimate (VS 2015 Enterprise).

Moq can create a dummy object for an interface or overwrite the virtual methods, properties of a class, the behavior of Moq and Stub is likely the same.

However, MS Fakes has a powerful flavor called shims. Shims can intercept the real methods of a class inside an Assembly and redirect the method-call to a method that has been defined as an overwritten in the shims context.

Below code is overwriting the get method of System.DateTime.Now property and return the fixed date whatever System.DateTime.Now is called.


Stubs and Moq.

Hopes, the comparison bellow will help to decide when the Stubs or Moq should be use.

 Stubs  Moq
Override methods to return hard-coded values also referred to as state-based.

Example: Your test class is depending on a method Calculate() taking 5 minutes to complete. Rather than wait for 5 minutes you can replace its real implementation with stub that returns hard-coded values; taking only a small fraction of the time.

Very similar to Stub but interaction-based rather than state-based. This means you don’t expect Mock to return some value, but to assume that specific order of method calls are made.

Example: You’re testing a user registration class. After calling Save, it should call SendConfirmationEmail.

 Stub is like making sure a method returns the correct value.  Moq is like actually stepping into the method and making sure everything inside is correct before returning the correct value.
 Stub: a dummy piece of code that lets the test run, but you don’t care what happens to it.  Mock: a dummy piece of code, that you VERIFY is called correctly as part of the test.

How to Fake an Assembly on your Unit Test Project?

In your unit test project right click to an assembly which you want to create a Fake and choose Add Fakes Assembly. Visual Studio will create a Fakes assembly and add to your test project reference as a photo below. Then you can use it as a normal assembly. The Fake classes will have prefix is Shim or Stub.

This topic is consolidated my understanding about MSTest and MSFakes. If there get some missing, please point it out. So this topic will have more values for those who want to start with MSTest, MSFakes and Moq.

Hope this helps.