Archive for September, 2017

Application Architecture Guidance

Practical advice, best practices, and sample applications for using .NET with microservices, Docker containers, Kubernetes, Xamarin, ASP.NET, Azure, Service Fabric, and more.

Microservices and Docker Containers

Microservices are small, modular, and independently deployable services. Docker containers (for Linux and Windows) simplify deployment and testing by bundling a service and its dependencies into a single unit, which is then run in an isolated environment.

Web Applications with ASP.NET

ASP.NET Core allows you to build high-performance, cross-platform web applications. Patterns like MVC and built-in support for Dependency Injection allow you to build applications that are easier to test and maintain.

Deploying to the Cloud with Azure

Production ready cloud applications need to be built for scalability, monitoring, management, security, resiliency, and more. The patterns covered in this guidance include example implementations for Microsoft Azure.

 

Mobile Applications with Xamarin

Xamarin allows you to build native Android, iOS, and Windows applications using .NET. Common patterns, such as MVVM, combined with good application layering, will maximize code sharing and result in an application that is easier to understand, test and maintain.

Taken from:

https://www.microsoft.com/net/learn/architecture

Imagine you have a set of microservices or applications that you want to publish to the world. There are several alternatives out there that you can choose from. Most of the reverse proxies were created when container technology was not around, so you have to jump through some loops to get going. As a broadly used example we will have a peek at how to configure nginx and some of its downsides. To get our hands dirty, we will have a more detailed walk-through of the modern, dynamic Traefik reverse proxy which we will use to deploy some services.

Best in class before Docker: Nginx

There is quite a number of container deployments out there that use nginx as a front end. The configuration is easy to read and write and the C style syntax gives you a cozy feeling. A simple config to deploy a service might look like this:

With this config we created a simple HTTP reverse proxy on port 80. Nginx will answer the requests by forwarding these to the upstream servers. The container with the least number of active connections will be chosen from the pool. Nice configuration. Plain and easy to read.

One thing you will encounter when you deploy nginx in a mutable container enviroment is that you can’t replace containers without at least reloading the nginx configuration although the container DNS name is still the same. Nginx will cache the IP address to the container and you have to manually take care of it. You can work around this problem in many ways but still you have to take care of it.

Don’t get me wrong: I don’t want to pick on nginx. I like it and used it a lot before I switched to Traefik as my go to solution.

Traefik

There’s a more modern reverse proxy around that is able to handle dynamic container environments: Traefik. It is a small application written in GO tailored to the new challenges. You can use it as a frontend in a variety of environments. The simpler ones are Docker and Docker Swarm, the more complex ones are Apache Mesos or Kubernetes. You can even read metadata from directory services like etcdor Consul.

Back to our application we want to deploy. Let’s imagine we have a set of services that are described in a Docker Compose file. We can wire up our services and deploy these. Here we can have a look at a simple configuration:

This configuration will start the whoami test image that will allow us to see our requests in a kind of echo chamber. You can start it with docker-compose up and call it with your browser. How can we deploy it on a specific virtual host? Let’s extend the configuration a bit by adding Docker labels.

This is the configuration needed for Traefik to deploy our service at http://whoami.server.test . Pretty straightforward.

When you followed the example closely you might ask where Traefik is involved and you are right. Next we need to spin Traefik itself up:

The config above takes care of starting Traefik and will connect to the hosting Docker daemon to retrieve the needed metadata. It will scan for Docker containers that are marked with labels and will publish the services accordingly. The connection is kept so that changes will be reflected without any delay.

Both services are wired together using a Docker network called call webgateway that is prefixed by the project name. If no project name is specified, the name is inferred from the directory name where the compose file is located.

You can find more configuration options on the documentation site: https://docs.traefik.io/toml/#docker-backend. This takes you straight to a backend configuration part. Below that there is a list of Docker labels that can be used to further configure the publishing of the services. Currently we just used traefik.backend and traefik.frontend.rule in the sample above but you can find more.

Once Traefik and the service are up you can connect to the service and test the deployment. Make sure you first start Traefik in this example because the config provides the network the services can connect to.

Have a look at the built in dashboard by pointing your browser to: http://localhost:8080/

Here you can see what services are deployed and how these are configured. You see that our service is available as whoami.server.test. But since we don’t have a DNS record pointing from this name to our localhost, we need to manually set the Host header and call the localhost.

Once you have entered the command, you can see the request that is being sent to Traefik and the response that will be returned. The result will look similar to:

DNS

To fully enjoy the power of Traefik, you need to take care of the DNS records of your deployments. But this is a one time setup, so don’t worry about it too much. One deployment we run at a customer consists of two DNS records per host. One is an A record pointing to the IP Address of the host. And the other is a CNAME record that catches all virtual hosts below this one and forwards it to the A entry. This is a simple way to locate our services.

Just a little example to show you the setup:

