Category Archives: windows

XAML and C#, or HTML and WinJS for Windows Store, Universal and cross platform apps?

Microsoft designed the Windows Runtime (WinRT, the engine behind the controversial touch-friendly “Metro” user interface in Windows 8) to support three development platforms. These are C++ with XAML (for most GUI apps) or DirectX (for fast games); or C# and XAML; or HTML and JavaScript using the WinJS library for access to Windows-specific functions.

Microsoft’s line is that all three approaches are fine to use, with little performance difference other than that C++ avoids an interop layer. Of course if you have any arbitrary code that runs faster in C++ than in C#, then you will still see that difference in the WinRT environment.

It is also obvious that if you are an HTML and JavaScript expert but know nothing of C# or XAML, you should use WinJS; similarly if you have a lot of C# code to port and know nothing of HTML or JavaScript, C# and XAML chooses itself.

But what if you approach the decision from a neutral perspective. I am going to leave aside the C++ option for the moment as it is more of a leap than C# versus JavaScript. Which is best?

On the WinJS side, a common misconception is that this library is only for Windows. At Build 2014 Microsoft announced that WinJS is now open source, and works on other browsers and devices:

The library has been extended to smaller and more mobile devices with the release of WinJS 2.1 for Windows Phone 8.1, which was announced today at //build. Now that WinJS is available for building apps across Microsoft platforms and devices, it is ready to extend to web apps and sites on other browsers and devices including Chrome, Firefox, iOS, and Android.

In order to sample this, I went along to try.buildwinjs.com on an iPad. All the things I tried quickly worked fine on iOS.

image 

If you used WinJS to build an app, you could use PhoneGap or Cordova to package it as a native application for the iOS or Android app stores.

A further reflection on this is that some of the WinJS controls which you might have assumed are native WinRT controls instantiated from JavaScript are in fact implemented in CSS and JavaScript. That is an advantage for cross-platform, but does suggest that Microsoft has been busy duplicating the look and feel of XAML controls in HTML and JavaScript, which seems a lot of work and an approach which is bound to result in inconsistencies.

Another snag with this approach – leaving aside the questions of performance and so on which I have not investigated – is that you end up with the distinctive look and feel of a Windows 8 app, which is going to be surprising on these other devices.

C# also has cross-platform potential, thanks to the great work of Xamarin and not forgetting RemObjects C#. Note though that I wrote C# rather than XAML. There is no cross-platform XAML implementation other than the abandoned cross-platform Silverlight efforts, Silverlight for the Mac and Moonlight for Linux. Xamarin expects you to rewrite your UI code for each platform – which may in fact be a good thing, though more effort.

If you are focused on the Windows platform though, it seems to me that the pendulum is swinging away from WinJS and towards C# and XAML. Wordament is an interesting case. This is one of the better games for Windows 8, and also available for Windows Phone, iOS and Android. Originally this was implemented in HTML and JavaScript. The developers have blogged about the choices they made:

Wordament grew up very fast. It seemed like it went from an indie game with a handful of players to a full on Microsoft title with millions of users, on lots of platforms, almost overnight. In that transition we ended up writing lots of code. For instance, in the course of a year we had ports of the Wordament client written in JavaScript, Objective C, C++ and C#. Each one of these ports has its own special issues, build processes and maintenance challenges. At the time, we were still a two person team and Jason and I were struggling to continue to innovate on Wordament, while supporting the “in-market” code bases we had shipped. So we started looking for a solution that would allow us to share more code between all of the platforms we were targeting. Funnily enough, the answer was sitting in our own backyard: C#.

As we looked around at the state of “cross platform development” on Windows, Windows Phone, iOS and Android we started to realize that C# was an excellent choice to target all modern mobile devices. So we did just that. With the help of Visual Studio for Windows and Xamarin for iOS and Android, we started a project to build a single version of Wordament’s source code that could target all the platforms we ship on. This release on Windows 8 marks the end of that journey. All of our clients are now proudly built out of one source tree and in one language. Even our service, which runs on Windows Azure, is built in C#. This is a huge efficiency win for our team of four.

Notable also is that the forthcoming Office for WinRT, previewed at Build, is written in XAML and C++ (according to what I was told). This means XAML will get some love inside Microsoft, which is bound to be good for performance and features.

An advantage of the C# approach is simply that you get to use C#, which is well-liked by developers and with some compelling new features promised in version 6.0, many thanks to the Roslyn project – which also promises a smarter editor in Visual Studio.

