Adding HTTPS to WordPress with Cloudflare

patridgedev.com with a fancy green "Secure" padlock

With some helpful pursuasion from Planet Xamarin, I decided my blog needed to support HTTPS requests. I’ve wanted to find a way to support HTTPS traffic on my blog for a while, but I wanted to find a solution that would Just Work™ without me doing the leg work. I’ll stick to writing the blog posts and let someone else worry about hosting details.

Just like anything security-related, setting up SSL intimidates me a bit (more so because this often involves the dark magic of DNS records). I’ll do security when I have to, but my prerequisite is always that I read so much about the topic I feel comfortable explaining every decision I make to either an expert or someone completely unfamiliar with the topic.

Encrypting patridgedev.com traffic

This blog is currently a WordPress site on a host using AdminPanel. I have spent hours in IIS for ASP.NET sites, but almost nothing on Linux hosting. It’s all just me poking around hoping to find things. Fortunately, when it comes to SSL support, there are simple options that can bolt on to other hosting: specifically Let’s Encrypt certificates and Cloudflare’s secure proxy system.

Everything I looked into for Let’s Encrypt said to use the settings in AdminPanel, but that required some administrator management to enable. These are not my servers, so that was a no-go.

Cloudflare is a proxy between the world and my site that just happens to offer some mostly-automated, and free, SSL support. You give it a domain, it scans the DNS for that domain and creates a new DNS layer, with some requests going through their system before your servers see them. With those DNS records in Cloudflare’s system, you simply update your nameservers at your domain registrar, Namecheap for most of my domains. (Disclaimer: if you buy Namecheap services through that link, they’ll give me little bit as an affiliate.)

In doing this proxy dance through Cloudflare’s DNS, they can encrypt the connection between any web visitor and the Cloudflare servers. These servers then make requests to my existing servers and return the result through that encrypted connection, making patridgedev.com “support” HTTPS requests. You could argue that the connection isn’t yet encrypted end-to-end, which is true, but it’s way better than before where the connection could be compromised at any point from your computer to my servers.

There was zero downtime with this transition. My old DNS entries went away, and the new Cloudflare ones took over. Unfortunately, it also didn’t magically make my site SSL-awesome.

patridgedev.com with several mixed-security broken things making it render horribly in most browsers

Making WordPress SSL-awesome

You probably don’t want to stop here, as most browsers will block mixed content like this. If a malicious attacker can intercept your HTTP requests for the JavaScript on an HTTPS web site, they can do all sorts of nasty things (stealing authentication cookies, making requests on your [authenticated] behalf, changing content in subtle ways). You really do want the browser to prevent that for important sites, even if it means things break. For patridgedev.com, I just don’t want anyone to have such a bad experience on HTTPS, so I had to fix it.

Most of these issues were because links were still being fully qualified to http:// inside WordPress. The simple solution to this was supposed to be setting the WordPress Address and Site Address to https://www.patridgedev.com under Settings>General, but that didn’t seem to do anything for the site. In fact, it made it so my admin WordPress pages would get stuck in a redirect loop.

Setting the WordPress and Site Address fields to HTTPS

Investigating with Chrome Developer Tools showed a request being made over HTTPS and an immediate redirect to the exact same HTTPS URL, meaning it wasn’t redirecting back and forth between two places as I first suspected. I didn’t have anything custom in an .htaccess file, so it wasn’t causing the redirects. The DNS settings didn’t have anything funky that would cause this, just normal A records for www and non-www. I even searched my site’s code for instances of http:, but that was a really noisy set of search results.

My searches for “WordPress too many redirects” were finding lots of potential suspects, but none seemed to apply to my site. Once I added “Cloudflare” into the search term, I stumbled on this Stack Overflow question where the original source appeared to have been having an .htaccess issue. The question had one sad no-votes (at the time) answer that turned out to be my magic bullet.

Inside WordPress is an is_ssl method that checks a couple $_SERVER variables to decide if the current request is using HTTPS and/or port 443, neither of which is technically true for HTTPS requests at that point. WordPress was not seeing HTTPS requests, because they really aren’t. The connection to Cloudflare is secure, but my site is seeing Cloudflare’s proxied requests via old-school port-80 HTTP.

This is_ssl method gets called all over the place to decide how to prefix fully-qualified URLs with a protocol. In order to get through that logic, we have to force the $_SERVER['HTTPS'] variable to be true at the right time before that method is ever called. That’s exactly what the Stack Overflow answer establishes. We set up a little extra check in the site’s root wp-config.php file for a particular header seen on Cloudfare’s proxied requests hitting my site.

php if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') { $_SERVER['HTTPS'] = 'on'; }

