Kotan Code 枯淡コード

In search of simple, elegant code

Menu Close

Tag: windows

Deploying ASP.NET 5 (Core) Apps to Windows in Cloud Foundry

Today I found myself sequestered in a room with a pile of super smart people. This is my favorite kind of day. We have already experimented with pushing an ASP.NET Core application to Cloud Foundry on linux, but we haven’t tried out whether it would work on Windows.

There are a bunch of wrong ways to do this, and we discovered a number of them. First, it’s possible (and actually a default in RC1) to use dnu publish to produce an application that needs to be compiled and doesn’t have its dependencies fully vendored. This is not only a bad idea, but it violates a number of the 12 factors, so we can’t have that.

In Release Candidate 1, you need to explicitly specify which runtime you want bundled with the app as well as indicate that you want your application compiled via the no-source option:

dnu publish --no-source --runtime active

Assuming we’ve already got a functioning, buildable application and we run this from the application’s project root directory, this will then run through a ton of compile spam and finally publish the app to a directory like bin/output/approot/, but you can override this location as well.

When RC2 comes around, we are likely to see the publish command show up as a parameter to the dotnet command line tool. Unfortunately, even though I’ve got an early RC2 build, there’s no way of knowing if that’s going to change so I don’t want to confuse anyone by speculating as to the final syntax.

Next we go into this directory and modify the web.cmd file. At the very end of this file you’ll see a line that looks like this:

@"%DNX_PATH%" --project "%~dp0packages\SampleMicroservice\1.0.0\root" --configuration Debug web %*

Make note of the %~dp0packages section of this. This substitution is looking at the packages sub-directory within the published approot directory. If we didn’t publish with the –no-source option, then our compiled service would not appear as a package here.

While this will work just fine on a plain vanilla Windows Server box, it’s not going to work in the cloud because cloud applications need to adhere to the port binding factor. This means that the PaaS needs to be able to tell the application on which port to listen, because it is taking care of mapping the inside-container ports to the outside-container ports (e.g. port 80).

So we modify this last line of web.cmd to look like this:

@"%DNX_PATH%" --project "%~dp0packages\SampleMicroservice\1.0.0\root" --configuration Debug --server.urls=%PORT% web %*

We’ve added the %PORT% environment variable, which we know is set by Cloud Foundry for all applications, Windows or Linux. Now our start command will use the application-bundled runtime to launch the application, which will have all of its dependencies vendored locally. The only thing we need to do before we push to Cloud Foundry is ensure that our Windows Cell has the right frameworks installed on it. For our test, we made sure that ASP.NET 4.6 was installed.

Now we can push the application, assuming we’re using the default name for the Windows stack:

cf push sample-service -b binary_buildpack -s windows2012R2 -c "approot\web.cmd"

If your application does not expose a legitimate response to a GET of the root (GET /) then you’ll want to push it with –health-check-type none so PCF doesn’t think your app is crashing. Note that you have to specify the location pointing to the web.cmd file to set your start command. Your app isn’t going to start properly without that.

It would be nice if Microsoft let us supply parameters to alter the generated start command inside web.cmd, but we’ll take what we can get.

While it’s a little bit inconvenient to have to modify the web.cmd generated by the publish step, it isn’t all that difficult to push your ASP.NET 5/Core RC1 application to Pivotal Cloud Foundry on Windows cells.

Windows 8 Still Feels Like a Frankenproduct

After having used Windows 8 now for a while, I still find myself having mixed emotions about the product. This is, of course, the root of the problem because Windows 8 doesn’t feel like one product, it feels like a Frankenproduct, an unsophisticated mash-up of two entirely different products.

I used Windows 8 to play around with WinRT (what you see on all of the Windows 8 commercials) and overall I am very pleased with that experience. I love having live tiles on my desktop, I really like the new login and multi-user experience, and much more. There’s very little about WinRT that I dislike… on the surface (pun intended).

This morning, I clicked on the WinRT version of Internet Explorer (the fact that it feels like there’s two versions of IE really pisses me off as well) and tried to get connected to work via VPN. Turns out Java’s not installed and it won’t work. Also turns out that the page doesn’t even have permission to ask me if I want to enable the ActiveX control alternative to Java for the VPN. In short, nothing worked. Using the WinRT version of IE10, you cannot access the security settings responsible for ActiveX or Java.