What about XAML? This is harder to love. XML is out of fashion – too verbose, too many angle brackets – and the initial promise of a breakthrough in designer/developer workflow thanks to XAML and MVVM (Model – View – ViewModel, which aims to separate code from user interface design) now seems hollow. I am writing a game in XAML and C# and do not much enjoy the XAML part. One of the issues is that the editing experience is less satisfactory. If you make an error in the XAML, the design view simply blanks out with an “Invalid Markup” error. Further, the integration between the XAML and C# editors is a constant source of problems. Half the time, the C# editor seems to forget the variables declared in XAML, giving you lots of errors and no code completion until you next compile. Even when it is working, a rename refactor in the C# editor will not rename variable references that are within quotes in the XAML, for example property names that are the targets of animations.

On the plus side, XAML is amazing in what it can do when you work out how. The user interfaces it generates are rich, scalable and responsive. It is way better that the old Win32 GDI-based approach (also used in the Windows Forms .NET API), which is hard to get right for all the combinations of screen sizes and resolutions, and has odd dependencies on system font sizes and dialog units (don’t ask).

Despite the issues with XAML, C# and XAML (or C++ and XAML) is my own preference for targeting the new Windows platform, but I am interested in other perspectives on this.

Getting animated: basics in Windows Store apps

I am not a designer and prefer to avoid things like animation as too difficult. On the other hand, I am writing an electronic card game and it looks bad if the cards move without any animation. There is also an issue in that animation is built into the standard controls, so if you do not animate your own parts of the user interface, it looks inconsistent.

Animation is more significant than it may first appear. You can think of it as a natural progression from a basic graphical user interface, along with things like full window drag. In the real world, objects do not just blink in and out of existence when they move from one spot to another.

My game is a bridge simulation so four cards are laid on the table in turn, at which point the winner of the four cards is calculated and the four cards gathered to form a “trick”. In my original implementation, the four cards simply disappeared at the end of the trick. How can I have it so that they smoothly gather themselves into a pile of four cards?

Like most things in Store apps, it proved a little more complex than I had thought. Originally, I put put each card in a separate cell of a layout grid. In Store apps, there is no built-in way to animate movement between grid cells, though users have come up with custom animations that do this. I thought it would be simpler to put the cards on a canvas instead.

I did some sums and positioned four Rectangle objects at the borders of the Canvas.

image

I want the Rectangle objects to slide smoothly into a pile in the centre. You do this in XAML with a Storyboard element. A Storyboard has child animation elements. When you call Storyboard.Begin() in your code, all the animations run. They run simultaneously unless one or more of the animations has a different BeginTime attribute. If you want a sequence of animations, you can either vary BeginTime, or use a KeyFrame animation which is designed for this.

There are several ways to do what I want. One is to animate Canvas.Top and Canvas .Left using a DoubleAnimation (the name indicates that it targets properties of type Double, not that anything happens twice). Note that if you this, the Storyboard.TargetProperty has to be in parantheses:

Storyboard.TargetProperty="(Canvas.Top)"

because it is an attached property. However, I chose to use a RepositionThemeAnimation. I found the way this works counter-intuitive. In XAML, you define a RepositionThemeAnimation with either or both a FromHorizontalOffset and a FromVerticalOffset. At runtime, the RepositionThemeAnimation moves the object to the offset position instantly, and then back to its starting point with animation. In other words, the animation itself does not move the object; unless you have AutoReverse set to True, in which case it does a second animation back to the offset position.

Once you grasp it, it is not difficult. Here is my Storyboard, set as a XAML Resource:

<Page.Resources>
    <Storyboard x:Name="TrickStoryboard">
        <RepositionThemeAnimation Storyboard.TargetName="CardLeft" SpeedRatio=".5"  FromHorizontalOffset="-185"/>
        <RepositionThemeAnimation Storyboard.TargetName="CardTop" SpeedRatio=".5"  FromVerticalOffset="-200"/>
        <RepositionThemeAnimation Storyboard.TargetName="CardRight" SpeedRatio=".5"  FromHorizontalOffset="185"/>
        <RepositionThemeAnimation  Storyboard.TargetName="CardBottom" SpeedRatio=".5"  FromVerticalOffset="200"/>
    </Storyboard>
</Page.Resources>

And here is my code to gather the trick:

this.CardTop.Margin = new Thickness(0, 185, 0, 0);
this.CardLeft.Margin = new Thickness(200, 0, 0, 0);
this.CardRight.Margin = new Thickness(-200, 0, 0, 0);
this.CardBottom.Margin = new Thickness(0, -185, 0, 0);
this.TrickStoryboard.Begin();

In other words, you move the objects to where you want them, and then apply the animation which moves them temporarily back to their starting point, then smoothly to their destination. At this point I should include a little video, but will leave you to imagine the four Rectangles above sliding and merging to a single central Rectangle.

Something to watch for here is how the animation impacts your code flow. The animation runs asynchronously, so if you have:

this.TrickStoryboard.Begin();
DoSomething();

then DoSomething runs before the animation completes. If this is not what you want, you can break at that point, and handle the StoryBoard.Completed event to resume. In my brief tests, StoryBoard.Completed always fires even if the animation gets interrupted, say by some other code that did something to the objects.