With that in place, we force the HTTPS variable to be 'on' for these requests whenever is_ssl is later called for URL generation, resulting in much happiness. There were still a few non-SSL requests on my blog pages, most of which was my own doing.

Cleaning up the last errors

I had a few widget HTML blocks that were referring to HTTP content: an ancient Amazon affiliate script include, an old Stack Overflow profile badge image, an Apple App Store widget for Smudges, and a lot of embedded post images (and post cross-links). All said, it was just a visual find-and-replace job in WordPress. Only the Apple widget wasn’t as simple as adding an “s” to a URL.

Apple add widget snapshot after HTTPS efforts

The App Store widget definitely doesn’t cooperate with a HTTPS page. Presumably, it is mishandling things on a secure connection. It’s especially evil since it seems to render fine, so the non-SSL request is totally unnecessary. Unfortunately, even the latest iframe HTML from Apple hasn’t changed, so the error won’t go away.

It turns out that I had a tendency to be inconsistent when embedding images in my posts. While there are probably ways to do mass find-and-replace efforts in WordPress, I just opened all my posts individually and did the work there. It wasn’t as bad as it sounds; only a handful of posts had the domain hard-coded, and I haven’t written enough posts to feel intimidated by the count.

I probably still need to set up a forced redirect for non-SSL requests to be secure by default. This could also make sure search engines don’t see HTTP and HTTPS pages as different content, but I’ll work toward that another time, maybe when I finally get to rewriting this blog as a static-content site (e.g., Jekyll and GitHub Pages).

I’m hoping none of this will affect anyone reading blog posts here, but if you see anything looking unusual, drop me a line on Twitter.

Return of Netduino, .NET on small hardware

A little piece of magic wandered into my Twitter feed recently. Between the Windows IoT stuff I messed with this summer, controlling LEDs via Xamarin.Forms, and this awesome news, I’m bound to be learning the hardware side of things a little better.

That’s right, Netduino has returned; this time Wilderness Labs has taken the reins (with Bryan Costanich heading things up). Netduino is a hardware platform, similar to Arduino with lots of input and output options through a bunch of pins on the board, that allows interacting with it using .NET. Not only has Wilderness Labs resurrected Netduino, they have released three new boards: Netduino 3, Netduino 3 Ethernet, and Netduino 3 WiFi.

According to the Wilderness Labs Netduino docs, these new boards are as fast as ever, all running Cortex-M4 processors at 168MHz, and with more flash storage and a bump in RAM: the base Netduino 3 has 384KB of flash (matching the old Netduino 2 Plus), and the Netduino 3 Ethernet and Netduino 3 WiFi both have a bump to 1,408KB. If it wasn’t obvious, the Netduino 3 Ethernet board also offers a 10/100 Ethernet port, and the Netduino 3 WiFi has an 802.11b/g/n wi-fi adapter. So, they are as fast as ever and with more resources to do what you tell them.

I have been interested in Netduino since I first heard about it, though I didn’t buy one to play with until the release of the prior Netduino 2 Plus. All I had ever done with that system was blink the on-board LED. A few hours after I read that tweet, I was digging through my box-o’-electronics until I found it. This time, I decided I would do something more useful, or at least more fun.

Getting hardware rolling [again]

Since I wasn’t entirely sure what firmware was installed on my Netduino, I decided to install the latest from Wilderness Labs. I figured there was no sense in finding a bug that was fixed in the later firmware versions.

Unfortunately, every time I tried to flash the firmware on my MacBook, it would get stuck. After several unsuccessful attempts to debug the issue, I randomly ended up using a different USB cable. Everything flashed perfectly after that, and I tossed the defective USB cable. While it may not help with my faulty cable issue, Alex Corrado has since updated the error handling on the macOS firmware update tool, so you may have not have as much trouble debugging issues by the time you read this.

Getting an IDE rolling

What little code I wrote the last time I did Netduino development was probably on Visual Studio 2013. While the Netduino Discord channel looks like Netduino is quickly moving to Visual Studio 2017 and Visual Studio for Mac, it’s not quite 100 percent there yet. So, I busted out my older MacBook with Xamarin Studio. (I could have also installed Visual Studio 2015, but having spent so much time with 2017’s more self-contained installs makes me not want to return to the previous era.)

Since I was going the Xamarin Studio route, I added the Micro Framework add-in/extension as instructed. A quick restart of the IDE, and I was up and rolling, blinking the same LED I’d blinked a few years back.

What’s next?

I have played with a few sensors and LEDs already, and some more code-happy posts will be coming soon.

So far, I have a few random toys to play with: a water-resistant temperature sensor, a BME280 temperature/pressure/altitude sensor, and an ultrasonic range sensor

