Testing all links in the chain

Our Fitradar solution is using various third party services, and therefore the Integration tests in our solution became a very important part next to the Unit tests. In our backend application we are trying to follow the ideal Test Pyramid

Ideal Test Pyramid

but for some Use cases it makes more sense to run all the involved services rather than replace them with Mock objects, mostly because there is no complex logic involved in particular Use Case; it is rather straightforward without conditionals and loops. And on the other hand the Integration Tests give us more assurance that the Use Case is robust and works as expected. And so for some Use Cases we started to prefer Integration tests instead of Unit tests and our test pyramid became a little bit distorted. The following parts in our back end application are tested by Integration Tests:

  • ASP.NET Core Model Binding. Once we discovered that produced JSON data for some C# objects is not exactly as we expected, and that some incoming JSON is not parsed as we expected we started to test and verify that incoming and outcoming data are transformed as we are expecting
  • ASP.NET Core and third party libraries configurations defined in Startup file. The configurations can be tested only at runtime and therefore to test these configurations we have to run the test web server and make some requests against the server. Some of the configurations we are testing are following:
    • Dependency injection
    • AddMediatR and FluentValidation configuration
    • ASP.NET Core Authentication and Authorization integration with  Firebase Authentication
  • Entity Framework produced SQL code. Especially for complex queries. And Entity Framework save and update logic for complex types where at runtime some nested objects might have different EntityState than parent object. And any complex logic interacting with Entity Framework
  • Integration with Azure Services like Service Bus and Azure Web Functions
  • Integration with Stripe

The crucial factor that made our team write more Integration Tests is the new ASP.NET Core test web host and test server client. It allowed us to quickly setup the test server with our back-end application and run the requests against our API. By using the test host we were able to test most of the configurations in the Setup file. It was harder to test our back-end parts that were part of the Azure Functions, but after some error and trial we were able to create a test web host for the Azure functions as well and issue the calls that triggered the Functions. And here is how we test the sport event cancellation Use Case that is triggered by message from Service Bus queue:

        [Fact]
        public async Task TestUnpaidEventCancelled()
        {
            var resolver = new RandomNameResolver();

            IHost host = new HostBuilder()
                .ConfigureWebJobs()
                .ConfigureDefaultTestHost<CancelSportEventFunction>(webJobsBuilder => {
                    webJobsBuilder.AddServiceBus();
                })
                .ConfigureServices(services => {
                    services.AddSingleton<INameResolver>(resolver);
                })
                .Build();

            using (host)
            {
                //Arrange
                await host.StartAsync();
                _testFixture.SeedSportEvent();
                await _testFixture.BookSportEventInstance();
                _testFixture.AddCommentToSportEventInstance();

                //Act
                await _testFixture.SendMessageAsync("CanceledEvents",
                    _testFixture.CanceledSportEventInstance.Id.ToString());
                await _testFixture.WaitUntilSportEventInstanceIsCancelled();

                //Assert
                //_output.WriteLine($"Found {parsedOrders.Count} invoices.");
                var calendarEvents = _testFixture.GetCalendarEvents();
                Assert.Empty(calendarEvents);
                var order = _testFixture.GetCancelledSportEventOrder();
                Assert.NotNull(order);
                var msg = _testFixture.GetVisitorsInboxMessage();
                Assert.NotNull(msg);
                Assert.Equal(MessageSource.CANCEL_EVENT, msg.Source);
                var statistics = _testFixture.GetVisitorsInboxStatistics();
                Assert.NotNull(statistics);
                Assert.Equal(1, statistics.NumberOfCancelMessages);
            }
        }

P.S. Visit our website: https://www.fitradar.me/ and join the waiting list. We launch very soon!

SwiftUI and UIKit interoperability

Many iOS developers started to insert SwiftUI views into existing production projects. UIHostingController makes it really easy to integrate. Yet sometimes you need it vice versa: insert a UIKit view into SwiftUI view. In FitRadar we provide calendar view to show not only your trainings, but also display other events from calendars on device. Trainers will find it easy to plan, avoid overlapping or help customers not to book training when there is important meeting planned.

Photo by Waldemar Brandt on Unsplash

This time we use power of UIViewRepresentable. In this example FSCalendar view (written in Objective-C) needs to be inserted in SwiftUI view, linked with MVC view model. Official documentation is quite laconic about it’s usage. I assume there are many ways how to embedded view behind UIViewRepresentable structure. Some advice to use Coordinator. I don’t see big value in it for our case, since I want make this view reusable and make view model be responsible for calendar view data representation.

