Connect(); 2016

Volume 31 Number 12

[Xamarin Workbooks]

The (Interactive) Future of Technical Docs

By Craig Dunn

Once upon a time,printed technical books were the primary approach to learning new programming languages and SDKs. Today, you’ll find a myriad of content online, from product documentation to developer blogs, from Stack Overflow to GitHub, and from podcasts to YouTube—even Xamarin University online classes.

There can still be barriers to learning, though: Configuring the new IDE you want to start programming in, understanding the File | New Project wizard and all its options, typing or copying sample code into a new or existing project to try it out, and even navigating the resulting solution structure, can all be confusing for the uninitiated. Developers who’ve switched from Visual Basic to Eclipse to Xcode understand just how different these experiences can be.

Roslyn—the Microsoft open source .NET compiler service—­facilitates new experiences that mitigate these problems by removing the need for the IDE. Learning experiences, such as Gistlyn (bit.ly/2d00D7b) and the new online C# tutorial from Microsoft (bit.ly/28WyuvW), immerse the developer in documentation and code, without the overhead of solutions and projects. These new tools make learning simpler and more interactive.

Introducing Xamarin Workbooks

Xamarin Workbooks brings this interactive-documentation-­plus-live-coding concept to mobile and desktop application development. In conjunction with device simulators, Workbooks gives you the same immersive experience as the online tools I mentioned, but provides the added ability to learn and experiment with the entire native SDKs for Android, iOS, Mac and Windows Presentation Foundation (WPF):

  • Learning Xamarin Mobile app development becomes an interactive and exploratory process. Rather than just reading the docs, Workbooks lets you interactively code and test native mobile app features.
  • Exploring online APIs—including Microsoft Azure services—­can be done without the hassle of starting up a sample app and navigating through a maze of source files. Because you’re using the same tools your mobile apps are written with, working code can be copied from Workbooks into your Xamarin app projects.
  • Writing your own Workbooks is easy, whether testing out an idea or building your own courseware to teach others. Instead of creating your hundredth File | New Project to try something new, you get a faster, easier way to experiment. As an added bonus, you can interact with the UI in the simulator, and explore the visual tree in the inspector view.

Getting Started

What, exactly, is Workbooks? In short: It’s live, interactive documentation for mobile and desktop platforms. You can download the Workbooks app for Mac and Windows at bit.ly/2ejXBj8. For Android and iOS, you should have Xamarin and the platform SDKs and simulators installed on your system.

Workbooks files are essentially Markdown files with a YAML header; they contain formatted text and code-fenced C#. The file extension is “.workbook.” You can write a workbook with any text editor, but the Xamarin Workbooks app includes the ability to create and edit workbooks, so you don’t really need to learn the underlying format. Here’s some sample Markdown source:

---
uti: com.xamarin.workbook
platform: iOS
---
# My First Workbook
Simple C# assignment will render the resulting object as a string.
```csharp
var greeting = "Hello, MSDN"
```

Figure 1 shows the resulting workbook before and after execution.

MyFirst.workbook Before and After Execution
Figure 1 MyFirst.workbook Before and After Execution

Executable code cells have a grey background and utilize the same editing experience as Visual Studio Code. Features like syntax highlighting, code completion, compilation errors and keyboard shortcuts are all supported.

When you click inside a code cell to give it focus, a set of action buttons appears below it (as shown in Figure 1). Press the Play button (arrow inside circle, on the far left) to execute that code cell (and any preceding code). You can also run the entire workbook at once from the Run menu.

Once the code has executed, a result cell is displayed below the code cell. You can edit any part of the code cell, to change how it runs or to experiment with the API, and press Play to run it again. (And again. This is how developers learn with Workbooks—by reading the documentation, and running and modifying the example code as they go.)

The result cell contains a representation of the last object reference in the code cell. By default, the object’s string representation is used, but Workbooks supports a number of additional visualizers to help you explore the results. Use the small menu next to the result to choose from the available visualizations, including:

C#: A string escaped for C# (for example, new lines encoded as “\n”).

Plain Text: An unescaped string value (for example, new lines are rendered as multi-line text).

Object Members: Renders a complete list of the object’s properties in a table. Large, cyclic object graphs are evaluated on demand, so they don’t slow down your coding, but are available to be explored if required, just like with a runtime debugger.

Enumerable: Automatically expands a collection so you can explore each item. Only the first 10 elements are initially displayed, but you can explore more by clicking the Continue Enumerating button.

Color: A small swatch of color is displayed, along with Hex or RGB representations of its value.

Location: Objects that represent a latitude/longitude location are shown on a map (Mac only).

Image: Valid image view classes can show the image inline in the workbook.

Exception: Highlights exception messages in the result cell.

Html: Workbooks authors can use the AsHtml method in their code­ cells to have the result cell render a string as HTML.

Figure 2 shows the Visualizers Workbook, including examples of some of these options.

Visualization Options
Figure 2 Visualization Options

So far you’ve just seen Workbooks displaying their results inline, but they’re even more interesting when exploring native mobile APIs with Xamarin via mobile device simulators.

Learning Xamarin with Workbooks

Once you’re comfortable running code cells and interpreting the results, you can visit developer.xamarin.com/workbooks and download Workbooks to learn Android, iOS and Xamarin.Forms. The native platform APIs are available in Workbooks, for tasks as simple as adding a label to the screen, up to rendering 3D content that responds to touch.

When you create or open an iOS, Android or Xamarin.Forms workbook, a mobile device simulator will start up (Mac and Windows Presentation Foundation [WPF] workbooks just start an empty window). These external simulators (or windows) run an agent app that communicates with the workbook—you’ll see a status message when the agent is being started. Once the agent is running, Xamarin Workbooks is ready to be explored.

As you read through and run each code cell, the app in the simulator changes to reflect each new piece of code. If you’re curious about how something works, edit the code and run it again. Figure 3 shows a simple iOS UITableView example, and Figure 4 shows it running in the simulator.

Figure 3 XamariniOS.workbook

---
uti: com.xamarin.workbook
platform: iOS
packages:
- id: Newtonsoft.Json
  version: 9.0.1
---
# iOS UITableView
This example uses **Json.NET** and `WebClient` to download a file *monkeydata.json* that is used to bind to the iOS UITableView.
```csharp
#r "Newtonsoft.Json"
#load "json_monkey.csx"
```
To add a UITableView control to the screen, instantiate an instance, set the bounds, and add to the `RootViewController`. You can experiment with changing the `Frame`.
```csharp
var tableView = new UITableView();
tableView.Frame = UIScreen.MainScreen.Bounds;
RootViewController.View.AddSubview(tableView);
```
Wiring up a data source (like a generic list of `Monkey` objects) to a table requires a `UITableViewSource`. This class converts the data into `UITableViewCell` classes to be rendered.
```csharp
public class MySource : UITableViewSource
{
  string identifier = "mycell";
  public List<Monkey> Data {get;set;} = new List<Monkey>(); // C# 6
  public override nint RowsInSection (UITableView tableview, nint section)
  {
    return Data.Count;
  }
  public override UITableViewCell GetCell (UITableView tableView,
    NSIndexPath indexPath)
  {
    // First, get or create a cell
    UITableViewCell cell = tableView.DequeueReusableCell (identifier);
    if (cell == null)
    { cell = new UITableViewCell (UITableViewCellStyle.Subtitle, identifier); }
    // Then, get the data and set the UI
    cell.TextLabel.Text = Data[indexPath.Row].Name;
    cell.DetailTextLabel.Text = Data[indexPath.Row].Location;
    return cell;
  }
}
```
To display the data in the table, create the source object, assign the Monkey object list, then assign it to the table
```csharp
var source = new MySource(); // Create the class
source.Data = monkeys;       // Assign the list of strings
tableView.Source = source;   // Give it to the table view
tableView.ReloadData();      // and show on the screen
```

