Monthly Archives: November 2017

Getting Started With iOS for a C# Programmer – Part Two – Running the Simulator

The purpose of this post is to take the code that we created here and run it in the simulator.

Leaving the Playground

To a .Net programmer, this seems like an alien concept but, depending on the mode that you run Xcode in, it results in a different IDE. If, instead of selecting Plaground, we select “Create an Xcode Project”, the whole app experience changes:

There are a lot more options available now; but let’s stick to the most basic:

The created Single View App should look like this in structure:

The target of this post is simply to take the few lines of code that we wrote in part one, and have them run on a simulator.

The first thing it does is launch the ViewController, so let’s take the code that we created in the first part, and add it directly to the ViewController; the new controller will look like this:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        let x = UILabel()
        x.text = "test"
        x.textColor = UIColor.black
        x.frame = CGRect(x: 5, y: 5, width: 80, height: 20)
        
        let v = UIView()
        v.frame = CGRect(x: 0, y: 0, width: 100, height: 100);
        v.backgroundColor = UIColor.white
        v.addSubview(x)
        
        self.view = v
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

There are a couple of changes – firstly, we no longer reference Playground, and secondly, the active view is set here:

self.view = v

When we run this, we get the simulator appearing, and the text appears (as we might expect):

Short Walks – Using JoinableTaskFactory

While attending DDD North this year, I attended a talk on avoiding deadlocks in asynchronous programming. During this talk, I was introduced to the JoinableTaskFactory.

This became strangely useful very quickly, when I encountered a problem similar to that described here. There are a couple of solutions to this question, but the least code churn is to simply make the code synchronous; however, if you do that by simply adding

.GetAwaiter().GetResult()

to the end of the async calls, you’re very likely to result in a deadlock.

One possible solution is to wrap the call using the JoinableTaskFactory, in the following way:

var jtf = new JoinableTaskFactory(new JoinableTaskContext());
var result = jtf.Run<DataResult>(() => _myClass.GetDataAsync());

This allows the task to return on the same synchronisation context without causing a deadlock.

References

https://docs.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.threading.joinabletaskfactory

https://stackoverflow.com/questions/33913836/how-to-render-a-partial-view-asynchronously

Xamarin Forms Woes

Xamarin Forms is one of those technologies that I keep meaning to play with… but then don’t. Anyway, this is the story of the day that I first did… the intention was to spend a Sunday afternoon getting a quick prototype of a Xamarin Forms app running… but instead, I encountered error after error.

In the end,all I ended up producing was this post!

The first error after creating a new app:

This gave me the impression that I might have the wrong version of Android; so off I went to install the latest JDK; from here.

Thus began a process that took hours to complete…

Android SDK

Launch Android SDK Manager and install the latest (or a later) version:

Amazingly, this did seem to fix (or at least, change) the error.

Next Error:

The next problem was a build error from the Android project:


Error: No resource found that matches the given name: attr 'colorAccent'

There’s two things that were necessary here; the first was to make sure that this package was installed:

Install-Package Crosslight.Xamarin.Android.Support.v7.AppCompat

And now we’re onto the next problem…

Suddenly, it decided there was an issue with some of the resources in the file ‘Tabbar.axml’:

Errors:
1>C:\Code\MyApp\MyApp.Android\Resources\layout\Tabbar.axml : error APT0000: 1: error: No resource identifier found for attribute 'tabIndicatorColor' in package 'com.companyname.WizardGame'
1>C:\Code\MyApp\MyApp.Android\Resources\layout\Tabbar.axml : error APT0000: 1: error: No resource identifier found for attribute 'tabGravity' in package 'com.companyname.WizardGame'
1>C:\Code\MyApp\MyApp.Android\Resources\layout\Tabbar.axml : error APT0000: 1: error: No resource identifier found for attribute 'tabMode' in package 'com.companyname.WizardGame'

Taking inspiration from my Spectrum programming days, and having no clue what the hell was going on at this stage, I just deleted these lines… and got a different error:

error CS0012: The type 'AppCompatActivity' is defined in an assembly that is not referenced. You must add a reference to assembly 'Xamarin.Android.Support.v7.AppCompat, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

This didn’t make much sense, but while I was messing around in the Package Manager screen, I decided to update the Xamarin.Forms package; for some reason, the latest version seems to be (numerically) older that the older one:

Giddy with the thrill of the update working without a new, spurious error, I updated everything! This required VS to be restarted at least once.

At this stage, the project started compiling… so before Xamarin regained its footing and thought of a new error, I added back in the code I’d removed:

    app:tabIndicatorColor="@android:color/white"
    app:tabGravity="fill"
    app:tabMode="fixed" />

Now it compiles!… But won’t deploy to Android

Xamarin was catching up with me – a new error now appeared:


1>Please select a valid device before running the application.

After a little help from a well-known search engine, I selected the emulation manager:

If you find yourself in this situation, then don’t keep clicking (despite no feedback at all, the manager does open in the background)!

Select one of the devices and start it:

And it now deploys… I didn’t get anything done, but I did manage to get Xamarin running on an Android emulator… so that’s something.

Getting Started With iOS for a C# Programmer – Part One

I’ve never programmed with XCode before; I’ve never even owned a Mac, so since I now have access to one, I thought I’d see if I could create a basic game. In order to motivate me to complete this, I thought I’d document my efforts, and try to put at least one post up every two weeks. As I knew absolutely nothing about this to begin with, I’m going to start from there.

The Basics

The first thing that you’ll need is an Apple account. You can use one that you might have set-up for your iPhone; otherwise, you can set one up here. It’s free to register, and there’s no need to sign up for a developer account immediately; although, should you wish to, it will cost you $99.

