Contents tagged with .NET
-
JSON Serialization in .NET Core 3: Tiny Difference, Big Consequences
Recently, I migrated a web API from .NET Core 2.2 to version 3.0 (following the documentation by Microsoft). After that, the API worked fine without changes to the (WPF) client or the controller code on the server – except for one function that looked a bit like this (simplified naming, obviously):
[HttpPost] public IActionResult SetThings([FromBody] Thing[] things) { ... }
The
Thing
class has anItems
property of typeList<Item>
, theItem
class has aSubItems
property of typeList<SubItem>
.What I didn’t expect was that after the migration, all
SubItems
lists were empty, while theItems
lists contained, well, items.But it worked before! I didn’t change anything!
In fact, I didn’t touch my code, but something else changed: ASP.NET Core no longer uses Json.NET by NewtonSoft. Instead, JSON serialization is done by classes in the new System.Text.Json namespace.
The Repro
Here’s a simple .NET Core 3.0 console application for comparing .NET Core 2.2 and 3.0.
The program creates an object hierarchy, serializes it using the two different serializers, deserializes the resulting JSON and compares the results (data structure classes not shown yet for story-telling purposes):
class Program { private static Item CreateItem() { var item = new Item(); item.SubItems.Add(new SubItem()); item.SubItems.Add(new SubItem()); item.SubItems.Add(new SubItem()); item.SubItems.Add(new SubItem()); return item; } static void Main(string[] args) { var original = new Thing(); original.Items.Add(CreateItem()); original.Items.Add(CreateItem()); var json = System.Text.Json.JsonSerializer.Serialize(original); var json2 = Newtonsoft.Json.JsonConvert.SerializeObject(original); Console.WriteLine($"JSON is equal: {String.Equals(json, json2, StringComparison.Ordinal)}"); Console.WriteLine(); var instance1 = System.Text.Json.JsonSerializer.Deserialize<Thing>(json); var instance2 = Newtonsoft.Json.JsonConvert.DeserializeObject<Thing>(json); Console.WriteLine($".Items.Count: {instance1.Items.Count} (System.Text.Json)"); Console.WriteLine($".Items.Count: {instance2.Items.Count} (Json.NET)"); Console.WriteLine(); Console.WriteLine($".Items[0].SubItems.Count: {instance1.Items[0].SubItems.Count} (System.Text.Json)"); Console.WriteLine($".Items[0].SubItems.Count: {instance2.Items[0].SubItems.Count} (Json.NET)"); } }
The program writes the following output to the console:
JSON is equal: True .Items.Count: 2 (System.Text.Json) .Items.Count: 2 (Json.NET) .Items[0].SubItems.Count: 0 (System.Text.Json) .Items[0].SubItems.Count: 4 (Json.NET)
As described, the sub-items are missing after deserializing with System.Text.Json.
The Cause
Now let’s take a look at the classes for the data structures:
public class Thing { public Thing() { Items=new List<Item>(); } public List<Item> Items { get; set; } } public class Item { public Item() { SubItems = new List<SubItem>(); } public List<SubItem> SubItems { get; } } public class SubItem { }
There’s a small difference between the two list properties:
- The
Items
property of classThing
has a getter and a setter. - The
Subitems
property of classItem
only has a getter.
(I don’t even remember why one list-type property does have a setter and the other does not)
Apparently, Json.NET determines that while it cannot set the
SubItems
property directly, it can add items to the list (because the property is not null).The new deserialization in .NET Core 3.0, on the other hand, does not touch a property it cannot set.
I don’t see this as a case of “right or wrong”. The different behaviors are simply the result of different philosophies:
- Json.NET favors “it just works.”
- System.Text.Json works along the principle “if the property does not have a setter, there is probably a reason for that.”
The Takeways
- Replacing any non-trivial library “A” with another library “B” comes with a risk.
- Details. It’s always the details.
- Consistency in your code increases the chances of consistent behavior when something goes wrong.
- The
-
“Mini-DevCon” der DevGroup Göttingen/Kassel am 21.10.2016
Die .NET DevGroup Göttingen/Kassel veranstaltet am 21.10.2016 ab 17:30 in Hann. Münden-Laubach ihr 202. Treffen, das als “Mini-DevCon”, also im Prinzip eine Halbtags-Konferenz, konzipiert ist.
Es hat mich sehr gefreut, als ich in meiner Eigenschaft als Mitglied des Sprecherbüros von INETA Deutschland angefragt wurde. Ich habe gerne zugesagt und werde in meinem Vortrag praxisrelevante Grundlagen in den Bereichen Visual- und User Interface-Design sowie User Experience vermitteln.
Das Programm der Veranstaltung sieht aktuell wie folgt aus:
- 17:30 – 17:45 Begrüßung und Keynote (Joachim Bieler)
- 17:45 – 18:30 Industrie 4.0 für zuhause – IoT für Otto Normalentwickler (Martin Roppert)
- 18:45 – 19:45 Design/UI/UX-Grundlagen für Entwickler (Roland Weigelt)
- 19:45 – 21:00 Abendessen und Verlosung
- 21:00 – 21:45 PRISM 6 (Jürgen Goschke)
Die Teilnahme ist kostenlos, um Anmeldung wird gebeten.
-
SonicFileFinder 3.0 Released
My colleague Jens Schaller has released version 3.0 of his free Visual Studio extension SonicFileFinder, now with support for Visual Studio 2015.
SonicFileFinder is comparable to ReSharper’s “Go to File” feature; both let you search for files in the projects of the currently loaded solution. One of the key differences is that SonicFileFinder remembers the search term whereas in ReSharper you start from scratch each time. SonicFileFinder recreates the result list blazingly fast and if you want to enter a different search term, you can start typing immediately.
You’ll learn to love SonicFileFinder’s approach when you have several files in the result list and you don’t quite know which one may be the one you are actually looking for. You open a file e.g. by pressing Enter, see that it’s not the one you wanted, hit the hotkey (Ctrl+Shift+Y by default) again and simply choose another one from the list – without having to enter the search term again. Alternatively, you could also select multiple files and open them at once.
SonicFileFinder has a couple more nifty features; head over to the SonicFileFinder website for the complete list and some screenshots that give you a good idea what this excellent Visual Studio extension has to offer.
-
How to Create a Thumbnail for a File in Windows
Recently I had to create thumbnails for various file types and it took me some time to search the web for a solution that works and doesn’t require the discontinued Windows API Code Pack.
Daniel Peñalba‘s answer to a question titled “Extract thumbnail for any file in Windows” on StackOverflow works beautifully (tested on Windows 7 and 8.1): http://stackoverflow.com/questions/21751747/extract-thumbnail-for-any-file-in-windows .
I didn’t find it immediately because of the use of the word “Extract” instead of “Create”, so maybe I can give it some more Google juice with this blog post.
-
A C# Feature I’d Really Like to See in a Future Version
In C#, if you declare a variable somewhere inside curly braces, that variable cannot be accessed from the outside. Examples are (private) member variables inside a class, (local) variables inside functions or statement blocks in general.
What I really would like to see in a future version of C# are variables that can only be accessed within a property declaration. Then it would be possible to write something like this:
class MyClass { public string MyProperty { string _myProperty; // only accessible from within MyProperty get { DoSomething(); return _myProperty; } set { _myProperty=value; DoSomethingElse(); } } }
Looks like other people had the same idea, the feature is already suggested on UserVoice. The original author of the suggestion had a different reason for the suggestion (citing documentation requirements); the benefit that I and another commenter see is the additional encapsulation. By declaring the variable the way it is shown above, you could express the intent that the backing field isn’t intended to be accessed directly, helping other people reading the code (or yourself in a couple of weeks…).
If you agree that the feature would be a valuable addition to the C# language, it would be nice if you could vote for it on UserVoice.
-
Using Nancy to Remotely Control a Desktop Application
I recently had the requirement to control a desktop application from a mobile device. The application, written using Windows Presentation Foundation (WPF) uses the secondary monitor of a system in full-screen mode, generating views that are shown on projection screens in a sports arena. More on the background story in a later blog post. [Update: the post is now online]
When I write “control” I mean that I wanted to be able to
- see a preview of the 10-30 possible views; the views are rather static, so a static preview with a manual refresh is sufficient.
- tap a preview picture and make the application show the corresponding view on the projection screens
The “mobile device” should not be limited to a specific platform, so the least complicated solution that came to my mind was to let the desktop app host “something” that would let me open a web page in a mobile browser. The web page could show the preview pictures, tapping one of the pictures would use some JavaScript to call a specific URL (without navigating away from the web page).
So the requirements were:
- http://hostname:port/ returns the HTML for the web page
- http://hostname:port/images/filename.jpg returns a picture used by the web page
- Calling http://hostname:port/commands/show/provider/view tells the desktop application to show a specific view generated by a specific provider.
If you search the web for e.g. “wpf web server self-hosting”, you’ll sooner or later come across various recommendations, with the name Nancy popping up here and there. The Nancy framework advertises itself as follows (quote):
Nancy is a lightweight, low-ceremony, framework for building HTTP based services on .Net and Mono. The goal of the framework is to stay out of the way as much as possible and provide a super-duper-happy-path to all interactions.
In this blog post I’ll give some tips for using Nancy in the scenario I’ve outlined above, but please don’t expect ready-to-use code.
How to get Started
The Nancy website is at http://nancyfx.org/. Don’t be put off by the black background, just take a look at the small code snippet for a hint on the overall experience.
The NuGet packages you’ll need are Nancy itself (of course) and Nancy.Hosting.Self.
The next stop is the documentation; after reading the Introduction I headed straight to Self Hosting Nancy – this was looking promising enough in terms of simplicity to keep me going.
Do not ignore the section HttpListenerException, i.e. don’t stop reading at “may be thrown”, understand it as “will be thrown”. The netsh command line in the documentation is for a specific user, in my scenario I wanted anybody (in the heavily restricted network) to be able to access. In this case you’ll need the following command line (replace port with the actual port number):
netsh http add urlacl url=http://+:port/ sddl=D:(A;;GX;;;WD)
How you’ll proceed from here depends on your personal style. Combining the code snippets from the Introduction and Self Hosting pages will give you a first feeling of success with “Hello World” appearing in your browser.
General Remarks on (Learning) Nancy
The Nancy framework is simple to use, but that doesn’t mean you get around learning the basics. Two recommendations:
- If you share my feeling that the Nancy documentation has the tendency to dive into the specifics a bit too fast (which later may be great, usually framework docs are too shallow), read the article “Understanding Nancy – Sinatra for .Net”. I found it very helpful because it explains the core terms in a very concise way.
- Not a groundbreaking insight, but true nevertheless: If you learn a new framework, set breakpoints everywhere to learn the life cycle. It is especially important to know what gets instantiated when and how often.
Some Remarks on Self-Hosting in an Existing Application
- I had trouble getting the Razor view engine to work, searching the web I had the feeling that I’m not alone. I didn’t dig much deeper as the “Super Simple View Engine” does everything I needed.
- When you self-host in a desktop application and want an incoming call of a URL to have an effect on the GUI, keep in mind that the GUI can only be updated from the UI thread. In the case of WPF, you’ll have to use on the Dispatcher.BeginInvoke pattern, e.g.
Application.Current.Dispatcher.BeginInvoke((Action) (()=> { // Update UI }));
- My application uses the Managed Extensibility Framework (MEF) and I needed a specific application service (IRemoteAccess) inside a Nancy module. The “Nancy-way” to pass something to a Nancy module (that is instantiated for each request) is to use dependency injection (DI) via a constructor parameter. Nancy uses an IoC container called TinyIoC for DI and bridging the world of MEF and TinyIoC isn’t complicated. If you use Nancy, you’ll sooner or later have a “bootstrapper” class that is used for tweaking things in Nancy – that’s where you can e.g. put stuff you’ll need later into the TinyIoC container:
public class RemoteAccessBootstrapper : DefaultNancyBootstrapper { public static CompositionContainer MefContainer { get; set; } protected override void ApplicationStartup(TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines) { // …
container.Register(MefContainer.GetExportedValue<IRemoteAccess>()); } // ... }
The Web Client
The project was a spontaneous idea with a very tight deadline, so the “client” is a single static web page. Tapping on one of the preview pictures is supposed to access a specific URL without navigating away from the page. In the spirit of “the simplest thing that could possible work” I used the following bit of JavaScript code I found on StackOverflow:
function show(provider, view) { var i = document.createElement("img"); i.src = "commands/show/" + provider + "/" + view; }
Over the summer the client will be rewritten completely as a single page application, inspired by the article “AngularJs, NancyFx, TypeScript, and BootStrap Oh My!”. The goal is to include more sophisticated features in the client and have learn new technology along the way.
Final Verdict
In the short time I had available I didn’t do thorough research what could be the best solution to my problem, but what I can say is that Nancy did its job well enough I can recommend it – at least for this specific scenario.
Nancy kept the promise of simplicity, but at the same time I always had the feeling whenever I needed “more”, there was a way for me to customize / tweak it without jumping through hoops.
Nice one!
-
Anmeldung zur dotnet Cologne 2013 ab 21.3.2013 um 12:00
Die dotnet Cologne, organisiert von Bonn-to-Code.Net und der .net user group Köln ist, schaltet am 21.3.2013 um 12:00 die Anmeldung frei.
Das Anlegen oder Aktualisieren von Accounts (von früheren Konferenzen oder Kölner User-Treffen) ist bereits jetzt möglich und auch sehr zu empfehlen. Denn erfahrungsgemäß sind die Tickets mit Frühbucherrabatt (für die ersten 200 Plätze) heiß begehrt, da zählt jede Sekunde.
Die mit 350 Teilnehmern mittlerweile größte deutsche .NET Community-Konferenz findet zum fünften Mal statt, Veranstaltungsort ist das Komed im Mediapark Köln.
Wir – das sind Melanie Eibl, Stefan Lange, Albert Weinert und ich – freuen uns sehr, ein volles Programm mit Rundum-Sorglos-Paket bieten zu können.
30 Sessions auf 6 Tracks, ein kleines Frühstück, Mittagessen, Kuchen am Nachmittag, Kaffee und Softdrinks den ganzen Tag über, freies WLAN - und das wieder zu absolut fairen Preisen:
Für Privatpersonen
- 25€ im Super-Early-Bird
- 40€ im Early-Bird
- 55€ regulär
(Preise inkl. MwSt., Zahlung per Vorkasse, Rechnung nach Zahlungseingang, ausgestellt auf die Privatadresse, ohne Nennung eines Firmennamens)
Für Firmen/Firmenangehörige auf Rechnung
- 75€ (zzgl. MwSt.)
Für die Firmenanmeldung gilt:
- Die Bezahlung geschieht auf Rechnung (die automatisch nach der Anmeldung verschickt wird)
- Die Anmeldung kann auch eine Kontaktperson vornehmen, die selbst nicht an der Konferenz teilnimmt
- Mehrere Teilnehmer können auf einmal angemeldet werden
- Last but not least: Der Firmenname erscheint auf den Teilnehmerausweisen, eine gute Gelegenheit “Flagge zu zeigen”
Termin merken und weitersagen: 21.3.2013 um 12:00
Alle Informationen zur Konferenz gibt es auf www.dotnet-cologne.de.
-
dotnet Cologne 2013 – Vorträge gesucht!
Am 3. Mai 2013 findet im Mediapark Köln die dotnet Cologne 2013 statt. Damit die mittlerweile fünfte Ausgabe dieser Community-Konferenz wieder ein solcher Erfolg wie in den Vorjahren wird, suchen wir (Stefan Lange, Melanie Eibl, Albert Weinert und ich) Sprecher mit interessanten Vorträgen zu Technologien aus dem Microsoft-Umfeld.
Dabei wünschen wir uns sowohl Einführungsvorträge in neue Themen als auch die eine oder andere “Level 400 Hardcore-Session” für Spezialisten. Für beides sind passende Räume im Komed vorhanden, das auch in diesem Jahr wieder Veranstaltungsort sein wird.
Alle Infos zum Call for Papers gibt es hier.
Über die dotnet Cologne
Die dotnet Cologne, die 2009 zum ersten Mal stattfand, hat sich im Laufe der Jahre mit mittlerweile 350 Teilnehmern zur größten .NET Community-Konferenz in Deutschland entwickelt. Veranstaltet von den .NET User Groups Bonn-to-Code.Net und .net user group Köln, versteht sich die dotnet Cologne als Konferenz von Entwicklern für Entwickler. -
Html Agility Pack for Reading “Real World” HTML
In an ideal world, all data you need from the web would be available via well-designed services. In the real world you sometimes have to scrape the data off a web page. Ugly, dirty – but if you really want that data, you have no choice.
Just don’t write (yet another) HTML parser.
I stumbled across the Html Agility Pack (HAP) a long time ago, but just now had the need for a robust way to read HTML.
A quote from the website:
This is an agile HTML parser that builds a read/write DOM and supports plain XPATH or XSLT (you actually don't HAVE to understand XPATH nor XSLT to use it, don't worry...). It is a .NET code library that allows you to parse "out of the web" HTML files. The parser is very tolerant with "real world" malformed HTML. The object model is very similar to what proposes System.Xml, but for HTML documents (or streams).
Using the HAP was a simple matter of getting the Nuget package, taking a look at the example and dusting off some of my XPath knowledge from years ago.
The documentation on the Codeplex site is non-existing, but if you’ve queried a DOM or used XPath or XSLT before you shouldn’t have problems finding your way around using Intellisense (ReSharper tip: Press Ctrl+Shift+F1 on class members for reading the full doc comments).
-
Looking Back at BUILD
BUILD, the “everything is secret”, “no information until September” conference is over and I’m back at home. Time for a personal look back.
The Announcements
Others have already done the job of writing a full roundup (here is one of the many), so I will give you only the the short version from a developer’s perspective:
- Windows 8 offers a new kind of applications with a new UI (“Metro”), running on top of the new Windows Runtime (“WinRT”).
- WinRT was developed with an emphasis on performance, both real (it is written in native code) and perceived (all API calls taking longer than 50ms are designed to be called asynchronously).
- “Metro style apps” can be developed in C++, C# or JavaScript
- C++ and C# applications use a XAML based UI technology, similar to Silverlight, but with higher performance and built-in touch support.
- JavaScript applications use HTML5 and CSS for their UIs.
- Windows 8 still allows “classic” desktop applications, developing these is not different from developing for Windows 7.
The bottom line: A wide range of developers will feel at home writing Metro style applications. That wasn’t all that clear after the messages from the unveiling of Windows 8 at the D9 conference in June, where it was all about HTML5 and JavaScript – which made many .NET developers mad. And shutting down all channels of information until September didn’t really help making the situation any better.
Was the intended effect of unveiling of WinRT as a surprise (i.e. “pulling an Apple”) really worth yet another Microsoft PR disaster? In a world where perception often is as important as reality, Microsoft PR really should put a bit more thought into what is said publicly and how people could react to it.
What about Silverlight?
The future of Silverlight after the release of version 5 later this year remains unclear. Sure, Silverlight applications won’t magically stop working in e.g. Windows 7. And it could be that Silverlight 5 is “good enough” for years to come. But there’s already the hint of a limited life time inside the Windows 8 Metro UI with its plugin-less Internet Explorer (the desktop version will allow Silverlight to run, though).
For business applications, an area where Silverlight really shines (forgive the pun), Metro style applications are not an alternative yet. Currently all Metro style apps will have to go through Microsoft’s app store, which in many situations simply isn’t acceptable. At some point in the future Microsoft will have to offer a solution for business applications with some kind of private app store, similar to what Apple already has.
The Sessions
As I’m very interested in UI/UX, I attended the user experience sessions regarding the design principles behind the Metro UI, which I enjoyed very much. I can highly recommend this and this session.
The technical sessions on the other hand were a mixed bag. Some of the “I’ll show you how to build X” talks that I saw were rather light on content, with the title promising more depth than was actually shown. There’s nothing wrong with introductory content, but the usual labeling of sessions from “level 100” to “level 400” was sorely missing. And please refrain from the term “deep dive” if your session merely gets people’s toes wet.
Not publishing the agenda before the conference prevented people from planning their personal schedule e.g in an online application, which in turn meant that Microsoft had no data for planning the required session rooms. The result: too many sessions ended up in rooms that were way too small and many people could not see the sessions they wanted. Unlike earlier PDCs, BUILD did not offer any overflow rooms.
Sure, the sessions were available on video the next day, but an important reason for attending a session in person is to be able to discuss the topics with other people afterwards.
The Location
The Anaheim Convention Center is a very typical conference location (i.e. at some point they all look the same). And because of that, two very typical problems came up:
- The chairs are designed for skinny female super models, not laptop-wielding IT guys
- The air condition is just too much for a European like me.
The handling of many thousand people is something that “just works” at developer conferences in the US (at least at the ones I have been to in the last 13 years). Congratulations to the BUILD organizers and their staff for having done a good job at directing the masses when giving out the slates, feeding the hungry and keeping the fridges full of soft drinks at all times .
The Slate
As mentioned above, attendees received a slate PC with a preview build of Windows 8. The machine is not actually an iPad killer, but this giveaway is not about providing people with a free toy to play around. This is a developer machine for giving attendees the opportunity to develop and test Windows 8 applications.
The slate has an Intel x86 processor and is able to run “classic” Windows apps. This makes the machine run hot (it has a fan) and, I guess, also heavy. Things will look different on an ARM CPU, but it remains to be seen whether anybody will be able to come near Apple’s iPad from a hardware point of view.
My Personal Takeaways
The following list is by no means complete:
- I’m impressed by the work on performance in Windows 8.
- WinRT is a major step forward in many ways.
- We’re in a transition period which will take many years.
- The ongoing work on C# is impressive. I really like how Anders Hejlsberg and his team approaches things, thinks about the consequences and continuously improves the language and its compiler.
- Microsoft really gets the importance of good UX. This does not necessarily translate into great UX in Metro, though, which at some points doesn’t feel quite natural yet. But they are heading in the right direction.
- I’m disappointed by the lack of communication regarding Silverlight.
- My development skills in C# and XAML will be still valuable in the future.
- My skepticism towards “HTML5 + JS + CSS” (disclaimer: I have written large amounts of JavaScript in my life) wasn’t helped by the fact that one problem during a demo was caused by a simple typo that a compiler would have caught.
- During the Ask the Experts I learned that the common Metro controls are actually not a fine example for the power of HTML5. Many calls to WinRT are necessary behind the scenes to achieve the performance or fully support touch. I don’t have a problem with that, people just shouldn’t look at the UI and think “who needs anything else besides HTML5, JS”.
- I really like the concepts for interoperability between applications e.g. via contracts.
- The pooled storage feature of Windows Server 8 (pool of storage space across multiple hard drives) looks like something that could bring back the Drive Extender feature to a future version of Windows Home Server.
The following months and years are definitely going to be interesting!