For more on this subject, read up on Animating your UI and get to know the different animation classes, Visual states, easing functions, RenderTransforms and more. It soon gets complex and verbose unfortunately, but on the plus side it is great to have animation baked into the framework, and the result is a more polished user interface.

Microsoft completes Nokia acquisition: what now for Windows Phone?

Microsoft has completed its acquisition of Nokia today, a milestone in the turbulent story both of Nokia and of Windows Phone, which Nokia adopted in the hope of establishing a “third ecosystem” to challenge Apple iOS and Google Android.

Rumour has it that the Nokia acquisition was controversial within Microsoft and a large factor in the departure of Steve Ballmer as CEO. However, even if Microsoft took the view that an independent Nokia was better for Windows Phone, it faced the risk that market pressure would drive Nokia to Android and weaken the platform. The beginnings of that process may have been under way, with the launch of the Nokia X Android-but-not-Google range of phones, but we will never know, since Microsoft decided on acquisition.

image

How important has Nokia been for Windows Phone? In my view, life-saving. Before Nokia, there was no manufacturer nor operator which really cared about the platform, and it showed in lacklustre hardware and half-hearted marketing efforts. Nokia came up with the distinctive Lumia brand and style, added a decent mapping service, and with its focus on the PureView camera technology, gave enthusiasts a reason to take a close look at its devices. It also saw an opportunity at the low end, and created some great value devices that opened up a new market for the operating system.

There were some blunders (the original Lumia 800 suffered many faults and terrible battery life on launch) and Lumia did not grow fast enough to restore Nokia to health, but to my mind it was a good effort.

Today, the general opinion of Windows Phone is that it is a strong smartphone operating system but suffers from a lack of high-quality apps. Users have to put up with the fact that most app vendors feel they are done if they support iOS and Android; and if there is a Windows Phone version of their app, it is often poor. That is not a great position for Microsoft/Nokia to be in, but it could be worse. Blackberry 10, which is also a decent mobile operating system, has been all-but written off as a viable contender.

Microsoft is fortunate in that, unlike Blackberry, it can to some extent create its own ecosystem. Office 365, Bing, OneDrive, Nokia’s maps, Azure for developers needing a cloud back-end: taken together they form a viable alternative. In this respect, Microsoft actually has an advantage over Apple, which lacks this breadth of services.

I have been reading the latest Developer Economics report from Vision Mobile. It is a good example of the neutral perspective on Windows Phone, though you will find it somewhat inconsistent:

Windows Phone sales picked up significantly in Q3 2013, showing a 140% increase year-on-year, fuelled primarily by low-end device sales. According to Kantar, Windows Phone sales in the three months running to Oct 2013, reached double-digit figures in some Western European markets. While this is certainly a positive sign for Microsoft they will continue facing an uphill struggle, in an increasingly unfavourable race against the two runaway leaders, iOS and Android.

The report emphasises that iOS and Android have won the mobile OS wars, but says that there are signs of hope for Microsoft:

Windows Phone Developer Mindshare has finally moved upwards, following positive market signals in the last two quarters. As we have frequently highlighted in past reports, the developer intent has always been there, with Windows Phone figuring at the top of our Developer Intentshare chart, but needed positive market signs in order to convert this interest into Mindshare. While the 26% Developer Mindshare is still less than half of that for iOS, Microsoft can now claim that over a quarter of developers that target mobile platforms are now actively developing for Windows Phone. […]

As a latecomer to a mobile market dominated by strong network effects, establishing a credible footprint in mobile remains a formidable challenge
for Microsoft. We believe that Microsoft may be better served in the long-run by leveraging the Android ecosystem as the deployment platform for Office
and Server businesses which are still growing.

Microsoft is in fact supporting iOS and Android as clients for its cloud services, as noted again at yesterday’s financial webcast, where CEO Satya Nadella talked about a strategy that goes across “devices some ours, some not ours.” It is a bit of both though, and the company is not showing any signs of weakening its own mobile efforts.

In my view reports like that from Vision Mobile miss a couple of factors. One is that Windows and Windows Phone are converging. They already use the same OS kernel, and at the Build conference earlier this month Microsoft announced Universal Apps that will run on both, and the ability for developers to sell an app once and have users install on both phone and full Windows.

This means that the future of Windows Phone and that of Windows itself are closely bound together. Longer term, they will either both fade away, or both succeed.

Windows remains a huge business for Microsoft, despite the decline of the PC, especially in business. Microsoft’s problem though is that adoption of Windows 8 has been relatively weak, and that those who do use it, largely live in the desktop environment rather than running Store apps (of which Universal Apps are a variant).