This will allow us to reach our server as server.test and whatever.server.test, youwant.server.test. When you access the site with your favorite tool like a REST service, httpie or a browser, the client will forward the target host in an HTTP header called Host. Traefik will find the right container based on this header to forward the request to.

One advantage of using virtual hosts is that you don’t need to take extra care of redirects in your web application. We ran into problems when using relative paths for deployments because nobody thought about that being an option. Once you have your environment set up, you can deploy the services as you like.

Scaling out

Deploying a single container is easy and we could achieve it without any great effort. But what about scaling out? What part of the config do I have to change? The simple answer is: You don’t have to change your config. Just spin up more containers and that’s it. In our simple example:

This command will spin up four containers that will get added to the load balancer instantly. You can verify it by hitting the endpoint repeatedly and see the container name change and by having a look at the dashboard that is located on port 8080.

Sticky Sessions

Clearly I would strive for a stateless application backend that can be scaled independently and without any restrictions regarding the service endpoint.

Sometimes you don’t have the freedom because you are running a session-based application that doesn’t distribute the sessions in a cluster of servers. Or – if you think more of REST services – you heavily use caching of resources and you want your sessions pinned to a specific container. No matter why you want your clients to be pinned to a specific Docker container, there is an easy configuration switch to handle it:

This will check for a session cookie with a specific backend as a value. If the cookie is present and the backend is up, the request will be forwarded there. If the backend is down, another is chosen.

Be sure to use the upcoming 1.4 version for this feature or my patched Docker image (marcopaga/traefik:1.3.5.2) if you want to use this feature. Before these versions, the cookie path wasn’t specified so that clients tended to drop the cookie once in a while depending on the request path.

Post originally appeared at:

https://visualstudiomagazine.com/articles/2017/09/06/free-xamarin-book.aspx?m=1

 

Microsoft has been publishing a series of free eBooks and accompanying blog posts providing guidance about .NET application architecture best practices, with the latest focusing on Xamarin.Forms patterns.

Previous guidance addressed microservices architecture, containerized Docker apps and modern Web apps with ASP.NET and Microsoft Azure. The guidance consists of detailed eBooks, end-to-end reference architecture applications used as examples and blog posts that can help developers get a gist of the guidance and decide if they want to dig deeper with an eBook and reference application.

The new guide, “Enterprise Application Patterns Using Xamarin.Forms,” includes source code for a container-based eShop that extends the previous microservice/containers scenario. It includes the following functionality:

  • Authenticating and authorizing with a back-end service.
  • Browsing a catalog of shirts, coffee mugs and other marketing items.
  • Filtering the catalog.
  • Ordering items from the catalog.
  • Viewing the user’s order history.
  • Configuring settings.

“Guidance is provided on how to implement MVVM, dependency injection, navigation, validation and configuration management while maintaining loose coupling,” Microsoft said in a blog post. “In addition, there’s also guidance on performing authentication and authorization with IdentityServer, accessing remote data from containerized microservices, and unit testing.”

Developers don’t have to create the full-blown implementation that consumes back-end services from containerized microservices, however. They can just consume mock data services if they aren’t interested in how to deploy fully functional back-end services.

Written by David Britch, the 91-page book reportedly provides a comprehensive solution for Business-to-Employee (B2E), Business-to-Business (B2B) and Business-to-Consumer (B2C) apps that can share code across all target platforms — iOS, Android and the Universal Windows Platform (UWP) — and help lower the total cost of ownership (TCO).

 

The entire series of eBook guides are available on Microsoft’s .NET Application Architecture site. The new Xamarin.Forms offering can be downloaded here (note that this link triggers an automatic download).

While primarily targeting an audience of developers interested in learning how to design and create cross-platform enterprise apps, the book says it can also serve to help technical decision-makers choose an appropriate approach for creating such apps.

The post originally appeared at:

Developers can use Effects in Xamarin Forms to customize native controls and add some styling of their own. But why not simply use a custom renderer to achieve the same thing? While that is certainly possible there are some benefits to Effects.

Why would you use Effects?

Contrary to a custom renderer that always targets controls of a specific type an effect can be re-used throughout your app. Another advantage is that you can parameterize your effects with additional data. Most people use effects to simply change properties of a native control that aren’t yet made available through the existing Xamarin Forms controls. Effects work by attaching/detaching them to/from a Xamarin Forms control.

To get a quick idea of how that looks in XAML:

<Entry Text=This entry is awesome! TextColor=White HeightRequest=100 VerticalOptions=Center HorizontalOptions=Fill>
<Entry.Effects>
<local:CatEffect />
</Entry.Effects>
</Entry>
view rawCatEffect.xaml hosted with ❤ by GitHub

You can add multiple effects to a control. As you might have noticed this gives you a lot of freedom because unlike a custom renderer you specifically decide which control gets the effect without any need to subclass it. When creating an effect it is not mandatory to implement it in each platform. You can create an effect and choose to only implement it in iOS. It’s completely optional.