I had to launch an app that I knew wasn’t a WinRT app (command prompt) because I can’t for the life of me remember the magic keystroke responsible for opening the desktop while I’m in the WinRT start screen. Once there, I launched the real version of IE and, after 20 more minutes of swearing and keyboard mashing, I was able to get my VPN to work.

You might say, “Well, that’s just Java for you.” This is true, Java is generally a pain in the ass in browsers. However, this isn’t just Java. This is just a sample of a much more systemic problem to Windows 8. I am constantly hunting around trying to figure out when I need to escape the WinRT façade to get something done or when I can get it done from within the WinRT façade. Those using a Surface (not Surface Pro) and some of the other WinRT devices coming out don’t have the ability to escape the façade – WinRT is all there is on those boxes.

Overall it just feels like a poor experience. There’s no clear reason why I can do one task in Win8 and cannot in WinRT versus being able to do the same task in both places. I hate the jarring experience of being immersed in the really nice WinRT experience and then being slammed into the desktop experience. The perfectly square windows with no gradient or decoration certainly comply with the new minimalist WinRT stylings, but even those feel out of place in the Win8 desktop view because in this view, people expect it to look like Windows, not WinRT.

I am not sure what the solution to the problem is. But right now, without a touch screen on my laptop, I feel hamstrung and crippled using Windows 8. I feel like I have two operating systems installed side-by-side and they keep switching to each other without warning like some kind of bad virtualization experience.

Folks who just have WinRT to deal with probably won’t feel this kind of frustration for a number of reasons. Firstly, they won’t be trying to do power user stuff like VPN from IE10 to their office, because for the most part they’ll be treating their WinRT devices like tablets, and won’t expect to be able to do that kind of thing. Using Chrome or Firefox doesn’t make it any better because those aren’t WinRT apps, they slam you into desktop mode anyway. That said, I wonder what the frustration level is going to be like on the crazy hybrid devices that flip, fold, collapse, and transform into 20 shapes and run Win8 … so those devices will see the jarring transition from WinRT to Win8 desktop… will the nature of the device make that transition any easier to take? I don’t know.

Windows 8 is quite honestly the first Windows operating system that I have felt disoriented by and frustrated with. I have a ridiculously high tolerance for tech level frustration, but I find that trying to do my normal daily stuff in Windows 8 just plain increases my stress level.

App Store Developer Experiences – Separating the Wheat from the Chaff

This weekend I spent a considerable amount of time working with Apple’s In-App Purchase system so that I could get sample code and screenshots for the In-App Purchases chapter of my upcoming book on Mac OS X Lion programming. The experience easily ranks among the most frustrating learning curves I have experienced for any technology. I read and re-read the iTunes Connect Developer Guide, read and re-read the StoreKit Programming Guide, read and re-read five or six other documents. As is typical with Apple documentation, each document provided a tiny nugget of insight hidden deep among the prose and, only upon reading each document a third or fourth time did the true “how to” information surface.

To be fair, there is a learning curve to any new development platform and it’s a foolish assumption that the App Store portion of any mobile platform should be “easy”. The problem here is that Apple consumers always assume that Apple stuff “just works” and Apple developers know better – it’s rarely that easy.

So, how painful should an App Store experience be? I feel that there needs to be some level of complexity. After all, you are participating in a supply chain where real money and real products exchange hands and this exchange needs to be secure and Apple needs to be able to weed out those who would attempt to defraud or dilute the marketplace.

What it really boils down to is this – the marketplace vendor (Apple, Microsoft, and Google, for example) has a choice when they design the interaction between developers and the marketplace. They can choose how much work they do on behalf of the developer and how much work the developer must do.

Let’s take a quick example. On Mac OS X, you must manually validate the receipts issued by the App Store. Very early in the life of the Mac App Store, Angry Birds did not validate receipts. As a result, it was possible for people to take a legitimate, purchased App Store bundle, rip out the legit receipt and replace it with the receipt for a Free application … and then the bundle could be distributed (read: pirated) outside the App Store.