Despite the dismal progress so far for the Store apps platform and ecosystem, I believe it should be taken seriously. On paper it has many advantages, not only for touch control, but also in deployment, security, roaming data driven by the cloud, and discoverability through the store. Isolation from the core operating system protects users against the things that destroy desktop Windows, like unwanted extras foisted on users who simply need to update Java or Flash.

At Build we saw not only Universal Apps, but also a preview of Office in the Windows Runtime (Store app) environment. We also saw a preview of Store apps running within a window in the desktop environment, solving the jarring transition between desktop and Store app environments that unsettles users. If Microsoft gets this right, both Windows Phone and Windows tablets will be substantially more attractive.

Microsoft also has the ability to bind Windows Phone into its enterprise device management environment, System Center and InTune. In Windows Phone 8.1 the device management and security features businesses need are much improved. More is still needed; but the company should be able to build integration points that make it attractive to business customers already using products such as Active Directory, Microsoft Office, Office 365, System Center or InTune.

Another factor is the strength of Visual Studio for developers, especially as Microsoft improves its integration with cloud services like Azure and Office 365. You can use C# everywhere from cloud or server to mobile client.

image

Cortana is sure that Windows Phone is the best; but check out the Bing ad.

What then is the future of Windows Phone? Uncertain, as ever; but if Microsoft pulls off a smooth Nokia acquisition – leaving in place the things that enabled the company to build the Lumia brand – and if it delivers on the promise we saw at Build, of a strong unified platform, then I expect market share to continue to grow. If it can climb to 10% or 15%, it will be on the map for vendors and the app problems will ease.

On the other hand, if Microsoft/Nokia means a return to the ineffective marketing and strategy we saw before Nokia adopted Windows Phone, then I expect Windows Phone to follow Blackberry into oblivion.

I am positive, but Microsoft needs to execute carefully and quickly to win market share for its mobile platform.

Microsoft financials: strong quarter especially in cloud services. We have a very different way to think about Windows says Nadella

Microsoft has released its financial results for the first quarter of 2014. The year on year segment figures look like this:

Quarter ending March 31st 2014 vs quarter ending March 31st 2013, $millions

Segment Revenue Change Gross margin Change
Devices and Consumer Licensing 4382 +30 3906 -23
Devices and Consumer Hardware 1973 +571 258 -135
Devices and Consumer Other 1950 +294 541 +111
Commercial Licensing 10323 +344 9430 +345
Commercial Other 1902 +453 475 +211

The “Gross margin” figures above do not tell us much other than for hardware, since Microsoft no longer allocates its research and development costs against specific segments.

Overall revenue is slightly down year on year but only because of a $1778 million decline in the “corporate and other” segment. This means it was a better quarter than the overall revenue suggests.

So what is notable? Windows OEM revenue is up, but only thanks to the business market, and partly thanks to upgrades driven by the end of support for Windows XP. Consumer OEM Windows is down by 15%.

Xbox revenue is up 45% thanks to the launch of Xbox One (and I have a hunch we will see less positive figures in future since Sony’s PS4 seems to be winning the console wars).

Surface (Microsoft’s own-brand tablet) revenue is up by over 50% year on year, to $494 million. It is a significant business, though apparently not a profitable one. Cost of sales was $539 million, says Microsoft in its notes.

Windows volume licensing, which accounts for most enterprise usage, is up 11%, also no doubt influenced by the end of XP support. SQL Server revenue is up by 15%, though in relation to server products Microsoft notes the impact of “the transition of customers to Cloud Services.”

The big winner is cloud services. Microsoft says:

  • Office 365 revenue grew more than 100%
  • Microsoft Azure revenue grew more than 150%
  • Cloud services revenue grew $367 million or 101%

These sums are a little puzzling. If growth was 101% overall, and Office 365 grew by more than 100%, where is the Microsoft Azure growth hiding, or was it from a very small base?

Note that consumer Office 365 is accounted for separately, it seems, as part of “Devices and Consumer other”. There are now 4.4 million Office 365 Home subscribers, growing by around 1 million in this quarter.

Questioned in the earnings call, CEO Satya Nadella talked about mobile-first and cloud-first, adding that the strategy goes across “devices some ours, some not ours.” He also mentioned how the advent of Universal Apps means that “we have a very different way to think about [Windows].” That is partly wishful thinking of course: the Universal App framework is still in preview and targets a still unreleased update to Windows Phone (8.1). Still, that is the strategy, even if it means giving Windows away on smaller devices – we have “monetization on the back end,” said Nadella, presumably thinking of Office 365 subscriptions and the like.

On the business and enterprise side (where Microsoft can be more confident) Nadella also spoke of the synergy between Office 365 and Azure; every Office 365 sign-up enables Azure as a business cloud platform, thanks to Azure Active Directory and other integration points.

Microsoft’s segments summarised

Devices and Consumer Licensing: non-volume and non-subscription licensing of Windows, Office, Windows Phone, and “ related patent licensing; and certain other patent licensing revenue” – all those Android royalties?