Creating our first Effect

We’re going to create an effect which puts an awesome cat as the background image of an Entry. To get started we create a class in our PCL that inherits from RoutingEffect which has no code but we’re going to use it to make sure we can consume our effect in our XAML code:

public class CatEffect : RoutingEffect
{
public CatEffect () : base (“SuperAwesome.CatEffect”)
{
}
}
view rawCatEffect.cs hosted with ❤ by GitHub

This class calls the RoutingEffect base class constructor and passes in a string parameter. Take note of this parameter as you will be seeing it later on in this sample. It is used to initialize an instance of this effect at runtime and is a concatenation of 2 variables we’ll be seeing in the platform-specific implementations of our effect.

Creating the platform-specific code

To actually create the custom Effect you need to subclass the PlatformEffect class in your platform-specific projects and each platform-specific PlatformEffect class subsequently exposes the following properties for you to use:

  • Container – the platform-specific control being used to implement the layout.
  • Control – the platform-specific control.
  • Element – the Xamarin.Forms control that’s being rendered.

When inheriting from PlatformEffect you also gain access to two methods for you to override: OnAttached and OnDetached. You can use OnAttached to apply your effect and OnDetached to clean up your effect. Now let’s create our effect shall we?

On iOS we implement it as follows:

using System;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using SampleApp.iOS.Effects;
[assembly: ResolutionGroupName(SuperAwesome)]
[assembly: ExportEffect(typeof(CatEffect), CatEffect)]
namespace SampleApp.iOS.Effects
{
public class CatEffect : PlatformEffect
{
protected override void OnAttached()
{
try
{
if (Control is UITextField)
{
// Set the border style to none to show background image.
(Control as UITextField).BorderStyle = UITextBorderStyle.None;
// Create an image and set it as background pattern.
var image = UIImage.FromBundle(cat.jpg).CreateResizableImage(new UIEdgeInsets(0, 10, 0, 10), UIImageResizingMode.Stretch);
Control.BackgroundColor = UIColor.FromPatternImage(image);
}
}
catch (Exception ex)
{
Console.WriteLine(Cannot set property on attached control. Error: , ex.Message);
}
}
protected override void OnDetached()
{
// Back to white.
Control.BackgroundColor = UIColor.White;
}
}
}
view rawCatEffectiOS.cs hosted with ❤ by GitHub

On Android our effect code looks like this:

using System;
using SampleApp.Droid.Effects;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ResolutionGroupName(SuperAwesome)]
[assembly: ExportEffect(typeof(CatEffect), CatEffect)]
namespace SampleApp.Droid.Effects
{
public class CatEffect : PlatformEffect
{
protected override void OnAttached()
{
try
{
if (Control is EntryEditText)
{
Control.SetBackgroundResource(Resource.Drawable.cat);
}
}
catch (Exception ex)
{
Console.WriteLine(Cannot set property on attached control. Error: , ex.Message);
}
}
protected override void OnDetached()
{
// Back to white.
Control.SetBackgroundColor(Android.Graphics.Color.White);
}
}
}
view rawCatEffectDroid.cs hosted with ❤ by GitHub

As you can see there are 2 assembly attributes decorating our effect.

[assembly:ResolutionGroupName (SuperAwesome)]
[assembly:ExportEffect (typeof(CatEffect), CatEffect)]
view rawCatEffect.cs hosted with ❤ by GitHub

You might remember I talked about passing a string value into the constructor of your RoutingEffect class in your PCL a bit higher up in this post. These two values uniquely identify this specific effect and are the linking pin between your PCL code and your platform-specific code. These two values need to match the string in your PCL code (concatenated with a period character in between). It’s what makes the whole thing come together!

The result of our Effects

Obviously this leaves a lot to be desired and it serves solely as a sample of how effects work and I can’t call this one production-worthy 🙂 There are however ways you can implement your effects that can be a lot more useful. Some samples include:

  • Creating drop shadows on visual elements
  • Setting keyboard types on an entry
  • Setting auto-correct settings on an entry
  • Etc.

 

Sharing is caring

Why did I create such a useless effect to show off how effects work instead of creating one from the list above? Because the ones I mentioned have already been created by other people! The beauty of Effects is that you can easily share them which is exactly what some people have done. The FormsCommunityToolkit is a project that tries to aggregate Effects (among other things) and you can contribute to it if you’ve created one. Since it already contains some nice ones you don’t have to recreate them yourself.

A word of warning…

You can attach effects to any type of view however you need to take care of the fact that someone might attach your effect to a Button even though it was meant to work with an Entry control. Xamarin Forms does nothing to stop this behaviour. You will need to take care of graceful exception handling yourself just in case this type of thing occurs either by also implementing it for Button or by silently (yet gracefully) failing.