This manual validation process involves using a third party command-line tool to generate ANSI C classes that rip open the PKCS file and extract individual bits and bytes from the underlying, encrypted binary data. You’re not done there. You then need to figure out how to utilize the ASN.1 code that was generated on your behalf in order to validate the receipt you find in your App’s bundle. Once you get that working, you’re going to need to modify your code further so it doesn’t look like everybody else’s code to avoid giving hackers a replacement pattern on which to search for malicious injection and hijacking (e.g. replace the return value in your “IsRecieptValid()” function to always be YES, etc).

While I am all for security, and I can certainly see the need for this level of security, what I disagree with is the fact that Apple is deferring this particular task to developers. Many developers are going to skip this process because it is maddeningly difficult to get right and it employs a skill set that many developers new to Mac OS X will simply not have (low-level C, encryption “by hand”, etc). The argument here is that it’s a necessary evil so suck it up, be a man, take your lumps, blah blah.

But does it have to be? Do we really need to go through that effort? We can’t even re-use libraries we find sitting on github because any of them with a common surface area are detectable by hackers who have access to the same code, making all our hard work completely meaningless.

I don’t know what the Android store is like but I know that the Windows Phone 7 store does not foist this kind of gruntwork requirement onto WP7 application developers. The security infrastructure takes care of this kind of thing. Hell, the security infrastructure on iOS even lets us make web calls to validate receipts, and Apple promised we could do the same for Lion but – are you going to explain to your users that you don’t know if the app is legit because you can’t communicate with iTunes? (this is why DRM-haters hate iTunes, BTW…). Windows 8’s security and signing infrastructure mirrors that of Windows Phone 7 and will not require developers to drop into generated C code to validate the legitimacy of the application – “it just works”.

So, what’s a developer to do? Nothing, of course. The potential target audience of all Mac laptop and desktops make this a necessary evil if you want to make commercial applications for Mac OS X. So we will have to suck it up and take our beating if we want to reach that target audience. The point is that we shouldn’t have to. It should be easier, it should be simpler, it should just work.

Remember: If it seems more complicated than necessary, it probably is. That said, there are times (like this) when you can’t do anything about it other than rant and rave.

WinRT Distilled

Since Microsoft showed off the features in Windows 8 at their Build conference, the internet and many office water coolers have been riddled with discussions about WinRT.. what it is, how it works, why should you use it versus something else, etc. Hopefully in this post I can provide some clarity.

First, a little history lesson: Microsoft originally wrote this thing they called the Win32 API. The Win32 API was written in C++ and littered with data types like the “lpzstr” and where developers had to do black magic tasks like “cracking messages” (it’s more benign than it sounds, honestly). We couldn’t pass big, bloated, complicated data structures around on the call stack so the use of the Win32 API was typified by the act of bundling up all your parameters to an API method into some obtuse, bit-packed “thing”, making the call, and then getting a response, which could be just as obtuse and bundled. Heaven help you if you wanted to hook into the bowels of the API so you could receive notifications and messages in your own code.

Then along came COM (yes, I’m skipping OLE and DDE for you history buffs… it’s too traumatic for me to write about). COM, which stands for Component Object Model, was an API. More than an API, it was a binary standard for allowing components written in (virtually) any language to communicate with each other. Those of us who had to write our own COM components or consume them are familiar with “DLL hell”. This is when the act of trying to make versioned components make sense on your system goes straight to hell in a handbasket. An important thing to note is that while COM provided an object-oriented, component-style layer to expose and consume functionality, the Windows UI was still very much the Win32 API.

Now we finally get to the .NET Framework, a managed runtime environment that claims to solve the problems of DLL at the same time as making UI development easier, more developer-friendly, and much more intuitive. We start with Windows Forms and eventually get technologies like XAML, WP, and Silverlight to build our user interfaces. Despite support for 64-bit and being a boatloat more powerful and complex, we’re still all sitting on top of something that strongly resembles the original Win32 API … we’re just insulated from it, and by insulated, I mean we’re sitting in a warm cozy ski lodge while the underlying API is freezing its ass off on the top of the mountain. This brings us all the way up to .NET 4.5. That’s right, .NET 4.5 is still going through a similar stack of abstractions to get to the underlying system that we go through today. This point is important.

Now we get WinRT. Contrary to popular belief, WinRT is not just a re-branding of the Windows API. It isn’t a codename for .NET 4.5. WinRT is actually a UI (among other things, including file system & device access) library written in C++. The reason I took so long getting to this point with the history lesson is this:

WinRT is the biggest single change to the Windows desktop development story since the arrival of the Win32 API.

WinRT takes many of the classes and features that we’re used to having available to us in .NET and re-writes them in native C++. Much of the .NET BCL (Base Class Library) that we take for granted has now been cleaned up and made available within WinRT – again, in native code. Rather than making us suffer through yet another poor interop layer, WinRT is also built with its own self-describing metadata. This allows Microsoft to generate C#, JavaScript, and C++ class libraries. These class libraries aren’t just cheap shunts, but rather they surface the concepts available within WinRT in ways that seem familiar and, more importantly, idiomatic, to the developers who have been working in those environments for years. When your “appx” (Silverlight devs, think “.xap” here) bundle is loaded, WinRT figures out what kind of host process is needed (an HTML engine, a CLR process, or a C++ process) and then fires up your app within the WinRT sandbox.

So, regardless of how it is implemented in the underlying WinRT C++, a collection exposed to JavaScript will look like a vector whereas it will look like a .NET collection complete with Add() and Remove() methods to a C# developer and it will look as it should in C++ as well.

So – how do you decide if you’re going to use WinRT or if you’re going to continue with the standard desktop application story? Well, in general, if you want access to the “Metro” style, then you’re going to need to use WinRT. If your application just doesn’t fit with Metro (or has a complicated UI that makes no sense to expose to touchable surfaces) then you’ll continue using standard .NET 4.5 technology.

WinRT applications have the potentially to finally give Microsoft a good mobile and slate environment. Windows CE, PocketPC, and Windows Mobile were all terrible attempts at shoehorning a desktop operating system into a mobile form factor. Windows 8, with WinRT apps and the Metro style, has the potential to give both big-monitor desktops and slates/tablets a compelling and engaging experience.

For us developers, this means 400+ million potential happy customers.

Windows 8 – As groundbreaking as Win3.1 was?

Last week in Anaheim, Microsoft debuted its new operating system, Windows 8, and much of the developer experience that goes along with it. This conference is for developers of software as well as for OEMs who work for hardware companies and even IT professionals looking to get the inside scoop on the new operating system.

I’ve been around the Microsoft developer scene since the days of DOS 4.11 (yeah that’s right, I had it on 5.25″ floppies…) and I’ve been developing for other platforms, including Unix/Linux, OS/2, and Mac, off and on for nearly as long. I am accustomed to the “OMFWTFNEW!!” feeling that developers get when they see a shiny new technology, operating system, or device. So, with that in mind, I generally take a cynical or even jaded approach when I sit through keynotes for fancy new shinies. So when I say the following, hopefully it has the right amount of impact:

I was absolutely shocked.

After watching a few keynotes and then watching a few of the deep-dive technical sessions outlining how Microsoft built some of the technology they showed in the keynote, I remember saying to a friend and colleague:

Windows 8 is to Windows 7 as Windows 3.1 was to DOS. It is that much of a paradigm shift.

Let’s look at Microsoft’s past attempts at bringing a desktop operating system to mobile devices. Windows CE and the 30 other OEM variants of CE and XP embedded, Pocket PC, and then of course Windows Mobile. All of those were attempts at shoehorning the desktop operating system into a mobile device. Windows Phone 7 was a complete re-imagining of how Microsoft wanted their users to interact with applications… Note that I said interact with applications and not interact with the OS. The Metro style is very much about getting out of your way and letting you do what you want and how you want it, with as little wasted time as possible.

Now Microsoft is using what they call a touch-first approach. A Metro-style app supports and embraces touch first, but can use the mouse as a fallback option. Swipes, gestures, and a decided lack of OS chrome, are hallmarks of this new style. Microsoft is investing heavily in touch devices of all shapes and sizes and, from the video linked below, you can see that a Windows8-based tablet is a truly compelling device (as opposed to a Windows7-based tablet, which is an overpriced electronic paperweight). In addition to the new look and feel, Microsoft is giving developers access to all Windows 8 consumers via a new App Store. If you thought the Mac OS X App Store could reach a large number of users, compare that to the number of Windows users there are…

Gizmodo’s “How Windows 8 and iOS5 stack up Side by Side” , comparing a Windows8 tablet (the developer tablet given out to Build attendees) and an iPad 2 running iOS 5.