Devices and Consumer Hardware: the Xbox 360, Xbox Live subscriptions, Surface, and Microsoft PC accessories.

Devices and Consumer Other: Resale, including Windows Store, Xbox Live transactions (other than subscriptions), Windows Phone Marketplace; search advertising; display advertising; Office 365 Home Premium subscriptions; Microsoft Studios (games), retail stores.

Commercial Licensing: server products, including Windows Server, Microsoft SQL Server, Visual Studio, System Center, and Windows Embedded; volume licensing of Windows, Office, Exchange, SharePoint, and Lync; Microsoft Dynamics business solutions, excluding Dynamics CRM Online; Skype.

Commercial Other: Enterprise Services, including support and consulting; Office 365 (excluding Office 365 Home Premium), other Microsoft Office online offerings, and Dynamics CRM Online; Windows Azure.

Windows problems: new users cannot log in, SQL Server 2014 install fails

Two issues I have seen recently:

1. A Windows 7 laptop which belonged to a developer and was being passed on to a new user. However, although you could create the new user, you could not log in as that user. The error was “User Profile Service service failed the logon. User profile cannot be loaded.”

I narrowed the problem down to an “Access denied” error when trying to create the profile, but we decided to restore Windows to factory settings (using recovery tools) since that was probably a better approach for the new user anyway – you never know what a developer may have tweaked or installed in Windows!

2. SQL Server 2014 Database Engine installation failing on Windows 8. The reported error: Could not find the Database Engine startup handle.

Annoyingly, you cannot attempt a repair install if you get this, since repair cannot run if there has not been a successful install in the first place. However this error does not rollback the installation, so you have the feature installed but not working. You have to remove the SQL Server feature using control panel, then you can retry. I got this on a couple of machines, tried a few things but failed, so used fresh VMs instead.

Others have run into this and there is a solution, which applies to both problems. They are actually the same, since SQL Server 2014 creates a new profile in the default install.

This solution means resetting the permissions on c:\users\default so that they are replaced with permissions inherited from the parent folder. This solution works; but it is not perfect, since these are the wrong permissions for the folder (too loose). Someone has done the job of finding the correct permissions for Windows 7. Applying all these is arduous though, and things may possibly have changed with updates since. In a production environment it would be better to narrow down the exact permission that is wrong, or to do a system restore.

If you are happy to risk it, navigate to c:\users in Windows Explorer and find the Default folder. This is hidden by default; you can make it visible using the View Options in Explorer; on the View tab choose Show hidden files, folders and drives. Next, right-click the c:\users\Default folder and choose Properties, then the Security tab, then Advanced, then click Change Permissions. Check the box:

Replace all child object permission entries with inheritable permission entries from this object

Click OK – it does not take long – and now new users can log in, and the SQL Server 2014 setup runs OK.

image

The problem seems to be common so it is likely that either an official update or a commonly-used third-party install is breaking these permissions. I would be glad to know what it is; it would also be good if Microsoft would build into Windows a feature that would restore default permissions for a system folder like this one.

Update: It may be sufficient to delete a single file. See this thread where event logs lead to a sqmdata…sqm file that, when deleted, fixed the issue. Check the Windows Application log for event 1509.

Notes on styling a Windows Store app ListView to vary item appearance according to the data

Problem: You have a ListView containing data. You want to vary the appearance of items in the ListView according to the value of the data.

I spent some time on this in relation to a panel for a game I am writing. For example, you have a ListView containing numbers. How can you have negative numbers appear in red?

image

In desktop WPF (Windows Presentation Foundation) you could do this with Property Triggers but these are not supported in Store apps.

One way to do this is with a value converter. Add a class to your project called MyValueConverter. Make the class public, and inherit from Windows.UI.Xaml.Data.IValueConverter.

Right-click IValueConverter and choose Implement Interface to have Visual Studio create two stub methods, Convert and ConvertBack.

This class is going to return an object which will be applied to the Foreground property of a ListViewItem. The Convert method looks like this:

public object Convert(object value, Type targetType, object parameter, string language)

At runtime, the value argument will contain the item displayed in this row of the ListView. The targetType will match the type of the property we are setting, which in this case is a Brush object.

Now add an instance of MyValueConverter to MainPage.xaml (or App.xaml) as a resource. If there is no Page.Resources element, create it, and add an instance of MyValueConverter with the Key “NumberForegroundConverter”:

<Page.Resources>
<local:MyValueConverter x:Key="NumberForegroundConverter" />
</Page.Resources>

Next, select the ListView element in the XAML editor or designer. Right-click the selected element in the designer, and choose Edit Additional Templates – Edit Generated Item Container (ItemContainerStyle) – Edit a Copy …

image

Accept the default name of ListViewItemStyle1 and click OK.