Even if the Netduino is overkill, I might start working on a small temperature-monitoring system feeding to Azure IoT Hub with an app front-end for our chicken coop. Or maybe a silly well-sensored aquaponics system. As much fun as blinking LEDs can be, what other semi-useful things should I be trying to make? Drop me a line on Twitter if you have any suggestions.

Cross-Platform Images in Xamarin.Forms Using SVGs

Screenshot from the demo app; code available via GitHub, showing the flexibility of SVGs.

For the last four months, I’ve been working on a fast-paced Xamarin.Forms project where almost every image used has been an SVG shared between both the iOS and the Android platform apps. And it has been glorious! If an early UI design needed a few pixels shaved or added to an image we were using, no new images were needed, let alone a handful of pixel-density variations on it. It was just the few lines of code or XAML to change the rendered size. (In fact, I’ve extended our use to include stretchable buttons by adding 9-slice SVG support.) With SVGs, you use one tiny XML file to render the resulting image at any size or for any screen density.

TL;DR

  1. Put SVGs in a PCL as an EmbeddedResource build action
  2. Use an SVG control (I recommend TwinTechsForms.NControl.SvgImageView, but there are other choices.)
  3. Add an SvgImageView to your C# or XAML UI the the right assembly and resource path

Without SVG Images

Images on iOS and Android are normally managed in slightly different ways regarding naming and location. For better or worse, Xamarin.Forms continues using these image conventions, making a detour from the focus on cross-platform sharing. On a normal iOS app, you want three sizes of every image with density-based names: someimage.png, [email protected], and [email protected] On Android, you generate the different-sized images with the same name, but place them in separate drawable folders: mdpi, hdpi, xhdpi, etc.

Typical Android images resource structure

Typical iOS images resource structure

While programs like Sketch have made generating these multiple images from a single vector file much simpler (and I’ll explain later why you will still need this), whenever you add a new one or change an existing one, that means remembering to put six or more images in their proper location. Wouldn’t it be nice if you just exported one file, put it in one location, and had that image available at any size and/or density at any time? This is where SVGs can greatly simplify things for you.

We are going to walk through using SVGs as embedded resources for this post, but you could certainly download SVGs as they are needed. Embedded resources, as the name suggests, are stored within the compiled assembly.

Bringing Your SVGs to Xamarin.Forms

To make your SVG resources easy to use in both Xamarin.Forms platform projects, we will embed them in a common portable class library (PCL). If your Xamarin.Forms app doesn’t use a PCL for code sharing, feel free to make a separate one just for SVG assets. If you are already using a PCL to share code between platform apps, you can simply put them in their own location within that library. You could also create a separate portable library for assets, depending on your organization preference.

Creating a portable class library (PCL) for your shared SVGs.

Once you have your target PCL project, you can start to further organize them however you want. (An additional benefit over Android drawables which must be all at the same directory level.) If we’re putting the SVGs in your Xamarin.Forms shared code, it might be best just to create another directory for them; you can name it whatever you like: Resources, Images, Assets, SVGs, whatever. With a destination set up, you can start adding your SVGs to the project however you prefer.

After adding an image to your project, though, you need to remember one important step. Switch the file’s “Build action” from “None” to “EmbeddedResource” by either the Properties pad or by right-clicking it. Don’t worry. You are bound to forget to do this a few times; the SVG loading code currently throws an exception if the resource stream comes back null.

Make an SVG an embedded resource.

With some SVGs in place, let’s get them showing up. For this, you have a few options, each can have their own trade-offs.

Xamarin.Forms SVG Controls

One of the first Xamarin.Forms SVG controls was SvgImage from GitHub user paulpatarinski. This SvgImage control was created prior to NGraphics offering really solid SVG support, so it uses a custom fork. You may be just fine using this library, but it you are already using NGraphics for something else, you will end up with two almost-identical libraries compiled into your app. Additionally, this version can choke on some SVG elements that others can handle.

With NGraphics’ SVG support vastly improved, while working on Xamarin.Forms projects at Twin Technologies I created a custom version of SvgImage that uses the standard NGraphics NuGet package directly. This variant, TwinTechsForms.SvgImage, is available as a NuGet package. In addition to updating NGraphics, I also added 9-slice SVG support to SvgImage control. This control does not offer Windows Phone or UWP support yet.

NControl.Controls also offers an SvgImage control using NGraphics. (NControl is a Xamarin.Forms control created as a wrapper around NGraphics for custom-drawn cross-platform controls, with NControl.Controls being sample implementations.)

While it isn’t derived from the NControl SvgImage control (yet!), I have also ported the 9-slice SVG implementation found in the TwinTechsForms.SvgImage control to an NControl version: TwinTechsForms.NControl.SvgImageView (also available on NuGet). This control does not offer Windows Phone or UWP support yet.