Let’s create the “view wrapper” for calendar

import SwiftUI
import FSCalendarstruct CalendarView: UIViewRepresentable {
var calendar: FSCalendar
@Binding var isCalendarExpanded: Bool func makeUIView(context: Context) -> FSCalendar {
calendar
} func updateUIView(_ uiView: FSCalendar, context: Context) {
let scope: FSCalendarScope = isCalendarExpanded ? .month : .week
uiView.setScope(scope, animated: false)
}
}

Normally, you would want to create FSCalendar inside makeUIView(context:) but we want keep reference to it, so we create it outside and pass as reference on creation. Another option we pass via binding is calendar mode which is either month view or week view.

After this we may insert in SwiftUI as easy as

CalendarView(calendar: viewModel.calendar,
isCalendarExpanded: $viewModel.isCalendarExpanded)
.frame(maxWidth: .infinity)
.frame(height: viewModel.calendarHeight)

To support this configuration we need a view model

class HomeViewModel: NSObject, ObservableObject {
@Published var calendar = FSCalendar()
@Published var isCalendarExpanded: Bool = true
@Published var calendarHeight: CGFloat = 300.0 override init() {
super.init() calendar.delegate = self
calendar.dataSource = self
calendar.scope = isCalendarExpanded ? .month : .week
calendar.firstWeekday = 2
}
}

That’s it. Please refer to the source code for full example.

References

https://developer.apple.com/documentation/swiftui/uiviewrepresentable

https://github.com/dmi3j/calendar-demo

Txt: https://dmi3j.medium.com/

P.S. Visit our website: https://www.fitradar.me/ and join the mailing list. We are in beta stage already!

Map in iOS app

Navigation is a crucial part of many mobile applications today. We might not even realise that behind something simple as finding car for rent, food delivery or Pokemon hunting there are some big tech: GPS (satellites in the Space!!!), Google/Apple/Microsoft maps services and, of course, intelligent mobile device with plenty of microcircuit. In FitRadar we use maps services to help trainers set training location by selecting some infrastructure object (gym, stadium, public location) or set some point in unnamed location by the river or lake for many open area activities like yoga, cycling or as simple as walking.

There are simple and clear requirements for map services:

  • present map to set a point for location
  • clustering (show single point on map with number of events instead of plenty points)
  • address search

Personally I try to utilise native platform solution (when it exists) for any problem. Obviously, I started with MapKit. But there is no way to ignore Maps SDK for iOS from Google. Or even check Bing from Microsoft. Integration process for all of them is relatively simple. Some require developer account and developer key creation. But let’s compare how they work.

Map and pin

All three candidates can do simple map presenting and selection random pin with coordinates pretty well. Also displaying simple map vs satellite is very good in all SDKs. Google maps can use

Clustering

Clustering for MapKit is something they support almost out of the box. For Google Map there is custom plugin. Which seems to be supported for a very long time. I wasn’t able to find any Bing map. (Please, share a link in comments if I’m wrong.)

Address search

Google Maps SDK is and absolute winner in this category. For some reason only Google pays attention not only to world wide known places like London or New York, but it also knows something like tiny beach, on border of Riga, Latvia.

Of course, it’s not something you may advertise on WWDC, but local citizen will appreciate when volleyball trainer organise next meeting at “Salaspils pludmale” app will know exactly where it is.

Bonus

Another “+” for Google Map iOS SDK is ability to use app custom colors to match app desing. This design is a JSON file which can be edited manually (or at online editor) and shipped with app bundle.

Again, I wasn’t able to find similar functionality for Apple or Microsoft maps, but, please, feel free to add in comments if they exist.

Conclusion

So, for today, obvious choice is a Google Maps SDK for iOS. I hope some day Apple bring it attention to MapKit and make it useful for all customer around the world, including some tiny country like Latvia.

Except where otherwise noted, this work is in the public domain.

P.S. Visit our website: https://www.fitradar.me/ and join the mailing list. Our app is coming soon.

P.S.S. Text by Dmitrijs Beloborodovs

Our journey towards serverless

Recently we were working on a ticket booking and booking cancelation feature in our Fitradar solution. In our solution the booking process consists of two steps: the place reservation in a sport event and payment. And in case the user for some reason didn’t make a payment the system should execute one more step – cancel the reservation. The process becomes non trivial when each step is done in separate environments – the reservation is done on the back-end, but the payment is done on the client’s device. The most challenging part was to figure out how to cancel the reservation in cases when payment was not made or failed.