Workbooks and iOS Simulator
Figure 4 Workbooks and iOS Simulator

Workbooks can also display an exploded view of the UI hierarchy to explore. You can select items in the simulator, the 3D rendering or the visual tree list, and view their properties in a pad. To access this on the Mac, select View | Visual Inspector. On Windows the pads are docked, ready to access at any time. To switch back to the code and documentation, use the View | Workbook menu item.

Exploring APIs

Workbooks is also great for exploring other APIs, such as those provided by NuGet packages or REST endpoints. An example that combines both is a workbook that connects to Azure EasyTables, using the free tryappservice.azure.com back end.

The complete workbook source is shown in Figure 5, including the required NuGet packages; and the complete source code to save and retrieve data from an Azure EasyTable is shown running in Figure 6.

Figure 5 Azure-TryAppService.workbook

---
uti: com.xamarin.workbook
platform: WPF
packages:
- id: Microsoft.Bcl
  version: 1.1.10
- id: Newtonsoft.Json
  version: 9.0.1
- id: Microsoft.Net.Http
  version: 2.2.29
- id: Microsoft.Azure.Mobile.Client
  version: 3.0.1
---
# Azure TryAppService
Two NuGets - **Microsoft.Azure.Mobile.Client** & Newtonsoft.Json - have been added:
```csharp
#r "Newtonsoft.Json"
#r "Microsoft.WindowsAzure.Mobile"
#r "Microsoft.WindowsAzure.Mobile.Ext"
```
This `TodoItem` class matches the one configured in the TryAppService back end.
```csharp
using Newtonsoft.Json;
using Microsoft.WindowsAzure.MobileServices;
public class TodoItem
{
  [JsonProperty(PropertyName = "id")]
  public string ID {get;set;}
  [JsonProperty(PropertyName = "text")]
  public string Name {get;set;}
  [JsonProperty(PropertyName = "complete")]
  public bool Done {get;set;}
  [Version]
  public string Version { get; set; }
  public override string ToString() {
    return $"{Name} is " + (Done?"done":"not done");
  }
}
```
Sign up at [tryappservice.azure.com](https://tryappservice.azure.com/ "Try Azure for free!") **Mobile App > TodoList**. Replace the URL with *your* temporary, generated endpoint URL:
```csharp
var mobileService = new MobileServiceClient (
  "https://da0cfa57-0ee0-4-231-b9ee.azurewebsites.net/");
  // Replace this with your own
var table = mobileService.GetTable<TodoItem> ();
```
The following code creates a new `TodoItem` class, inserts it into the table on the server, and retrieves the list from the server:
```csharp
var rememberTo = new TodoItem {Name="buy apples"};
await table.InsertAsync (rememberTo);
List<TodoItem> todos = await table.Take (10).ToListAsync ();
```

Using Azure TryAppService Interactively
Figure 6 Using Azure TryAppService Interactively

Of course, there’s a lot more to Azure—this example just begins to demonstrate how Workbooks can be applied to the idea of teaching an API.

Writing Your Own Workbooks

Although you can write workbooks in Markdown, the easiest way to create your own is within the Workbooks app itself. Choose the File | New menu item, then choose a platform: iOS and Android can be created on both macOS and Windows. Mac and WPF workbooks can be created only on macOS or Windows, respectively.

Workbooks consists of three types of elements: text cells, code cells and result cells. A brand-new workbook contains a single code cell, where you can immediately type and execute C# code.

Cells can be added and deleted using the action buttons that appear below a cell when it has focus. There are three buttons (visible in Figure 1):

  • Plus (+) – Add a new code cell.
  • Double Quote (") – Add a new text cell.
  • Delete (x) – Delete the preceding cell.

All the code cells in a workbook run in the same context, so variables and classes created in one code cell are available in subsequent code cells.

Text can be formatted by selecting it and using the formatting bar shown in Figure 7. Options include bold, italic, adding links, and code format, as well as bulleted lists, numbered lists, and blockquotes. There are also six heading levels and the ability to insert images or a horizontal rule.

Formatting Text
Figure 7 Formatting Text

Code cells support C# keyword highlighting and both member and signature/override auto-completion. Errors are indicated by a red underline, and the error message is displayed when you hover over it.

  Each platform has its own mechanism for accessing the UI, as follows:

Android: Building workbooks that utilize the simulator means you need a way to reference the UI from code cells. For Android, use the following code to get a reference to the Activity being used by the simulator:

var mainActivity = StartedActivities.First();
var label = new Android.Widget.TextView(mainActivity) {
  Text = "Hello, Workbooks",
  TextSize = 36
};
mainActivity.SetContentView(label);

iOS: iOS workbooks expose the RootViewController of the simulator so that you can build up the UI by adding subviews, as shown here:

var label = new UIKit.UILabel(new CGRect(10,10,300,50)) {
  Text = "Hello, Workbooks",
  Font = UIFont.SystemFontOfSize(36)
};
RootViewController.Add(label);

WPF: Adding controls to the app window in WPF workbooks can be accomplished by setting the Content property on System.Windows.Appli­cation.Current.MainWindow, for example:

var label = new System.Windows.Controls.Label {
  Text = "Hello, Workbooks",
  FontSize = 36
};
System.Windows.Application.Current.MainWindow.
  Content = label;

Workbooks also includes features to help you create more-sophisticated code scenarios, so you can:

Reference additional namespaces: By default, only a limited set of namespaces are available in each workbook. Some, such as System.Xml, require a using clause at the start of the code cell before they’re used (just like in a regular C# file).

Add NuGet packages: Use the File | Add Package menu item to add NuGet packages to a workbook, and ensure that the assemblies are referenced using the following syntax:

#r "Microsoft.WindowsAzure.Mobile"

Assemblies referenced this way still require the appropriate using statement in a code cell (as shown in Figure 6).

Include additional code:More-complex examples might require lots of code, which would only clutter the workbook if it’s displayed inline. External code files can be referenced by a workbook with the following syntax:

#load "my-extra-code.csx"

Use external files to create supporting classes, UI elements, Model and ViewModel classes or other objects that are required for the workbook to function but aren’t necessary to the documentation (and are unlikely to need modification by the user). The workbook in Figure 3 shows where some data-setup code is added with an external file, to keep the instructions easy-to-read.

Get help: Type help as the last line in any code cell to quickly view the convenience methods available in the workbook.

Wrapping Up

Xamarin Workbooks is now the fastest way to learn mobile application development. You can learn more about the native mobile platforms and explore online APIs. It’s also easy to create your own custom workbooks for your blog, training or anything else. Workbooks can include NuGet packages and can reference additional namespaces, as well as the entire Android, iOS, macOS and WPF SDKs.

Visit developer.xamarin.com/workbooks to get started. Xamarin is freely available as part of Visual Studio Community Edition (and also on the Mac), and the Workbooks app is free to download and use.


Craig Dunn is the program manager for Xamarin documentation at Microsoft. Find him on Twitter: @conceptdev or via LinkedIn at linkedin.com/in/conceptdev.

Thanks to the following Microsoft technical experts for reviewing this article: Aaron Bockover and David Britch
David Britch works in the Xamarin documentation group at Microsoft. He has authored a range of software development publications including books, guidance documentation, reference implementations, whitepapers, videos, and instructor led training courses.

Aaron Bockover leads the Xamarin Workbooks & Inspector team at Microsoft. He has been a .NET and Mono fanatic since the inception of Mono and is passionate about enabling others to get the most out of C# & .NET - and the myriad of platforms it targets today.


Discuss this article in the MSDN Magazine forum