This generates an element that defines the layout and appearance of items in the ListView. Currently it does not appear to do anything, since it is a copy of the default settings.

Find the element called <ListViewItemPresenter> which is nested within <ControlTemplate TargetType=”ListViewItem”>. No Foreground attribute for ListViewItemPresenter is generated, but we can add one:

Foreground="{Binding Converter={StaticResource NumberForegroundConverter}}"

If you now run the project, you will get an exception, because the methods in MyValueConverter do not yet have any code. Now we have to think about the type of the items in the ListView. In this example, I just typed some strings into the XML editor:

<ListView ItemContainerStyle="{StaticResource ListViewItemStyle1}">
<x:String>145</x:String>
<x:String>-30</x:String>
<x:String>442</x:String>
</ListView>

All the items are strings, so the Convert method can look like this:

String s = (String)value; //note this ONLY works if the item is always a string

if (float.Parse(s) < 0)
{
return new SolidColorBrush(Windows.UI.Colors.Red);
}
else
{
return new SolidColorBrush(Windows.UI.Colors.White);
}

We don’t care about the ConvertBack method so can use this code:

return Windows.UI.Xaml.DependencyProperty.UnsetValue;

It works but there are some issues. One oddity is that when you roll the mouse over a negative number, it looks the same as a positive number.

image

This is because we did a converter for the Foreground property but not for the SelectedForeground property. XAML in Store apps makes extensive use of themes, and themes include a lot of brushes.

Another issue, which may or may not impact your application, is that the converter code does not run again if you change the displayed item dynamically. That is, if you replace the item it updates OK, but if you update the existing item it does not.

A slightly more complex example will demonstrate this. Let’s say that rather than displaying strings, the ListView is displaying Widget quantities, where a negative number indicates backorders. The ListView is bound to an ObservableCollection<Widget>, and the Widget class implements INotifyPropertyChanged so that the ListView will update automatically when a Widget property changes. Note that the NumberForegroundConverter must be updated to accept a Widget value rather than a string.

Here is what happens if a Widget had a negative quantity when the ListView was first populated, but got dynamically updated to a positive value (some stock arrived):

image

Oops! Now the positive quantity is in red.

We can fix this by abandoning the converter, and instead giving the Widget class a Foreground property of its own, calculated to return Red for negative quantities and White for positive. Make sure it fires a NotifyPropertyChanged event when updated. Now the Foreground property in <ListViewItemPresenter> looks like this:

Foreground="{Binding Foreground}"

It works:

image

I used this approach in my game in order to implement an Enabled property that indicates items which are unselectable. This changes dynamically according to the state of the play.

Note that you are unlikely to want a Foreground property in your business objects, but could create a DisplayWidget class for the purpose.

I realise that these are not the only ways to create a ListView which styles items differently according to their values, but they may be the simplest. Other suggestions and comments are welcome.

Update: Mike Taulty has some comments and suggestions here.

Fixing failed wifi on Surface Pro

I experienced an odd problem on a Surface Pro (first edition). This happened shortly after upgrading to Windows 8.1 Update though not immediately after.

Symptom: I could connect to wifi but although I had five bars of signal strength, according to the notification area icon, I had no connection; and ipconfig reported “Media disconnected” for the wifi adapter. Tried a different wifi point, same problem. Rebooted (of course), same problem.

My next thought was another old favourite: reset tcp/ip with netsh int ip reset. Restarted, no change.

The fix I found was to go into device manager (which was not reporting any issues) and to remove the Marvell wireless network controller. Scan for hardware changes to reinstate same, and I was up and running.

The incident reminds me of how fragile Windows seems to be at times. One of the reasons I like Windows RT (the ARM version) is that its locked-down operating system should be more resilient though it is not immune (you can still scramble the registry if you feel so inclined).

Update: I may not yet be in the clear. Later in the day, wifi failed again, and this time the Marvell adapter showed in device manager with a fault icon. Enabling and disabling the device restored connectivity. A driver issue with the latest Windows update? Or failing hardware?

A quick hands-on with native code compilation for .NET

I had a quick look at the .NET Native Preview. I am interested to see what the benefits might be. Note that currently the preview only supports 64-bit Windows Store apps.

Here is what is promised:

For users of your apps, .NET Native offers these advantages:

  • Fast execution times
  • Consistently speedy startup times
  • Low deployment and update costs
  • Optimized app memory usage

I created a small C# app that counts prime numbers using a simple approach. I created it first as a Universal App that does not use .NET Native, and then as a second app that does use .NET Native.

image

My initial results are disappointing. The time taken to count prime numbers is similar in both apps.

image

As a further test, I added code that adds the prime numbers found to a ListView control using an async task. The idea was to see if GUI interaction and multi-threading would be more revealing than simply crunching numbers in a tight loop. The apps takes much longer with this enabled, but again, there is nothing to choose between the two.