No matter which SVG control you pick, you’ll want to add the package to both your Xamarin.Forms PCL project(s) as well as all of your platform projects. For the rest of this post, the code is based on TwinTechsForms.NControl.SvgImageView, so the exact code might be different for other SVG control libraries.

Using TwinTechsForms.NControl.SvgImageView

There is some initialization required to make SvgImageView work, but it’s a simple line in the platform projects after Xamarin.Forms initializes (AppDelegate.cs for iOS, MainActivity.cs for Android).

Xamarin.Forms.Init();
SvgImageRenderer.Init();

NOTE: without this line, SvgImageView will silently fail to use the custom renderer. I hope to eliminate the need for it at some point, but it is still needed for now.

Once we have the platform renderer Init in place, we can start putting SvgImageView in our UI code/XAML.

new SvgImageView {
    SvgAssembly = typeof(App).GetTypeInfo().Assembly,
    SvgPath = "some.embedded.resource.path.svg",
    WidthRequest = 48,
    HeightRequest = 48,
}

The SvgAssembly field might look a little unusual, but that is how we point our control to the assembly where the embedded resource is actually found. SvgPath is the string you pulled from the file’s properties.

If you are doing your SvgImageViews in XAML, which you certainly do, you will have to get your SvgAssembly from somewhere. (It may be possible in raw XAML, but my XAML skills were not up to par.)

<controls:SvgImageView
    SvgAssembly="{Binding SvgAssembly}"
    SvgPath="SvgImageDemo.Resources.logo.svg"
    WidthRequest="75"
    HeightRequest="75" />

You can see SvgImageView XAML in action in the demo repo for this blog post. In that case, I used a view model with an Assembly property to bind to SvgImageView.SvgAssembly.

Now we can start getting our SVGs rendering on the screen.

Embedded Resource SVG Gotchas

While you are experimenting with SvgImageView/SvgImage control, you are bound to hit a few mistakes. (There are some mistakes that I make almost every single time.)

Forgetting the SvgAssembly property results in a null reference exception in most controls. If you forget it, this exception will bubble up from the SvgImageView control, so it isn’t immediately obvious what went wrong. In an internal version of our SvgImageView control, we ended up setting a static DefaultSvgAssembly property so that all SVGs could be assumed to come from one location. This saved us from even bothering to add the line.

If you set the SvgPath incorrectly, you’re going to have issues at runtime as well. In some controls, it is an exception. In some, it just doesn’t render anything. It’s definitely worth checking the path you set against the value in the Properties pad for the file you want to use.

Even when you get what would be the correct embedded resource path, it is incredibly easy to forget to flag the file itself as an embedded resource. Every time you add an SVG, you need to do this before you try to render it. This error will also either be a runtime exception or result in nothing being rendered. With as many times as I’ve made this mistake, don’t ever feel bad when you go debugging an issue only to find there isn’t an SVG where you are pointing for this very reason.

Shared SVG Limitations

Remember when I said you would still need to export your images into the various density sizes? That is where one of the limitations of using SVGs comes in. Platform assets like launcher icons still require the various explicit assets because they are handled by the system before your Xamarin code can be used.

Additionally, there are some arguments for custom images when rendering an image at tiny icon sizes (or a separate SVG optimized for that purpose). Not every SVG detail will be discernible at the smallest sizes you need. This isn’t necessarily a limited of SVGs as much as complex graphics in general.

NGraphics has made some great progress toward consuming almost any SVGs I throw at it, but that could be more a symptom of the simplicity of my graphics and the use of Sketch. There are definitely SVGs that can either blow up rendering at runtime or render in unusual ways. Sometimes it is as simple as removing extra SVG non-rendering element cruft that came along from your export. If you run into an SVG that is giving you trouble, you can try exporting them from a different vector graphics application that may result in simpler paths. If you have a background with rendering SVGs, I’m sure NGraphics could use your help adding support for more elements.

Even SVG elements that do render (in some controls), don’t always render as expected. On prime example of this is the text element. If you have a text element, it likely has a typeface defined for it. There may be a way to make this work, but it might require some extra setup. So far, the easiest way to make text work is to output the SVG text as a path instead of a text element. For example, Sketch can convert text to outline paths that will work great in for SVG use.

Converting text to outlines for SVG use in Sketch.

Parting Thoughts

There are definitely limitations to using SVGs, but they can still vastly simplify your image workflow. Adding SVG support to your pre-existing app can be done without breaking any of your current image use, so it is ideal for adding to existing projects without rewriting your UI code. If you happen to give one of the TwinTechsForms NuGet packages, I’d love to hear your thoughts. Should you run into any issues, don’t hesitate to send a GitHub issue my way. Feel free to send any feedback my way on Twitter or leave a comment here. If you have any thoughts for improvements, pull requests are always welcome (or file an issue).