I have plans for several more blog posts about Windows 8, including a developer discussion of what exactly WinRT is and what it means for them.

For the first time since possibly Windows 95, I am truly excited about a new Microsoft operating system, not just as a consumer but, as a developer.  That said, I’m still not giving up my Macs 🙂

WP7: Presenting ListBox Items inside a WrapPanel

This morning I was trying to figure out how to display a list of items that ran horizontally across the screen. At first I tried a StackPanel but that didn’t work the way I wanted. After a few minutes of searching I remembered that the WP7 Control Toolkit from Codeplex includes a WrapPanel control. This control does exactly what it says – it lays out the child elements and then wraps them when an element might otherwise be clipped by the edge of the screen or the edge of the parent container.

So then I tried to figure out how I could get this WrapPanel to display items from a data-bound list. This is when I remembered that I wasn’t really thinking in Xaml. I don’t want to bind the child elements of the WrapPanel, what I want to do instead is tell a ListBox that it should use the WrapPanel as a content presenter instead of the default panel that it uses.

The Xaml for this was remarkably simple:

<ListBox x:Name="myList">
<toolkit:WrapPanel ItemHeight="150" ItemWidth="150"/>
<Image Source="103-Person.png" Height="48" Width="48"
HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBlock Text="{Binding Name}" Style="{StaticResource PhoneTextSubtleStyle}"
Width="100" TextAlignment="Center"/>

When you supply this listbox with some data (in my case,  just Person objects with a Name property), it might look something like the screen below. I numbered them when setting the people’s names so you could see how the WrapPanel is laying items out horizontally and then wrapping them down to the next level.

A WrapPanel-based ListBox

A WrapPanel-based ListBox

Changing your ListBox so that it uses a WrapPanel to present items is a simple trick, but it can come in really handy and save you a lot of trouble if you want this wrapped layout style.

Apple’s GameCenter vs. Windows Phone 7 and Xbox Live

As many of you know, I’m currently writing a book to help iPhone developers (as well as non-iPhone developers) adopt the Windows Phone 7 platform called Windows Phone 7 for iPhone Developers. In the course of writing this book, I’ve discovered a lot about the Windows Phone 7 development platform and SDK that I truly love. It really is an awesome platform on which to develop mobile applications and even mobile games.

It’s mobile gaming that is at the heart of this blog post. After version 4.0 of the iOS SDK was released, Apple’s GameCenter was made available. This is an area in which iPhone users can go to see a list of GC-enabled games, find friends, see the status of their friends, and even take part in multi-player games with those friends. Additionally, GameCenter games sport global leaderboards and an unlockable achievement system. I have a few GameCenter games on my phone and, with the release of iOS 4.2, I even have a few GameCenter games on my iPad. The user’s view is that GameCenter’s feature list is incredibly similar to that of Xbox Live as implemented on WP7. However, the similarities disappear altogether when you examine the developer experience.

GameKit is the portion of the iOS SDK that revolves around gaming. Through this API, developers can access a user’s GameCenter profile. They can read to and write from global leaderboards stored somewhere within Apple. For a developer, this is as simple as configuring a leaderboard from within iTunes Connect and then setting some numeric value on the gamer’s profile. This value is compared globally and the leaderboard is computed automatically. For example, if I wanted a leaderboard for “Monster Kill Count”, I would just set the monster kill count for the current player and the leaderboard takes care of itself thanks to Apple’s infrastructure and the GameKit API.

Further, GameKit provides APIs for establishing multi-player gaming sessions with either nearby players (Bluetooth, ad hoc via the Bonjour protocol) or players scattered across the globe. The GameKit API is so easy to use, there are simple method calls for sending data to individual players or broadcasting to all of them. And if you thought that was plenty, add to this the fact that GameKit gives you the ability to, in just a few lines of code, add an overlay channel for in-game voice chat between all connected players. Now if you’re starting to get impressed, think about the fact that NONE of this requires you to stand up a back-end server to support any of this. All of this can be done for ZERO up-front cost, making this an absolute goldrush ripe for the picking for Independent developers as well as prime target for commercial games that support GameCenter features. Oh, and don’t forget the fact that the GameKit API lets you unlock achievements on a player’s profile and those achievements are defined quickly and easily by a developer through the iTunes connect portal.