Did I really succeed in compiling the app to native code? I think so. Here are the contents of the AppX folder for the standard .NET executable:

image

and here for the native compiled executable – note the additional DLLs:

image

I am not actually surprised that there is no performance benefit in my example. JIT (just-in-time) compilation means that any .NET application is native code at runtime, though optimization might be different.

I have ended up with a much larger app to deploy, though the relative difference would be less, I imagine, with an app that contains more code.

I can also readily believe that start-up time will be better for a native compiled app, since there is no need for the JIT compiler. However my app is so small that this is not significant.

My question though is what kind of app will benefit most from native compilation? I would be interested to see guidance on this.

Of course it is also possible that later iterations of the technology will yield different results.

Microsoft Build 2014: what happened

It’s curious. Microsoft’s new CEO Satya Nadella has been in place for only a month which means that almost everything announced at Build, Microsoft’s developer conference which took place last week in San Francisco, must have been set before he was appointed; yet there was a sense of “all things new” at the event, as if he had overseen a wave of changes.

The wave began the previous week, with the simultaneous announcement and delivery of Office for iPad. The significance of this is threefold:

  • It demonstrated Microsoft’s decision to give first-class support to mobile platforms other than Windows
  • It demonstrated that Office can be redesigned to work nicely on a tablet
  • The quality of the product exceeded expectations, showing that in the right circumstances Microsoft can do excellent non-Windows software

image

Next came Build itself. It was a tale of two keynotes. The first was all about Windows client – both Phone and PC. The core news is the arrival of the Windows Runtime  (WinRT, the engine behind Metro/Store Apps) on Windows Phone 8.1. This means that WinRT is now the runtime that developers should target for apps that run across phone and desktop – and even, we were shown, Xbox One, which will support WinRT apps written in HTML and WinJS (Microsoft’s JavaScript library for Windows apps).

In support of this, Microsoft announced a new Universal App project for Visual Studio, which lets you share both visual and non-visual code across multiple targets. How much is shared is a developer choice.

There is more. A Universal App is now (kind-of) a desktop app as well as a Store app, since in a future free update to Windows 8, it will run on the desktop within a window, as well as appearing in the Start menu on the desktop. We were even shown this; apparently it is a mock-up. This was the biggest surprise at Build.

image

What did Executive VP Terry Myerson say about this? Here is the exact quote:

We are going all in with this desktop experience, to make sure your applications can be accessed and loved by people that love the Windows desktop. We’re going to enable your Universal Windows applications to run in a window. We’re going to enable your users to find, discover and run your Windows applications with the new Start menu. We have Live Tiles coming together with the familiar experience customers are looking for to start and run their applications and we’ll be making this available to all Windows 8.1 users as an update. I think there will be a lot of happy people out there.

This is significant. When Myerson says, “we are going all in with this desktop experience”, he does not mean backtracking on Windows Store apps, to return to desktop windows apps (Win32 or WPF) as the future of Windows development. Rather, he means Windows Store apps integrated into the desktop.

There is a further twist to this. Windows Store apps are sandboxed and cannot communicate with each other or with the operating system other than via carefully designed and secured paths. This is in general a good thing, but restrictive for businesses designing line of business apps. It also means that legacy code cannot be carried over into a Store app, other than by full porting.

In the just-released Windows 8.1 Update this has changed. Side-loaded apps (in other words, not deployed from the Windows Store) can now escape the sandbox thanks to Brokered Windows Runtime Components. There are some limitations (32-bit only on the desktop side, for example) but this will make it possible to implement business applications as Store apps even if they need to interact with existing desktop applications or services.

There is still a huge blocker to Store apps from a business perspective, which is that you need Windows 8. Still, my guess is that once the update with the restored Start menu appears, most of the objections to Windows 8 will melt away.

We also saw Office for the Windows Runtime, which will run on both Phone and PC. It is written, I discovered later, in XAML, DirectX and C++ (“Blazingly fast”, we were told). Corporate VP Kirk Koenigsbauer introduced a preview of this, or at least PowerPoint.

image

No detail yet, and several references to “early code” suggest to me that this is a year or more away from full release (giving Office on iPad a big head start); but it will come. Koenigsbauer did not call it cut-down; in fact, it was instanced as proof that WinRT is suitable for large-scale apps, so I would expect something more complete than Office on iPad; yet it is hard to imagine things like the VBA macro language appearing here in its current form (VBA is based on the ancient Visual Basic 6.0 runtime), so there will be some major differences.

We also saw Windows Phone 8.1, including the Cortana virtual personal assistant who responds to voice input. For me other things in Windows Phone 8.1 are more significant, including new swipe-style keyboard for fast text input, VPN, S/MIME secure email, and a new notification centre. Unlike touch Office, Windows Phone 8.1 is coming soon; Nokia’s Stephen Elop (soon to be in charge of Windows Phone at Microsoft) said that the first 8.1 Lumia devices could be out from May, depending on territory, and that all Lumia Windows Phone 8 devices will get the update in the summer.

On to day two, which was Cloud day, though we also got significant .NET developer news.

Executive VP Scott Guthrie introduced a new portal for Microsoft Azure, the cloud platform. This is not just a new look, but integrates with Visual Studio online so you can easily view and edit the code and track team projects. There are also new monitoring and analytics features so you can check page views, page load time, browser usage and more. Guthrie also announced integration with Puppet and Chef for deployment automation.

image

Language designer Anders Hejsberg also came on stage. He announced the release version of TypeScript, a “typed superset of JavaScript” which is suitable for large applications. He also announced a new preview release of the compiler project code-named Roslyn, and on stage pushed the button that published it as open source. What is Roslyn? It is the next generation compiler for C# and VB, and is itself written in C#. This enables compiler and workspace APIs, which in turn enable rich editor features:

The transition to compilers as platforms dramatically lowers the barrier to entry for creating code focused tools and applications. It creates many opportunities for innovation in areas such as meta-programming, code generation and transformation, interactive use of the C# and VB languages, and embedding of C# and VB in domain specific languages.

Roslyn will be fully released in the next version of Visual Studio, for which we do not yet have a date. Roslyn will be delivered alongside C# 6.0.

There is also a new .NET Foundation which will oversee open source projects for .NET, with backing from folk including Xamarin’s Miguel de Icaza and Umbraco’s Niels Hartvig. It is all a bit vague at the moment:

In the upcoming months, the .NET Foundation will be inviting many companies and community leaders to join the foundation, including its Board of Directors and will then finalize its operational details, including governance models for its open source initiatives, membership structure and industry and community engagement.

Another significant event in the .NET story is the arrival of true native code compilation for .NET, although currently only for 64-bit Store apps. More on this soon.

A couple of events during Build caught my eye. One was de Icaza’s session on using C# to build for iOS and Android, not so much for the content itself (though there was nothing wrong with it), but rather for the huge attendance it drew.

image

The session was moved to the Build keynote room, and while there were spare seats, the room felt well filled. This speaks loudly about the importance of those platforms even to Microsoft platform developers, as well as of Microsoft’s support of Xamarin’s work.

Another was the appearance of John Gruber, author of the Daring Fireball blog and an Apple enthusiast. He appeared in a video during the keynote, explaining how a project in which he is involved uses Azure for back-end services, and then in person at another session, interviewing journalist Ed Bott about what is changing at Microsoft.

image

Gruber seems to me representative of a group of smart observers who have not in general been impressed with Microsoft’s endeavours over the past few years; but he for one is now more positive on the subject. Windows Phone is much better than its market share suggests, he said. This alongside Azure and a new openness to supporting third-party clients has made him look more favourably on the company.

My summary is this. On the Windows client side, Microsoft is taking its unpopular Windows release and its minority Phone platform and making them better and more compatible with each other, making sense of the client platform in a way that should result in growth of the app ecosystem both on Phone and PC/Tablet. On the cloud side, the company is building Azure and Office 365 (two platforms united by Azure Active Directory) into a one-stop platform that is increasingly compelling. The result was a conference and a direction that was largely welcomed by those in attendance, as far as I could tell.

That does not mean that the PC will stop declining, or that iOS and Android will become less dominant in mobile. There is progress though, and more clarity about the direction of Microsoft’s platform than we have seen for some years.

For the official news from Build, see the Build Newsroom.

Microsoft Build goes nuts over Xamarin’s C# and .NET for iOS and Android

Xamarin’s Miguel de Icaza was booked for a standard session room at Build, Microsoft’s developer conference in San Francisco, but the session was moved to the keynote room because of demand. I am not sure how the likely demand was calculated, but it was possibly something to do with the event app that lets attendees plan their agenda.

It was just as well that the session got moved.

image

The attendance at the session mirrored my observation that Xamarin’s stand in the third-party partner exhibition was drawing more attention than any other. Xamarin’s tools let developers port applications to iOS and Android while still using C# and the .NET Framework.

image

I am not sure what to conclude from the obvious high level of interest in compiling apps for iOS and Android. You can interpret this as good news for Microsoft, in that it keeps developers working in .NET and with easy access to the libraries that support Microsoft services; or as bad news, in that it shows how many developers are moving towards non-Microsoft platforms in their app deployments.

It was the second time today that de Icaza appeared on the keynote stage. Earlier he stood there with Anders Hejlsberg, the author of C#.

image

It has been a long journey, from the time when Mono (the open source implementation of .NET founded by de Icaza) was viewed with distrust by Microsoft (as far as I could tell), as an open source competitor to the official version.

Now there is talk of whether Microsoft might acquire Xamarin – of which there is no news here at Build, I should emphasise.