So we started to look for possible solutions. Initially we were considering Background tasks with hosted services but we didn’t like the fact that the background task will be in the same process as our main back-end service and we have to make sure the process doesn’t shut down after the request is handled. And since we were using the Azure Cloud for hosting our beck-end services the next thing we started to look at was the WebJob which seemed a very good solution for our use case until we introduced ourselves to the Azure Functions. After some investigation we came to conclusion that Azure Service Bus with message deferral and Azure Functions would be perfect solution. The idea was to send a message to the Service Bus after the user has made a reservation. The Service Bus would deliver the message to our Subscription with 15 minutes delay and our Azure Function would cancel the unpaid booking. In order to receive the scheduled Service Bus message we needed to use Azure Function with Service Bus trigger.

Once we learned more about Azure Functions we decided to use them for other tasks as well that should be done outside the usual request – response pattern. One of such tasks in our solution was User Rating calculation. The task should run on a regular basis every Sunday night. This requirement was perfect job for timer triggered Azure Function.

We started to work on our serverless functions. After the function was scaffolded we started to add our business logic. And since we already had a solid CQRS architecture in place for the main back-end service and for each use case we were creating a separate Command that was using the rest of our infrastructure we wanted to add another Command for reservation cancelation use case, but we faced some .NET Core compatibility issues. Our backend runtime was targeting .NET Core 2.2 version, but our Azure Functions runtime was targeting .NET Core 3.1. Although we could just downgrade our Functions app runtime but the documentation strongly encouraged to use version 3.1, because Function apps that target ~2.0 no longer receives security and other maintenance updates. And so we started to migrate our back-end app to the .NET Core 3.1.

We followed official documentation but still struggled to make our third party libraries work again. The biggest challenge was to find a way how to make to work FluentValidation, MediatR and Swagger together. Once we updated the FluentValidation registration in the Startup file according to the provided documentation it switched off the MediatR Pipeline Behaviors. And once we found a way how to make Pipeline Behaviors work it switched off FluentValidation rules on the Swagger UI page. The Stackoverflow and Google couldn’t help us and we started to experiment with the available settings for FluentValidation and MediatR registration. After several hours of error and trial  we found one setting that made all three libraries work together nice and smooth. Here is the peace of code that made our day:

services.AddMvcCore().AddFluentValidation(fv =>
                {
                    fv.RegisterValidatorsFromAssemblyContaining<PlaceValidator>();
                    fv.RunDefaultMvcValidationAfterFluentValidationExecutes = false;
                    fv.AutomaticValidationEnabled = false;
                });

Now our Fitradar back-end can really benefit from all ASP.NET Core and Azure Functions provided functionality.

P.S. Visit our website: https://www.fitradar.me/ and join the mailing list. Our app is coming soon.

Fitness and mobile app

Hi ! My name is Dmitrijs Beloborodovs

Fitness become one of the buzzwords along with bitcoin or соvid. The first should eventually stop jumping up and down, the second should go away, yet fitness must stay forever. It is crucial to find a good personal trainer to have a smooth start and keep going for a long time. There is something that might help you with that.

Recently I joined a FitRadar team to help with mobile app development. What is a FitRadar (https://fitradar.me) in a nutshell? Briefly: we bring trainers and audience together. Today, your service must be available via different channels: website, integrated in social media and of course, has its own mobile app. A mobile device knows quite much information about you and your habits: your location, language preferences, your schedule and sometimes even specific health metrics (HealthKit is a good example). In other words, it knows enough to propose you a best fitness trainer or sport community in your area, with respect to your timetable, interest or by your friends recommendation. When you start building something great like this, you want to be sure are are building on solid foundation. Here is the first question you might want to evaluate:

Should I go cross platform or native?

Crossplatform solutions (i.e. Flutter, React Native) might look attractive initially, yet brings problems later: super long polishing to achieve smooth and nice UI/UX to mimic platform (all those bounces and responsiveness, etc) and hard path of integration with platform native hardware (location, calendar, etc). So, for us, answer is go 100% native. Stay tuned to know how well we managed to achieve a primary goal of our mobile app — bring nice experience of finding a sport fo your dreams.

Visit our website: https://www.fitradar.me/ and join the mailing list. Our app is coming soon!

P.S. Source: https://medium.com/@dmi3j/fitness-and-mobile-app-3dca370d8e10