The next stage is to install Xcode; which can be found here. Xcode is the IDE, so it’s the equivalent of Visual Studio – it is not a language in its own right. The language we’re dealing with here is called Swift.

Your first program

When you initially run Xcode, you’ll be faced with a screen like this:

Since we don’t know what we’re doing, let’s select “Get started with a playground”:

And let’s select a Blank playground.

We then get an (almost) blank text editor:

The examples given seem to introduce a new level of complexity by including controllers; however, this is the simplest example of a working “Hello, world” program that I could come up with:

import UIKit
import PlaygroundSupport

let x = UILabel()
x.text = "test"
x.textColor = UIColor.black
x.frame = CGRect(x: 5, y: 5, width: 80, height: 20)

let v = UIView()
v.frame = CGRect(x: 0, y: 0, width: 100, height: 100);
v.backgroundColor = UIColor.white
v.addSubview(x)

PlaygroundPage.current.liveView = v

To break down that code

import UIKit
import PlaygroundSupport

Playground support is the library that allows you to visualise the preview of what the app will look like when it’s eventually on the device.

let x = UILabel()
x.text = "test"
x.textColor = UIColor.black
x.frame = CGRect(x: 5, y: 5, width: 80, height: 20)

The UILabel object has to live within a frame; otherwise it will not appear on the screen. The default colour is black, but as I’ve specified the colour of the view, I thought it made sense to specify all colours.

let v = UIView()
v.frame = CGRect(x: 0, y: 0, width: 100, height: 100);
v.backgroundColor = UIColor.white
v.addSubview(x)

PlaygroundPage.current.liveView = v

This sets up the view; which seems to map to a form in WinForms, or a view in WPF. Again, the view needs a frame; and, in this case, it does need a colour (as the default is black).

The x, y, height and width variables are just guesses – so these may need changing later. Finally, we set the current Live View on the playground so that it knows which view to display.

Running the Code

If you run that initially, you’ll see that, whilst it compiles, nothing actually happens; the trick is here:

Summary and Target

Once you’ve established the basic syntax, the code suddenly seems much more familiar. There are some things that appear foreign to the eyes of a .Net developer; for example, “let” establishes a constant. In the case that it’s used here, it’s a constant pointer.

The target game that I have in mind is a very basic space invaders style game. I’ve already written a similar one in WinJS for the Windows Store so this is kind of a coding kata for me.

As a very loose plan, I intend to do the following:

Step 2: How does this code run on a simulator and on a device?
Step 3: Make an object move across the screen
Step 4: Allow control of said object
Step 5: Collision
Step 6: Graphics
Step 7: Score

Some of these steps may be spread over more than one post – it depends how hard they end up being.

Web API Routing – The Basics

Working with API projects, it’s easy to miss some key rules about the routing. This post is basically the result of some that I missed, and subsequent the investigation. It covers some very basic routing rules, and it certainly not intended to be an exhaustive guide.

.Net Framework

Starting with a .Net Framework Web API, let’s create a new web app:

And add a new controller:

Here’s the code for the controller; as you will see, it’s massively complex, but the good news is that you only need to pay attention to the name of the action, and the code inside it:

public class TestController : ApiController
{
    [HttpGet]
    public IHttpActionResult TestAction()
    {
        return Ok("TestAction Performed");
    }
}

Let’s run the project and navigate to the URL:

How did I know that was the URL? It’s magic, and you can buy some of that magic by sending a cheque for the low, low price of $25 to the address shown at the bottom of the screen.

Actually, it’s defined in WebApiConfig.cs:

Parameters

Where there is more than a single function, one surprising (to me) feature is that the parameters that it accepts is more important to the routing than the name of the controller. Here’s a second action with a parameter:

[HttpGet]
public IHttpActionResult TestAction2(string test)
{
    return Ok("TestAction2 Performed");
}

… and here’s it working:

However, should I not give it the parameter that it craves, it hides away, and instead, we get the first function that’s no too fussy about parameters:

It doesn’t even matter whether I just put some drivel as the controller name; the first criteria is the parameter:

This is because, according to this it follows these criteria:

The default implementation is provided by the ApiControllerActionSelector class. To select an action, it looks at the following:
• The HTTP method of the request.
• The “{action}” placeholder in the route template, if present.
• The parameters of the actions on the controller.

So, if we add the {action} placeholder, that ensures that it uses the correct method:

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services
 
    // Web API routes
    config.MapHttpAttributeRoutes();
 
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        //routeTemplate: "api/{controller}/{id}",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

Otherwise, we get a best guess based on the parameters.

.Net Core Web API

The rules have changed since switching to .Net Core; WebApiConfig has gone and, in its place, it a localised routing system.

Here, you tell the class how to handle routing; for example, the following:

[Route("api/[controller]")]

Will result anything decorated with HttpGet being called when the controller is called. The parameters must be explicitly decorated; so passing no parameters would look like this:

[HttpGet]
public string OneTest()
{
    return "TestOne";
}

Whereas, a single parameter would look like this:

[HttpGet("{id}")]
public string aaa(int id)
{
    return "value aaa";
}

If you duplicate the signatures then they are not found. As with the framework version, you can simply tell it to look to the action name that you give it:

[Route("api/[controller]/[action]")]
public class TestController : Controller
{
    [HttpGet]
    public IEnumerable<string> TestActionOne()
    {
        return new string[] { "one value1", "value2" };
    }
 
    [HttpGet]
    public string TestActionTwo()
    {
        return "two value";
    }

But, again, it pays no attention to parameters until you decorate it correctly.

References

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing