Finnish municipalities list published in OData!
In an attempt to contribute something back to the community, Offbeat Solutions has published a list of Finnish municipalities, regions, electoral districts and whatnot. And of course, in the modern spirit, using the OData protocol.
Check out the actual material at http://www.offbeat.fi/kunnat.aspx. The description of the data is only available in Finnish, but the data structures themselves are in English – you can also browse yourself just into the OData endpoint.
In case you can read Finnish and are in need of an OData tutorial, there are three new ones available on the ITpro.fi site:
Enjoy!
January 14, 2011
·
Jouni Heikniemi ·
No Comments
Tags: OData · Posted in: .NET
NullReferenceException from NHibernate in a WCF Service
Don’t you hate it when you get an NullReferenceException? NHibernate 2.1.2 throws one if you have an WCF Service that accesses the NHibernate context. If you get one from NHibernate.Context.WebSessionContext.GetMap(), read on…
It’s really simple but easy to forget – NHibernate’s web session models requires you to have HttpContext available. That particular mentioned method calls HttpContext.Current.Items[…], causing a NullReferenceException when the HttpContext.Current returns null. Quite logical, but since you rarely call WebSessionContext directly, it’s also easy to miss.
The fix is a very straightforward one: Make your service run in ASP.NET Compatibility mode. As described in MSDN article on WCF and ASP.NET coexistence, WCF services have their own processing pipeline, and also have a null HttpContext. However, you can coerce your WCF requests into the ASP.NET Model by enabling compatibility mode. You do this by tagging your service class with an attribute:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)] public class MyService : DataService<MyDataSource>
Once done, your service should execute fine. However, you might also get an InvalidOperationException with the following message:
The service cannot be activated because it requires ASP.NET compatibility. ASP.NET compatibility is not enabled for this application. Either enable ASP.NET compatibility in web.config or set the AspNetCompatibilityRequirementsAttribute.AspNetCompatibilityRequirementsMode property to a value other than Required.
This would indicate a need to add the following to your web.config:
<system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="false" /> </system.serviceModel>
Hopefully this will then finally get you back on the track. ![]()
December 21, 2010
·
Jouni Heikniemi ·
No Comments
Tags: ASP.NET, NHibernate, WCF · Posted in: .NET
Razor + Visual Studio bug: don’t paste whitespace in code
Just a quick note of a bug my wife discovered when working with some Razor code.
If you have ASP.NET MVC 3 Release Candidate installed, you can trigger this. Take a spot where your view file has a C# expression (such as @View.Title), and paste some code after that expression. An example of the code might be “.Trim(' ')”.
Pasting that would have you expect a result of @View.Title.Trim(' '), but instead you end up with @View.Title '').Trim('.
The problem is that pasting a C# segment with whitespace in it causes Visual Studio to mutilate the code strangely. This is particularly apparent when pasting heavy method calls with spaces between arguments. Well, yet another reason to avoid code in your Razor files!
The Razor team confirmed via email that this is a bug in the Release Candidate and will be fixed in RTM.
November 30, 2010
·
Jouni Heikniemi ·
No Comments
Tags: Razor · Posted in: .NET, Web
SANKO meeting on ORM tools, 2010-11-24
Finnish .NET Users Group SANKO will be meeting on 24th November in Leppävaara, Espoo, Finland in order to discuss the concept and details of object-relation mapping. In case you live in the Greater Helsinki Area, check this out!
The agenda is as follows (all sessions in Finnish):
13:00 – 13:15
Welcome & What’s this SANKO? / Jouni Heikniemi
13:15 – 14:00
Introduction to OR mapping: What and why? / Sami Poimala
14:00 – 15:00
Entity Framework 4 / Pasi Taive
15:00 – 15:15
Break
15:15 – 16:00
ORM under the covers – a deep dive on NHibernate / Lauri Kotilainen
16:00 – 17:00
Panel Discussion: Most common problems & the best practices for solving them
If you’re interested, register before Monday via the Microsoft site. On behalf of the SANKO team, welcome!
November 19, 2010
·
Jouni Heikniemi ·
No Comments
Tags: SANKO · Posted in: .NET
Outputting partial elements with ASP.NET Razor
The new ASP.NET MVC 3 also ships with a totally new option for a view engine, Razor. I’ve now been using Razor in a project for couple of months, and yeah, it’s good – but not entirely without problems. Here I’ll cover one of them.
Imagine a scenario where you’re outputting something that may or may not be a link, depending on the conditions. You’d be tempted to write something like this:
@if(linkUri != null) { <a href='@linkUri'> } Some text @if(linkUri != null) { </a> }
… only to find out that it doesn’t work. The error message you’ll be getting is probably “The if block is missing a closing "}" character. Make sure you have a matching "}" character for all the "{" characters within this block, and that none of the "}" characters are being interpreted as markup.” Alternatively, you could get “The foreach block is missing a closing “}”…” or something similar, depending on your enclosing elements.
That’s not really enlightening, and it turns out Razor is smarter than you’d think – and as usual, smart software has a flip side.
You could just balance yourself…
Razor is intended to be written with elements fully enclosed within the C# blocks. Therefore, you might rewrite this as:
@if(linkUri != null) { <a href='@linkUri'>Some text</a> } else { <text>Some text</text> }
However, such an approach repeats “Some text”, which may be a lengthy expression or even an entire block of HTML, making this rather clumsy. Note that you need the <text>…</text> element to ensure that the else block content gets parsed as HTML instead of C# – the text element will not be present in the resulting HTML, and would be unnecessary if you had any actual tags in there.
Another workaround would be to use the WriteLiteral method and enclose the tags in C# strings, disabling Razor’s parsing logic:
@if(linkUri != null) { WriteLiteral("<a href='" + linkUri + "'>"); } Some text @if(linkUri != null) { WriteLiteral("</a>"); }
… but what you really want is @:
Of course, this is a common enough scenario to warrant a syntactic helper. It’s called @:, and it means that the following line is markup, no matter what tags occur. This allows the logic to be written as follows:
@if(linkUri != null) { @:<a href='@linkUri'> } Some text @if(linkUri != null) { @:</a> }
Unfortunately, as you can see, the @: has a line scope and thus necessitates a few additional line feeds. Despite that, this is rather readable and scales well to complex instances of “Some text”.
Thanks to Andrew Nurse at the Razor team for helping me out with this!
November 17, 2010
·
Jouni Heikniemi ·
One Comment
Tags: ASP.NET MVC, Razor · Posted in: .NET, Web
Keeping ASP.NET MVC action method argument names separate from the query
ASP.NET MVC does a wonderful job of automatically routing and binding your HTTP request data to the action method. But what if you don’t want to use the same argument names in your routes (for example, query strings) and your methods?
There are a few typical scenarios where you might encounter this.
First, if you’re aiming for absolute shortness in URIs, you’ll end up using querystring arguments like “q”, “aqi” etc. (examples from Google). Such names wouldn’t work well in method names, which have more value in being readable.
Second, if your source code and URIs are in a different language, you might end up with a scenario where you have arguments like ?nimi=5, but not wanting to pollute your code with Finnish, you’d want to translate over to “name” (the same in English).
Third, your query string parameters might have names that are downright uncomfortable to use in programming language of your choice. Typical examples in C# include for, in, class and case. Although you can prefix the names with @ sign to escape the reserved words, it’s a bit clumsy.
BindAttribute to the rescue!
There is actually a very good solution to this: You can specify the name of the field to bind to via an attribute. It’s just a bit confusing: You set the name to a field called “Prefix”, although it is actually the full name of the field. Here you go:
- public ActionResult Index
- Â Â Â Â ([Bind(Prefix = "string")]string text, [Bind(Prefix="integer")]int number)
- {
- Â Â Â Â return Content(text + ", " + number);
- }
Now you can access this page with an URI like /?string=foo&integer=42, and the resulting output will be “foo, 42”.
November 15, 2010
·
Jouni Heikniemi ·
4 Comments
Tags: ASP.NET MVC · Posted in: .NET, Web
It takes ten megs to represent three leds
15 years ago we were really struggling with memory problems. Machines typically had 4 megabytes of RAM. And keyboards still had lights for Num lock, Scroll lock and Caps lock. Wait, how are these connected?
![]()
See, my modern Lenovo W510 has dispensed with the leds on the keyboard (well, we still have one for Caps lock). Good riddance, I didn’t really need them.
But hey! They have been replaced with an on-screen display. When I hit Scroll lock, I get a great visual reminder of the state popping up at the lower-right corner of my screen. And toggling the lock back off, I see yet another grandious display of graphical goodness.
You know, these things come with a cost. Looking at the task manager, I spot these two processes specifically dedicated for this purpose.
Looking at this, I realize that those three pesky leds actually take a bit over 2.2 megabytes of memory. And it doesn’t end there. See, both those processes have three threads (hence the “3”), each with a one megabyte stack. Added together with all the other overhead, the nasty indicators slice away almost ten megs of my RAM.
Counting all this together, we are left with the rather stunning conclusion: The leds were replaced with something that consumes twice the typical memory capacity of an early 90s home PC. Oh, and did I mention that the new one is worse, too: The graphical indicator isn’t drawn on top of full-screen applications, nor does it work when a Windows application declares itself “Always on top”.
So much for evolution on this front.
PS. I know the memory calculations are somewhat inaccurate with this little information, but I believe the figures to be sufficiently correct to post this. Feel free to post further details if you bother Process Exploring.
November 10, 2010
·
Jouni Heikniemi ·
3 Comments
Posted in: General
New guidance: No more Silverlight for the web?
Microsoft sparked quite a controversy when Bob Muglia stated in an ZDnet interview that their “Strategy had changed” regarding Silverlight’s position, and HTML5 was the future way to go. In this post, I look at the whole debacle’s effect on future technology recommendations.
While this has now been explained by Bob Muglia, Steve Ballmer and Scott Guthrie, all reassuring that Microsoft really views Silverlight as a strategic technology, some things are still left dangling. Of course, none of this was helped by Bing Maps visibly stepping back from Silverlight at the same time.
Of course, everything posted here is my opinion and has nothing to do with Microsoft’s truth.
It’s really XAML vs. HTML, and XAML lives beyond the web
We’ve seen for years that WPF and Silverlight are on a collision course. The two platforms are already reasonably close feature-wise, and the approach seems to be continuing. While full-blown WPF apps will certainly have features beyond Silverlight and Silverlight will have platform qualities unlike the libraryish WPF, these are all really rather insignificant factors. There will be one XAML platform, with one developer competence broadly sufficient for both.
How is this relevant? It is, because XAML has a far broader impact than HTML5. Even with Ray’s Post-PC vision, the full-blown PC is here for at least another ten years. If you want to build a rich UI on one of those still most dominant forms of electronic devices in the world, you will use the XAML stack.
Whether or not the XAML stack will reach devices beyond the desktop PC is a good question. Microsoft Surface is an example of potential direction of expansion, yet Microsoft isn’t exactly poised to conquer the OS market for all slim touch-based household devices. But they have now demonstrated the viability of Silverlight on the Windows Phone 7, so I wouldn’t count them out yet.
HTML 5 was always going to win on the web
Silverlight was an effort to speed up the creation of richer internet application at a time when browser capabilities were not sufficient for application development (certainly because of IE, to an extent). Mind you, it was successful at that: It brought onboard a whole slew of developers previously new to the RIA scene.
An even battle with HTML 5 was never particularly realistic. The W3C process and browser evolution is slow, and Silverlight filled a gap. But just like with CSS, once the spec is actually implementable, the W3C-driven standard is in a position to grab the market, largely because its creation was so heavily driven by vendor consensus.
Given the annoyance towards Flash that had lasted for years, how likely was it ever for another plugin, especially by Microsoft, to replace it?
It is extremely important that Redmondians embrace the HTML5 world. It keeps Microsoft-driven web development relevant – because no, Microsoft won’t control the next generation of device platforms, and yes, we as Microsoft technology developers need to be able to address the wider audience. There’s no way Microsoft would get Silverlight onto all those devices!
The XAML stack still has a role
But even with all the drive HTML 5 has, it doesn’t render everything else obsolete. In fact, the XAML stack has certain great advantages on its side:
- The developer toolset for WPF/Silverlight is far more mature than for HTML5. Although HTML5 tooling is advancing in leaps, it still consists more of separate libraries compared to the relatively unified developer experience Microsoft provides.
- The data connectivity between Silverlight and the server is far stronger than it is between HTML5 and a server. Although protocols like OData are becoming more common and JSON serialization is now a part of every respectable programming Framework, a data framework of RIA Services’ caliber and LINQ’s syntax is a luxury HTML5 developers don’t have.
- Silverlight still has features that beat the HTML5 equivalents. In particular, support for touch, offline mode and various media replay features far exceed what HTML5 has to offer at this time.
When to pick which?
My recommendations:
- For business apps with need for added richness and web deployment, use Silverlight.
- For rich “desktop” apps designed for maximum experience on a certain device, of course including Windows Phone 7, use Silverlight.
- For broad reach consumer apps, default to HTML5.
- If very high-fidelity media replay or similar features are required, sprinkle islands of Flash or Silverlight into the mix.
- If your app needs maximum accessibility and search engine visibility, play safe with HTML5.
- If your app would benefit more from the strong points of the XAML stack as listed above, consider using Silverlight.
- Gauge the competence of your existing developers. While a Windows Forms business app developer is not ready to just jump into a Silverlight project, the knowledge gap for jumping into an HTML5 endeavor is even wider.
- With HTML5, developer productivity increases considerably during the next few years. With Silverlight, developer experience is already considerably more mature.
Remember: Although HTML5 is likely to outlive Silverlight, it doesn’t mean Silverlight will die before your application is naturally obsolete. Do balance the short- and long-term benefits for your specific scenario.
November 5, 2010
·
Jouni Heikniemi ·
3 Comments
Tags: HTML5, Silverlight · Posted in: .NET, Web
Ray Ozzie’s Dawn of a New Day condensed
Microsoft’s soon to be ex-Chief Software Architect Ray Ozzie is a great thinker. But he’s also very, very verbose, and his latest 3500-word memo called Dawn of a New Day is quite a bit to digest. Here’s my summary of it (plus a few comments).
First, Ozzie iterates things that have changed since his Internet Services Disruption memo five years ago. He claims that Microsoft has truly taken services seriously: the “all in” cloud mantra is actually reality. He feels that the Software + Services ideology is successfully demonstrated by Windows Live, Office 365 and Xbox Live. He also points out that Microsoft has succeeded in staying relevant with concerns such as low-cost notebooks, virtualization and increased openness particularly in the Office space.
Then, he goes on to list a bunch of changes for the last five years, mostly focusing on drastically increased connectivity and the hardware evolution that has brought computing to entirely new form factors. Also, he identifies mobile, “seamless fusion of hardware & software & services” and social media as fields where Microsoft has lost ground to its competitors. After that, it’s time to start threatening.
The Post-PC era
Ray reminds us that it’s almost 25 years from the launch of Windows 1.0. Windows, with all its problems, was iconic for bringing Personal Computers onto every desk. But Ozzie predicts that while we feel personal computing so strongly connected with the notion of current PCs, they must go. The complexity of hardware, software and data management “sucks the life out of users, developers and IT" – or in other words, “Fragility can grow to constrain agaility”.
Ozzie challenges Microsoft to stop and envision a world after the personal computer. He then postulates a future based on continuous services (applications and agents continously available on an unlimited scale) and connected devices (more appliance-like, ready-to-use when unwrapped, easily replaceable, with unlimited cloud-based storage and data capabilities).
He then goes on to paint a picture where these elements – the services and new kinds of devices – work together to solve quite a few utopian challenges on various fronts of society (from collaboration to health care, transportation to security and so on). He deduces that the next computing revolution must start from the point of simplicity, from natural device and media independence. Instead, applications will be centered on your data and social networks.
Finally, he urges Microsoft to once more embrace the unknown and emerge as a winner.
My view on Ray’s view
Given the number of referrals Dawn of a New Day has received, I would have expected it to be a more drastic memo. Coming from the guy who championed Live Mesh (which in its original PDC 2008 form was actually a rather relevant component of this vision!), the picture that DoaND painted wasn’t really a new one.
That said, it’s not a bad wake-up call… But it’s a reasonable theoretical one. Yet I admit it’s a hard problem: Thinking about and planning for the next revolution is, by definition, a challenging task. If I had to name a single task that would prepare anyone, not just Microsoft, for the future Ray envisioned, it would be this:
Develop cloud-backed applications and business for smartphones.
Not only will it make you face the technological limitations of smaller form factors, it will also bring experience of all the problems related to people actually using services on the go, micropayments, frequent device updates and so on. While that’s not the whole picture of Ray’s vision, it’s perhaps the most reachable, most practical training ground available today.
November 1, 2010
·
Jouni Heikniemi ·
One Comment
Tags: future, strategy · Posted in: General
Devs vs. IT pros: Who runs all these Azure apps?
Last night’s PDC10 keynote sparked a few ideas overnight. One of them is a concern regarding the IT professionals’ role in running Windows Azure based software.
This idea was born of the fact that PDC, traditionally and so statedly a Developer conference, announced technology that was reasonably deep in the IT Professional space. I mean, seriously: Server application virtualization. I have a hard time finding developers who have even heard of client side App-V! Going on, we had private networking and whatnot.
Don’t get me wrong. I agree developers need to know about this technology. What concerns me is the role of IT professionals, the people who traditionally have taken a software package and deployed it. Everybody’s running around with all kinds of Azure features launched, but who’s here to educate the IT professionals on them?
The role of an admin
With Azure, the developer role is pushed quite far into the operations direction. In recent PDCs and TechEds, developers are educated on how to configure the scale, security, logging and diagnostics of Azure applications. When these applications go live, does IT magically take the responsibility of managing the deployed solution for the rest of its life cycle?
For small applications, devs have always maintained the software they built. But for those more enterprisey scenarios, developers usually ship semi-packaged software that gets installed by somebody else. With Azure, developers could quite well just publish the .cspkg files and have somebody else deploy and manage them. So the technical separation is there, but can we do this in practice?
Look at TechEd Europe 2010 session list (pick Cloud from the track filter). While some of the sessions are suitable for all audiences, most have “for developers” in their title, and exactly one, COS210, is titled “An IT Pro view of Windows Azure”. The same pattern repeats itself in most of Azure content available.
So what?
Personally, I think cloud has a lot of potential exactly for IT professionals – and yes, many of them are very interested and involved in things such as Office 365, Windows Intune and whatnot. But those are the SaaS offerings – the infrastructure and platform layers are left with much less attention. For custom software, the knowledge of these layers make or break the deal.
I fear that lack of Azure skills among IT pros can reduce the enthusiasm for cloud adoption in enterprise organizations. This may lead to software getting developed for on-premise deployment where cloud would actually make more sense, or alternatively, apps being developed for the cloud but then left without proper care. Neither of these scenarios is particularly beneficial for the future.
Things will change for the better as time passes. Until then, this is an excellent opportunity for cloud-aware developers to build relations with their favorite IT pros, facilitating discussion about the future in preparation of the moment when the world fully realizes that despite all the great abstraction and serviceness, Azure is not just a developer thing.
October 29, 2010
·
Jouni Heikniemi ·
2 Comments
Tags: Azure · Posted in: Cloud, Windows IT
