Note: this is a placeholder article so I can create a bit.ly link for an upcoming MSDN Magazine article that will point to the real documentation for this feature. Those docs are currently in progress and will likely be available by the time the article is published. But we have to finish the galley proof for the print magazine now, hence the placeholder!

Until just recently, here in the summer of 2015, the Visual Studio Online build system didn't have support for cross-platform apps like those created with Xamarin. That support has now been added.

When you're on VSO's Build tab for a project, you'll see "Build definitions" and "XAML definitions." The latter, XAML definitions, are those that worked with the previous build system that does not have cross-platform support.

VSO-Build1

If you create a new definition with the big green +, you'll be presented with the new list of templates:

VSO-Build2

Clearly you can see the options for building Xamarin.Android and Xamarin.iOS projects, along with the Xcode option for building a straight iOS native app.

What about Xamarin for Windows? I'm told you can use the Visual Studio template for that, but I haven't tried this myself. In any case, when you use one of the Xamarin templates you'll be required to enter your Xamarin credentials to activate the necessary platform licenses:

VSO-Build3

Anyway, that's all I'll say for now because I haven't tried out all of this myself. Again, proper documentation will be appearing soon on MSDN for all the details.

 


This blog post is an addendum to the article, Build a Xamarin App with Authentication and Offline Support, to be published in MSDN Magazine, September 2015. I'll update this post with a link once the article is available. Part 1, Cloud-Connected Mobile Apps – Create a Web Service with Azure Web Apps and WebJobs, which discusses the backend of the project, is available now.

As promised, there are a few points of interest in the app that have not been discussed previously.

First, we implemented some niceties for displaying items both in the home page list and on the item page:

  • When processing data from the backend in DataModel.ProcessItems, the app generates a description from the first 100 characters of the body. Because that body is typically HTML and the description is plain text, we use a one-line regular expression replacement to do a quick strip of the tags (this is the private function StripHTML in sync.cs):
Regex.Replace(source, "<[^>]*>", string.Empty).Replace("n", " ");
  • Similarly, we noticed during testing that item titles can have smart quotes in them, but the text field in the ListView control will display their escape sequence instead. So another little one-liner (CleanEscapes in sync.cs) takes care of this:
source.Replace("&#39;", """).Replace("&quot;", """);
  • The item page displays the name of the item’s source (such as StackOverflow or Twitter), and to make it easy to go to that source directly the ItemPage constructor makes it a hyperlink with the following code:
this.ProviderLabel.GestureRecognizers.Add(new TapGestureRecognizer
{
    Command = new Command (() =>
    {
        Device.OpenUri(new System.Uri(viewModel.Url));
    })
});
  • It’s also very likely that the item’s HTML displayed in the ItemPage’s WebView will contain hyperlinks. Left to themselves, these hyperlinks will cause navigation within the WebView, but because there are no navigation controls the user wouldn’t be able to return to the item itself. To prevent this, the following code redirects navigations within the WebView to the default browser. The trick (mentioned in Altostratus Extra #1) is that the exact behavior of the WebView varies by platform: on iOS and Windows Phone, a Navigating event will be raised when the webview is first loaded with content from the app, whereas on Android you get the event only for navigations within the WebView once it’s loaded. We thus use Device.OnPlatform to initialize a flag that says whether to ignore the first event:
private Boolean navigateToBrowser = Device.OnPlatform<Boolean>(false, true, false); 

// ...

wv.Navigating += (Object sender, WebNavigatingEventArgs e) =>
{
    if (navigateToBrowser)
    {
       Device.OpenUri(new System.Uri(e.Url));
       e.Cancel = true;
    }

    navigateToBrowser = true;
};

And second, although we wanted a change of configuration to trigger a sync with the backend, we obviously don’t want to do this with every UI activity in the configuration page. Instead, a sync should only be triggered if the user actually changes something in the configuration when they return to the home page.

To implement this, the UserPreferences class in the data model, which matches the data exchanged with the backend, supports cloning an instance (its Clone method) and comparing to another instance (its IsEqual method). The Configuration page uses these within its OnAppearing and OnDisappearing events to have the data model refresh itself if the user made changes when they return to the home page. This way, the user could toggle categories, change the conversation limit, and even log in and log off again, but if ultimately the user returns to the home page with exactly the same configuration, nothing needs to happen in the data model or the home page UI.


This blog post is an addendum to the article, Build a Xamarin App with Authentication and Offline Support, to be published in MSDN Magazine, September 2015. I’ll update this post with a link once the article is available. Part 1, Cloud-Connected Mobile Apps – Create a Web Service with Azure Web Apps and WebJobs, which discusses the backend of the project, is available now.

The OAuth credential flow in Altostratus is as follows, using Facebook as an example. Once the user is

  1. The mobile client app displays a web browser control and navigates to a known URL on the backend.
  2. The backend redirects to the Facebook sign-in page where the user signs in with his or her Facebook credentials.
  3. The backend does sends requests to Facebook to retrieve an access token.
  4. The client app redirects the browser back to the backend’s endpoint. The redirect URL includes the access token in the fragment hash.
  5. The client app has been waiting for the redirect. At this point, it parses the access token from the URL fragment.
  6. If the user is not yet registered with the backend, the client app sends a registration request to the backend. The backend creates a database entry for the user and issues a second access token. This step only happens on the first login.
  7. Once the user is registered, the client app includes the access token to make authenticated requests.

Put graphically:

AltoStratus_OAuth_Flow


This blog post is an addendum to the article, Build a Xamarin App with Authentication and Offline Support, to be published in MSDN Magazine, September 2015. I'll update this post with a link once the article is available. Part 1, Cloud-Connected Mobile Apps – Create a Web Service with Azure Web Apps and WebJobs, which discusses the backend of the project, is available now.

To summarize from the article: Xamarin.Forms is a framework that lets you use a single code base to implement apps with UI on multiple target platforms. However, as written in Part 2, "shared code doesn’t much reduce the effort needed to thoroughly test the app on each target platform: that part of your process will take about as long as it would if you wrote each app natively. Also, because Xamarin.Forms is quite new [it first came out in May 2014], you may find platform-specific bugs or other behaviors that you'll need to handle in your code."

That particular statement comes from direct experience! Here are the behaviors we encountered with Altostratus and had to manage in the client app code (http://aka.ms/altostratusproject, in the MobileClient project):

  • The Xamarin.Forms ListView control supports grouping, but not invocation of group headers as is supported on some individual platforms. We would have liked to enable this feature in the app, but chose not to until Xamarin.Forms makes it work.
  • ListView headers appear on iOS 7 but don’t appear on iOS 8. This is a known bug in Xamarin.Forms.
  • On iOS and Windows Phone, the OnAppearing and OnDisappearing events for page navigations happen in the expected order: the originating page receives an OnDisappearing before the target page receives an OnAppearing. There’s a significant Xamarin.Forms bug on Android (and here's a duplicate bug) that causes the target’s OnAppearing to fire first. For this reason it’s necessary in the app's Configuration page to update the page’s overall changed status with every UI activity, rather than just check it once within OnDisappearing. This clearly causes a lot of extra churn.
  • On all platforms, setting the Minimum property of a Slider control (as used on the Configuration page) will throw an exception unless Maximum is already set to a higher value. This makes it difficult to set the values through data binding, because the order in which XAML binding statements are processed is indeterminate. For this reason, these properties are set in code rather than through data binding. See https://bugzilla.xamarin.com/show_bug.cgi?id=21181 and https://bugzilla.xamarin.com/show_bug.cgi?id=23665.
  • Data binding the items in a drop-down listbox is not supported at the time of writing.
  • The Xamarin.Forms WebView control is written to fire a Navigating event when the user attempts to navigate a link within the WebView. In the mobile client, we capture this event to specifically disallow navigation directly within the control and redirect the navigation to the default browser, see the code in Altostratus Extra #3. (The code for this is in the ItemPage constructor in ItemPage.xaml.cs.) However, on iOS and Windows Phone 8.1, but not Android, the Navigating event is also raised when the WebView is initialized from local content. This means that on those platforms we want to ignore the first Navigating event, whereas on Android we want to pay attention to all of them. So we just set a flag (navigateToBrowser) within the ItemPage constructor to control whether we delegate a navigation to the browser.

 

The lesson to be learned here is that when platform technologies always have their bugs, especially new ones but often mature ones as well. If something you think should be happening isn't, or you encounter some other behavior that seems odd and especially those that are inconsistent between operating systems, check into the applicable bug database like bugzilla.xamarin.com, or check on the applicable forums. It'll save you plenty of frustration. :)


We just published Part 1 of a two-part series in MSDN Magazine that covers the cloud-connected mobile app project I worked on earlier this year, which we called “Altostratus” (the name of an interesting cloud).

Part 1 is entitled “Cloud-Connected Mobile Apps – Create a Web Service with Azure Web Apps and WebJobs”, and is on https://msdn.microsoft.com/en-us/magazine/mt185572. I didn’t write much of this first article, personally, as it covers the backend part of the project and I worked primarily on the client.

The Xamarin client is the focus of Part 2 that will be published in early September. In advance of that, you’ll see a couple posts here with some extra material that didn’t fit into the ~5000 words of the article. I’ll be making those posts shortly because we want to make sure the URLs are accurate before going to print. :)

The code for both the backend and the client are available now via https://aka.ms/altostratusproject (which goes to GitHub). It is an open project, so if you see anything to improve, we’re happy to accept contributions.

Enjoy


And now for something completely different, and just for fun.

My son and I have been enjoying Minecraft since last fall, working first with the Pocket Edition and mostly with the PC version that supports creating circuitry with the Redstone element. Between my son and I, he’s more of a builder and I’m the one that more enjoys mining.

In one of my worlds,* which I’m just playing by myself, I’ve been working a lot with enchantments for which you need a variety of materials like Lapis Lazuli (necessary to do enchanting) and the quite rare Diamonds (used to make the best armor, tools, and weapons). This has led me to do some systematic mining deep underground where these materials are best found. Because I was specifically looking for diamonds, I concentrated on mining at levels 5-12 (see the Ore page for distribution statistics), where you’ll also find lots of other good stuff too.

This kind of mining is best done systematically. Here’s how I went about it:

  1. Standing on level 11, I circumscribed a 50×50 square tunnel, 2 blocks high (you could do any dimensions), periodically dropping torches on the outer side of the walls for light.
  2. Level 11 is recommended because lava lakes are generated at this same level, so you’ll always come out on the edge of one rather than below one where it’ll drop on you and cook you rather quickly. (Always carry a bucket of water in case you get set on fire, and it’s also handy to dump on top of lava to make obsidian, which is an effective way to remove lava and mine obsidian at the same time.(
  3. I then mines tunnels in one direction all along the square, going every other block. This means that I end up with a bunch of parallel tunnels with a one block wall in between. This accounts for the fact that ores nearly always come in groups of 3 or more blocks, so you don’t have to mine out every last bit to find the ores. You will occasionally miss a single block of something like diamond, but they seldom generate that way.
  4. For the first tunnel near an edge, I don’t bother dropping torches but punch a hole in the wall about every 6 blocks to let light in from the adjacent tunnel. This is pretty sufficient for keeping monsters from generating, though they do show up every now and then. (But they’re in tunnels so very easy to handle.)
  5. I then light the next tunnel (the third) the same way I lit the first. In other words, odd tunnels get light, even tunnels get holes. This way I save on torches.
  6. When I encounter ore, I typically mine the whole thing out, but sometimes leave stuff on lower levels for the next set of tunnels.
  7. Once all the level 11 tunnels were done, I made a hole in each corner for ladders going down to level 8–which allows for a two-block high tunnel with one block for the ceiling.
  8. I then circumscribed the same 50×50 edge tunnels and repeated the parallel tunneling. At level 8 though, you have to listen for lava sources. When you do, be careful as you mine in case lava flows out. However, if you start at level 11, you’ll know where most of these are. When I encounter a lava lake at level 11 I’ll dump water on it to turn it to obsidian and mine a bunch of it out. As lava is exposed at level 10, I’ll water it down too. This reduces the risk of getting cooked, and makes it far less likely to encounter flowing lava in the level 8 tunnels.
  9. Finally, I did the same thing again down to level 5, which is the lowest you can go without encountering bedrock obstacles.

I was quite pleased with everything I was able to extract, especially as I used a pickaxe with the Fortune III enchantment when mining lapis, diamond, coal, and redstone to increase the yield. What I found interesting, though, is that the return on mining at level 5 wasn’t nearly as good as levels 8 and 11 as these numbers illustrate

Coal Iron Gold Diamond Redstone Lapis
Levels 8-12 654 243 38 74 1,637 78
Level 5-6 150 83 4 11 254 0
Totals 804 326 42 85 1,891 78
% Level 8-12 81% 75% 90% 87% 87% 100%
% Level 5-6 19% 25% 10% 13% 13% 0%

 

In short, the effort to mine at level 5 really wasn’t worth it. I’d have been better off extending the range of the tunnels at levels 8 and 11, or, if looking for Lapis, to extend up to make tunnels at level 14.

In any case, I got quite a good haul out of this effort!

* For this world I used the seed “St Louis” because we’d just visited there. It’s a great challenge, as you spawn on a set of mesa islands with just a single tree to work with, and a little bit of grass from which to get seeds. But that was plenty, as I have a whole forest and farms going strong. There’s also an ocean monument nearby, and if you go straight east for a while (use a boat) from the southeast islands you’ll cross a couple more islands and then get to a desert village and a number of other villages nearby.


Update: with Eric’s comment, we’ve worked out how to make SQLite work properly with Xamarin without playing versioning games. The instructions can be found on http://developer.xamarin.com/guides/cross-platform/xamarin-forms/windows/samples/#sqlite, with thanks to Craig Dunn. The short of it is that you want to add SQLite.net-PCL from NuGet, then separately add a reference to Microsoft Visual C++ 2013 Runtime.

We return you now to the original post…

 

The last few weeks I’ve been making significant revisions to a Xamarin project based on code review feedback. This project is part of a larger effort that we’ll be presenting in a couple MSDN Magazine articles starting in August.

One big chunk of work was cleaning up all my usage of async APIs, and properly structuring tasks+await to do background synchronization between the app’s backend and its local cache for offline use. The caching story will be a main section in Part 2 of the article, but the story of cleaning up the code is something I’ll write about here in a couple of posts.

The first bit of that story is my experience–or struggle–to find the right variant of SQLite to use in the app. As you might have experienced yourself, quite a few SQLite offerings show up when you do a search in Visual Studio’s NuGet package manager. In our project, I started with SQLite.Net-PCL, which looked pretty solid and is what one of the Xamarin samples itself used.

However, I ran into some difficulties (I don’t remember what, exactly) when I started trying to use the async SQLite APIs.
On Xamarin’s recommendation I switched to the most “official” variant, sqlite-net-pcl, which also pulls in SQLitePCL.raw_basic.0.7.1. Keep this version number in mind because it’s important here in a minute.

This combination worked just fine for Android and iOS projects, but generated a warning for Windows Phone: Some NuGet packages were installed using a target framework different from the current target framework and may need to be reinstalled. Packages affected: SQLitePCL.raw_basic.

This is because SQLitePCL.raw.basic is marked for Windows Phone 8.0 but not 8.1, which is what my Windows Phone project in the solution was targeting.

OK, fine, so I went to the NuGet package manager, saw an update for the 0.8 version of SQLitePCL.raw.basic, and installed that. No more warning but…damn…the app no longer ran on Windows Phone at all! Instead, the first attempt to access the database threw a System.TypeInitializationException, saying “The type initializer for ‘SQLitePCL.raw’ threw an exception.” The inner exception, System.IO.FileNotFoundException, had the message, “The specified module could not be found. (Exception from HRESULT: 0x8007007E).”

What’s confusing in this situation is that SQLitePCL.raw does not appear in the Windows Phone project’s references alongside sqlite-net, as it does in the Android and iOS projects. This is, from what I can see, because the Windows Phone version of sqlite-net does some auto-gen or the raw DLL or has pre-built versions in its own package, so a separate reference isn’t necessary. (If you know better, please comment.)

Still, those DLLs were right there in the package and I couldn’t for the life of me figure out why it couldn’t find them, so I resorted to the tried and true method of trying to repro the failure from scratch with a new project, where the default Windows Phone project targeted 8.0. I then added “SQLite-net PCL” to all the projects in the solution, which brought in the raw 0.7.1 dependency, tossed in a couple APIs calls to create and access the database, and gave it an F5. Cool, everything worked.

Next, I retargeted the Windows Phone project to 8.1 and F5’d again. Everything still worked, but I got the warning about SQLitePCL.raw.basic once again. Apparently it’s OK to ignore that one.

I then updated SQLitePCL.raw to the 0.8 version and boom–got the exception again, so clearly there’s an incompatibility or bug in the 0.8 version with Windows Phone 8.1.

Clearly, then, the solution is to altogether avoid using the 0.8 version with a WP8.1 target, and if you want to suppress the warning, open packages.config in the Windows Phone project and have the SQLitePCL.raw_basic line read as follows:

<package id=”SQLitePCL.raw_basic” version=”0.7.1″ targetFramework=”wp80″ requireReinstallation=”False” />


I know it’s been a while since I posted much on my blog here. The coding project I was engaged in at Microsoft took up much of time between January and March, and the focus on coding didn’t leave much time to write about said coding. The //build came along and I’ve been working on Visual Studio feature guides with our marketing team.

I also discovered, in the process of coming back to my blog and updating WordPress, that the MySQL database that you can get through an Azure account (where I host this site), has a 20MB limit on ClearDB’s free tier. While updating WordPress, which does database updates as well, the MySQL file exceeded that limit and so the database got set to read-only. This, of course, meant that the database couldn’t be updated which then got me stuck in the WordPress database update loop-of-death.

Having returned from //build last week (where I spent most of my time in the Visual Studio cross-platform development kiosk talking to developers about Cordova, Xamarin, the Universal Windows Platform, and cross-platform C++), I finally got this sorted out by deleting all the spam comments from the WordPress database to reduce the file size, after which the update worked and I can post again.

[Addendum: the spam comments continue to come in at a frightening pace! Fortunately, the akismet plugin for WordPress does a good job at catching them, and will supposedly auto-delete in 15 days. However, the sheet volume of spam (many of which are 1-2 pages long) and all of akismet’s metadata it saves for each one, generates quite a few MB of garbage data in the database. So I’m having to monitor all this more closely. I hope soon to migrate the whole DB to an Azure database with a much larger quota.]

Speaking of cross-platform development, two other pieces I worked on recently are summary topics for Visual Studio Application Lifecycle Management (ALM) features as they apply to Cordova and Xamarin projects. You can find those topics on the MSDN Library:

In the meantime, our coding project team has been writing up our learnings for MSDN Magazine, so you’ll see those articles later this summer. I’m working on cleaning up my Xamarin client code, which will be the focus of Part 2 of the article.

A few folks have asked, by the way, whether I’ll be updating Programming Windows Store Apps with HTML, CSS, and JavaScript for Windows 10 and the Universal Windows Platform. Because I’m no longer with the Windows team, I won’t have working hours to focus on that project. What I’m looking at, however, is moving to something of an open-authoring model. I’m hoping first to split the Windows 8.1 book into two parts. The first would be WinJS-focused and separate from Windows, as WinJS is now its own open-source library. The second part would be Windows apps using JavaScript without the WinJS stuff.

Then I can put the files on GitHub and invite contributions, serving more in the role of an editor than a writer, though I’d probably still write some. Anyway, let me know what you think of the idea!


Similar to my previous post, but perhaps not quite as fun, is an account from Fighter: The True Story of the Battle of Britain, by Len Deighton, which I just finished.

Any comparison of the Merlin engine [as used in the RAF Spitfire and Hurricanes] and the Daimler-Benz DB 601A [as used in Messerschmidt Bf109’s] must begin by mentioning the latter’s fuel-injection system. …

Fuel injection, which puts a measured amount of fuel into each cylinder according to temperature and engine speed, etc., was demonstrably superior to the carburetors that the Merlins used. Carburetors are, at best, subject to the changes of temperature that air combat inevitably brings. At worst they bring a risk of freezing or catching fire. And with such large, high-performance engines, the carburetor system seldom delivers exactly the same amount of fuel simultaneously to each cylinder. Worst of all, the carburetor was subject to the centrifugal effect, so that it starved, and missed a beat or two, as it went into a dive.

The RAF pilots learned how to half-roll before diving, so that fuel from the carburetor was thrown into the engine instead of out of it, but in battle this could be a dangerous time-wasting necessity.


Engineers–those on trains–in the 1800s got a good start in the art of hacking. This is from The Story of American Railroads, a thoroughly well-written and entertaining book by Stewart H. Holbrook written in the 1940s that provides many quotable passages:

Although neither the Santa Fe [railroad] or most of the other roads were in a hurry to adopt new inventions, the Santa Fe held in high esteem a gadget known as a Dutch clock. This device, perhaps the most unpopular one with railroad men of the day, was set up in the caboose and it noted and recorded on a tape the speed at which the train traveled. The rule was that freights should maintain a speed of eighteen miles an hour, no more, no less. The Dutch clock soon brought reprimands to all freight conductors who tried to make up time for the breakdowns of equipment that were forever happening.

After considerable discussion of the Dutch clock, the boys figured out a method of handling the menace. On the first sidetrack out of the terminal, the crew would uncouple the caboose, then uncouple the engine, bring it back to the rear on the main line, set it in behind the caboose, then use it to slam the caboose into the standing train at a speed of exactly 18 miles an hour. This, it had been discovered, so affected the Dutch clock’s insides that thereafter it continued to clock 18 miles an hour regardless of the speed developed. This fixing the Dutch clock was considered fine sport, and always left the train crew with a sense of immoderate satisfaction.