So how does Xbox Live on Windows Phone 7 fare? Well, this is where the waters get muddy. Xbox Live games have at their disposal leaderboards, lobbies for finding and grouping players, APIs for multiplayer gaming, and APIs for unlockable achievements. So what’s the problem? The first problem is that right in the Marketplace list of conditions for acceptance into the application marketplace is a rule that says your Silverlight application may NEVER make any API calls to any of the core gamer libraries provided for Xbox Live. This immediately rules out casual games written using Silverlight that have multi-player, social aspects.

That’s OK you might be thinking, you’ll just use XNA to build an Xbox game using DirectX9 / Direct3D. You don’t need Silverlight and you do get a flaming truckload of high-end graphics features by going the XNA route. Here’s the rub: You can’t access the Xbox Live APIs unless you’re an approved Xbox Live partner. This means that you must e-mail Microsoft and ask to be admitted into the elite group of Xbox Live partners. Conditions for entry to this club aren’t simple, either. You must already have published an Xbox game to be considered for Xbox Live partnership. I think there are also company size requirements and possibly even a “commercial revenue” requirement. In short, if you’re an indie developer looking to use Xbox Live features, you’re hosed.

With all that said, I wouldn’t be telling the whole story if I didn’t at least explain a bit about why you’re hosed if you want XBL features in your WP7 game as an Indie developer. Xbox Live isn’t just a suite of APIs, it’s an ecosystem. This ecosystem has a currency: gamerscore. This is a point value that every single Xbox Live gamer has on their gamertag. Every Xbox Live game a gamer plays will earn them both points and unlockable achievements. These are global. This means that every XBL gamer can see which achievements you have unlocked and what your total gamer score is – it’s part of your public profile. This is the currency by which relative wealth in the Xbox Live world is measured. Those with higher game score and rarer achievements are this ecosystem’s elite… the upper class.

If an independent developer were to be given unfettered access to the ability to unlock achievements and add points to a gamer’s score, it is entirely likely (if not simply inevitable) that a well-meaning Indie developer would make a game that was too easy, with too many achievements, that awarded too many points. The simple act of a single gamer playing this game and easily racking up its thousands of points and hundreds of achievements would immediately devalue the currency of the entire ecosystem. The hard work, time, effort, and (hopefully) fun players invested in earning their gamer score and unlocking their achievements would mean little in the face of the onslaught of indie developers able to create unbalanced games that respect neither the relative difficulty in unlocking achievements nor their relative worth ecosystem-wide.

GameCenter, despite having the ability to put together players from across the globe, has no global currency. There is no continent-wide Euro with a relative worth standard like the Xbox Live gamerscore. Every game has private leaderboards. The points required to rise up on those leaderboards are not scaled relative to the time or effort required to ascend the ranks of any other game. It might take me 10,000 points to reach the top of a leaderboard in GameCenter Game “A” and only take me 1,000 points in Game “B” but Game “B” might take me 300 hours whereas Game “A” only took me 20 minutes. This type of scale disparity would ruin the value of Xbox Live gamer score but because each GameCenter game is isolated, it has no affect on global GameCenter economy. The same is true for unlockable achievements within GameCenter. GameCenter’s lack of a single, unified currency or score, gives it the ability to allow any developer unfettered access to points, leaderboards, achievements, and multi-player gaming without ruining the ecosystem.

So, in conclusion, it is my belief that until Microsoft creates a mobile, “lite” Xbox Live in which they give developers access to points, leaderboards, achievements, and mobile-isolated multi-player APIs but without access to the global gamer score value, Indie developers will be out of luck.

If anyone from Microsoft is reading this, this is my formal request for such an isolated, “lite” Xbox Live. I realize that Windows Phone 7 is a v1 product, but at least letting your customers (developers, especially Indies) know that you have plans in the works to give us an equivalent of GameCenter and GameKit would go a long way toward platform adoption by Indie developers for casual, multi-player, social games.

BTW, in case you’re curious… the top selling games on the iTunes app store, after you remove the blockbusters by companies like EA, etc, are… drumroll…. casual, multi-player, social games. Here’s to hoping that Microsoft throws us a bone in the near future, or at least something to chew on while we wait for WP7’s sandboxed Xbox Live, if such a thing will ever exist.