Monday, October 31, 2016

ReactiveList: ObservableCollection on steroids

If you ever build an MVVM style application before(using WPF, Silverlight, UWP,…) you probably used the ObservableCollection class.  It implements the INotifyCollectionChanged interface and can be seen as the counterpart of INotifyPropertyChanged. Through this interface the ObservableCollection notifies its subscribers about items being added, deleted, moved, …

Unfortunately the ObservableCollection is rather limited in it’s behavior and doesn’t fit well in a truely observable architecture. Luckily the ReactiveUI framework and more specificly the ReactiveList solve exactly this problem…

image

Let’s describe a scenario I had to build that was hard to do using ObservableCollection and a walk-in-the-park with ReactiveList:

In our application we have to show a list of alerts and update the list when new alerts arrive. However alerts can arrive at a high pace and we don’t want to update the UI continuously but only when at least 5 alerts are raised.

In our original implementation we used a pull based mechanism combined with a timer to load the alerts every 30 seconds from the database.  Let’s see how easy it is to do the same thing with ReactiveList without having to fallback to polling and storing all data:

Friday, October 28, 2016

Over-Engineering: The curse of a software architect

We as software developers love technology, especially new and shiny stuff. When it comes to building software we always want to play with the latest tool, technology and architecture of the day. And for a part that’s OK, as it drives innovation and creates new opportunities but for a part it is not as we have a tendency to over-engineer and try to stuff as many of these new and shiny things into our pour software projects.

overengineering1

“Don’t over-engineer” is a golden rule that we all should apply.

overengineering2

A great post that perfectly relates to this sentiment is “10 Modern Software Over-Engineering Mistakes”, a must read!

Thursday, October 27, 2016

Get a headstart when building ASP.NET Core+Angular 2 applications

If you already tried to create your first Angular 2 application, you probably had the same experience as I had. It takes a lot of time before all building blocks, configuration settings, npm packages, webpack, system.js,… is finally configured in a way that works. Once you’ve passed this initial roadblock, you are good to go, but it will take some time to get there…

Luckily Mads Kristensen, the guy who brought us the great Web Essentials extensions for Visual Studio, created the ASP.NET Core Template Pack. It is a collection of project templates that makes it easy to learn how to use ASP.NET Core.

Among the templates you can find one specific for ASP.NET Core and Angular 2.

Let’s try it!

  • Download and install the ASP.NET Core Template Pack either from the Visual Studio Gallery or through the Extensions and Updates… inside Visual Studio.
  • Open Visual Studio. Go to File –> New Project.

image

  • Go to the Web section inside the Templates. Choose ASP.NET Core Angular 2 Starter Application from the list of templates. Click OK.

image

  • 10 seconds later, we have our preconfigured Angular 2 application ready to roll! No time lost, trying to understand which packages are required or to how to configure webpack.

 image

  • And if we run it we see that we get some extra goodies:
    • Server-side prerendering. For faster initial loading and improved SEO, your Angular 2 app is prerendered on the server. The resulting HTML is then transferred to the browser where a client-side copy of the app takes over.
    • Webpack dev middleware. In development mode, there's no need to run the webpack build tool. Your client-side resources are dynamically built on demand. Updates are available as soon as you modify any file.
    • Hot module replacement. In development mode, you don't even need to reload the page after making most changes. Within seconds of saving changes to files, your Angular 2 app will be rebuilt and a new instance injected is into the page.
    • Efficient production builds. In production mode, development-time features are disabled, and the webpack build tool produces minified static CSS and JavaScript files.

Nice!

image

Wednesday, October 26, 2016

ASP.NET MVC–WIF authentication pipeline is not invoked

After configuring my ASP.NET MVC application to use WSFederation with WIF, I was finally ready to run the app the first time. However instead of redirecting me to the configured STS and showing me a login page I ended up with a 401 Unauthorized error page.

I first thought that the required HTTP modules were missing, but no they were there:

Let’s have a look at the WIF configuration:

There is definetely something wrong here, but I had a hard time figuring out what. The problem is related to the passiveRedirectEnabled configuration setting. If you set passiveRedirectEnabled to false, WIF will no longer be responsible for the redirections to your issuers.

That explained a lot! Switching the setting to true solved my issue and I was finally welcomed by my STS login page…

Tuesday, October 25, 2016

WIF error: ID4175: The issuer of the security token was not recognized by the IssuerNameRegistry.

I’m currently working on a training for one of my customers covering WIF(Windows Identity Foundation),  OIDC(Open ID Connect) and some other security related topics on top of the .NET stack.

Yesterday I got a strange problem after configuring the MVC application that should act as the relying party.

Here is the WIF specific configuration:

And here is the error I got when I ran the application:

ID4175: The issuer of the security token was not recognized by the IssuerNameRegistry. To accept security tokens from this issuer, configure the IssuerNameRegistry to return a valid name for this issuer.

I compared the thumbprint of the certificate used by the STS with the thumbprint inside the config:

<trustedIssuers>
         <add thumbprint="6b 7a cc 52 03 05 bf db 4f 72 52 da eb 21 77 cc 09 1f aa e1" />
</trustedIssuers>


image

No matter how much I looked, I couldn’t see a difference.

Time to ask the global web for help. After some research I found the following article: https://support.microsoft.com/en-us/kb/2023835

It seems there is a bug in the Richedit control that is used by the Certificate UI. When you copy the thumbprint, an extra (invisible) unicode character is being copied also. And indeed when I typed it in instead of copying it over, the error disappeared… Confused smile

Monday, October 24, 2016

VSTS: Monitor usage

Last week I discovered a new tab inside VSTS; the Usage tab.

image 

The Usage tab shows the request history of the users ordered by usage( based on Team Services Throughput Units  or TSTUs). By default, visiting the Usage page will display requests for the last hour.

image

Another nice feature is that you can review the request history leading up to delayed requests.

image

Friday, October 21, 2016

Xamarin.Forms: INSTALL_FAILED_UPDATE_INCOMPATIBLE when trying to deploy to Android device

When we tried to deploy a Xamarin Forms app to an Android device, we got the following error:

Xamarin.AndroidTools.AndroidDeploymentException:
InternalError ---> Mono.AndroidTools.InstallFailedException: Failure
[INSTALL_FAILED_UPDATE_INCOMPATIBLE]
at Mono.AndroidTools.Internal.AdbOutputParsing.CheckInstallSuccess(String output, String packageName)
at Mono.AndroidTools.AndroidDevice.<>c__DisplayClass2a.<InstallPackage>b__29(Task`1 t)
at System.Threading.Tasks.ContinuationTaskFromResultTask`1.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
--- End of inner exception stack trace ---
at Xamarin.AndroidTools.AndroidDeploySession.RunLogged(CancellationToken token)
at Xamarin.AndroidTools.AndroidDeploySession.Start(CancellationToken token)

The problem seemed to be that a "ghost" copy of the app still existed on the device although there was no app icon. However when searching under Applications we found it with its package name instead.

After uninstalling the package we were able to deploy the new version…

Thursday, October 20, 2016

The Open Guide to Amazon Webservices

I hear people talk about JavaScript fatigue, the constant churn of new frameworks, tools and libraries in the JavaScript ecosystem makes it difficult to keep up. I must say that I have the same feelings regarding Cloud, every week Microsoft, Google or Amazon announce a new PaaS, SaaS, FaaS,… offering.

A great resource to help you understand what’s going on inside the Amazon cloud space, is the Open Guide to Amazon Webservices.

From the github page:

A lot of information on AWS is already written. Most people learn AWS by reading a blog or a “getting started guide” and referring to the standard AWS references. Nonetheless, trustworthy and practical information and recommendations aren’t easy to come by. AWS’s own documentation is a great but sprawling resource few have time to read fully, and it doesn’t include anything but official facts, so omits experiences of engineers. The information in blogs or Stack Overflow is also not consistently up to date.

This guide is by and for engineers who use AWS. It aims to be a useful, living reference that consolidates links, tips, gotchas, and best practices. It arose from discussion and editing over beers by several engineers who have used AWS extensively.

image

Wednesday, October 19, 2016

NHibernate Issue: Unexpected updates are triggered

A colleague came to me with the following NHibernate problem; he loads some data from the database using the QueryOver syntax. Although he doesn’t do anything else with the data, NHibernate detects that the list is changed and tries to flush the changes to the database.

What’s causing NHibernate to think that an item has changed?

We figured out the reason after some investigation.

Inside our database we have nullable column e.g.:

Age [int] NULL  -- Nullable column

But inside the mapping we decided to map it to a not nullable property:

<property name="Age" />

public virtual int Age { get; set; }

The moment that the data is loaded and NHibernate sees a null value for Age, inside the property it will be set to 0(the default value for an int).

As the value has changed, NHibernate will detect this and tries to flush the change afterwards.

The solution is to make the property nullable:

public virtual int? Age { get; set; }

Tuesday, October 18, 2016

Testing your Akka.NET system using EventFilter

Although Akka.NET has built-in support for testing, it is sometimes hard to find out what’s really going on inside your actor system.

A useful feature that can help you solve this problem during integration testing is the EventFilter. The EventFilter is a tool to verify that actors write certain log messages. It can also detect if messages go to DeadLetters and if certain exceptions are thrown.

2 examples:

Remark: By default the event filter searches for exact matches.

Monday, October 17, 2016

TypeScript 2.0–Fixing the million dollar mistake

With the introduction of TypeScript 2.0 one of the biggest root causes of bugs in software development finally got a solution. TypeScript 2.0 adds the ability to treat every type as non-nullable.

Let’s see how this works!

Installing TypeScript 2.0

Before we can check out the new language feature, we first have to install TypeScript 2.0. At the moment of writing it didn’t appear yet as part of my Tools and Extensions Updates inside Visual Studio, so let’s go to the TypeScript website and download the code from there.

Take the editor of your choice and install the required package.

image

Enable Strict null checking in Visual Studio

After installing TypeScript 2.0, strict null checking is not enabled out of the box. An extra compiler flag (—strictNullChecks) is required to switch to strict null check mode. To enable it in Visual Studio, you should unload your csproj file, edit it and add the following line to a propertygroup:

<TypeScriptStrictNullChecks>True</TypeScriptStrictNullChecks>

Strict null checking; what does it mean?

From the release notes:

TypeScript has two special types, Null and Undefined, that have the values null and undefined respectively. Previously it was not possible to explicitly name these types, but null and undefined may now be used as type names regardless of type checking mode.

The type checker previously considered null and undefined assignable to anything. Effectively, null andundefined were valid values of every type and it wasn’t possible to specifically exclude them (and therefore not possible to detect erroneous use of them).

In strict null checking mode, the null and undefined values are not in the domain of every type and are only assignable to themselves and any (the one exception being that undefined is also assignable to void).

Ahum? Yes, OK. Let’s try to rephrase this, before null and undefined were always valid values applicable everywhere. Problem was that the compiler couldn’t make any intelligent suggestions the moment null or undefined came into the picture. By switching to strict null checking mode, null and undefined can only be assigned to types that are explicitly flagged as nullable.

An example:

Without strict null checking the following code will compile:

With strict null checking we get a compiler error instead:

image

More information:

Friday, October 14, 2016

Manage your Azure environment using C#

Great announcement by Microsoft yesterday. They provided the first developer preview release of the new, simplified Azure management libraries for .NET. Thanks to a fluent interface-inspired method chains in combination with IntelliSense it delivers an easy to use experience.

Here is an example:

I don’t think it can become any easier…

More information:

Thursday, October 13, 2016

Orleans: Unsupported Type encountered–Part 2

This is a continuation of a previous post. Quick recap, I got an “Unsupported Type encountered” error when trying to send a message from an Orleans client to a silo.

I tried a lot of other things (adding and removing the [Serializable] attribute, creating a custom serializer, …) before I landed at the real solution.

When comparing our code with a sample I created using the Orleans template project in Visual Studio, I noticed that I had a specific NuGet package missing:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.Orleans.Core" version="1.2.4" targetFramework="net452" />
  <package id="Microsoft.Orleans.OrleansCodeGenerator.Build" version="1.2.4" targetFramework="net452" />
</packages>

Without this package doesn’t integrate in your build pipeline. Why is this important? Because behind the scenes Orleans is generating code for your grain messages.  You can see this generated code by expanding the Properties of your project:

image

Inside you’ll find an orleans.codegen.cs file that contains all the magic that Orleans is using behind the scenes. If you are curious, here is a quick peek at some of the generated code:

image

Wednesday, October 12, 2016

Orleans: Unsupported Type encountered–Part 1

I’m currently working on a project where we are using Microsoft Orleans, an actor implementation optimized for Azure. Everything was working fine until we tried to add a web role with an Orleans client to interact with our Orleans silos through a Web API.

However when we tried to send a message from the Web Api to the silo, following error message showed up inside the logs:

!!!!!!!!!! Exception deserializing message body Exc level 0: System.Runtime.Serialization.SerializationException: Unsupported type 'Sample.Contracts.SampleMessage' encountered. Perhaps you need to mark it [Serializable] or define a custom serializer for it? at Orleans.Serialization.SerializationManager.DeserializeInner(Type expected, BinaryTokenStreamReader stream) at Orleans.Serialization.BuiltInTypes.DeserializeOrleansResponse(Type expected, BinaryTokenStreamReader stream) at Orleans.Serialization.SerializationManager.DeserializeInner(Type expected, BinaryTokenStreamReader stream) at Orleans.Serialization.SerializationManager.Deserialize(Type t, BinaryTokenStreamReader stream) at Orleans.Serialization.SerializationManager.Deserialize(BinaryTokenStreamReader stream) at Orleans.Runtime.Message.DeserializeBody(List1 bytes)`

This is how the message object looked like:

First step towards the solution is checking your NuGet packages. It is important that all projects inside your solution are using the same version of Orleans. In our case we noticed that although most projects where using Orleans 1.2.4, a 1.2.3 version sneaked into one of our projects:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.Orleans.Core" version="1.2.3" targetFramework="net452" />
  <package id="Newtonsoft.Json" version="8.0.2" targetFramework="net452" />
</packages>

Ok, one problem fixed. But after deploying again, exactly the same error appeared. We’ll continue our journey in a next post…

Tuesday, October 11, 2016

IIS: Making your Failed Request Tracing logs human readable

One of the great features of IIS is Failed Request Tracing. It offers you an easy configurable way to log all kind of information related to one or more specific error codes. This gives you deep insight into the IIS pipeline and is one of my last resorts in case something is going wrong on the webserver.

The generated logs are large XML files that are hard to read and understand. Luckily in the same folder where your log files are generated(by default c:\inetpub\log\FailedReqLogFiles\W3SVC1) there should also be an XSLT file freb.xsl that transforms the XML into something that normal people could understand.

image

Tip: In case the freb.xsl is missing, delete the folder that contains the log files and IIS will generate the folder again including the missing freb.xsl when the next failed request is logged.

image

Monday, October 10, 2016

Test a webservice using basic authentication with Fiddler

Last week I had to investigate an issue in an old webservice that was still using basic authentication(on a not enforced HTTPS connection Confused smile). With basic authentication you have to send a Base64 encoded version of your username/password combination to the server(that explains immediatelly why using basic authentication over a HTTP connection is never a good idea).

I had to the test the service but the only tool I had available on the server was Fiddler.

So let’s start by creating the Base64 encoded version of our message:

  • Open Fiddler
  • Go to Tools –> TextWizard…
  • Type your username password combination separated by a ‘:’, e.g. username:password
  • Choose ToBase64 from the Transform list
  • Copy the generated string

image

Next step is to create our request:

  • Go to the Composer tab
  • Type “Authorization: Basic’’after the User-Agent string and add the generated string to the end. The result should look like this:
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=

image

Friday, October 7, 2016

ASP.NET Async SessionState module

The default ASP.NET SessionStateModule is already partly asynchronous; it reads the request state asynchronous, but it doesn’t support async when reading/writing to the session store.  In the .NET Framework 4.6.2 release, Microsoft changed this by introducting a new interface named ISessionStateModule.

Thanks to the async SessionState module it becomes possible to access the session storage providers(SQL Server, Redis,…) asynchronously. Async I/O operation helps release the thread more quickly than synchronous I/O operation, and ASP.NET can handle other requests.

Here are the required steps to start using this module:

The introduction of this module will help in improving the performance of your ASP.NET applications.

Thursday, October 6, 2016

Xamarin.Forms: Error CS1703 Multiple assemblies with equivalent identity have been imported

When trying to build our Xamarin.Forms project on a VSTS hosted build server, our build failed first with the following error message:

Error CS1703 Multiple assemblies with equivalent identity have been imported: ‘C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\MonoAndroid\v1.0\mscorlib.dll’ and ‘C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll’. Remove one of the duplicate references.

On our local system it worked without any compiler errors. We tried the easiest solution first, following the advice as mentioned in the error message. We removed the mscorlib.dll from the references. After doing that, everything was working again.

I hate it when the behavior differs between a local Visual Studio Build and the build server Sad smile

Wednesday, October 5, 2016

Could not load file or assembly 'Microsoft.SqlServer.Types'

A colleague contacted me to investigate a problem some of his customers had when opening an RDLC(local Reporting Services report) inside a ReportViewer control. Instead of a nice looking report, they got the following error message:

An unexpected error occurred in Report Processing. Could not load file or assembly 'Microsoft.SqlServer.Types, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Strange! We had no clue why this error appeared. I don’t see a reason why this DLL is needed. Anyway we solved it by downloading the assembly through NuGet(https://www.nuget.org/packages/Microsoft.SqlServer.Types/) and including it in the installation package.

If anyone has a clue why this DLL is required, feel free to share!

Remark: Even stranger was that we hadn’t this problem with a previous release.

Tuesday, October 4, 2016

Orleans error: Orleans.Storage.BadProviderConfigException: No storage providers found loading grain type

Next step in my journey into Orleans land, was using ‘Declarative Persistence’. Sometimes you want the state inside your actors(grains in Orleans terminology) being persisted in some kind of permanent storage, so that it can survive a silo shutdown. Orleans provides a simple declarative model that makes this possible.

Unfortunately while following the related tutorial, I got the following error message:

[2016-10-04 07:19:17.848 GMT    11      ERROR   103104  Catalog 127.0.0.1:11111]        !!!!!!!!!! No storage providers found loading grain type Grains1.Manager

No storage providers found loading grain type Grains1.Manager

Exception = Orleans.Storage.BadProviderConfigException: No storage providers found loading grain type Grains1.Manager

   at Orleans.Runtime.Catalog.SetupStorageProvider(ActivationData data)

   at Orleans.Runtime.Catalog.CreateGrainInstance(String grainTypeName, ActivationData data, String genericArguments)

   at Orleans.Runtime.Catalog.SetupActivationInstance(ActivationData result, String grainType, String genericInterface)

   at Orleans.Runtime.Catalog.GetOrCreateActivation(ActivationAddress address, Boolean newPlacement, String grainType, String genericArguments, Dictionary`2 requestContextData, Task& activatedPromise)

   at Orleans.Runtime.Dispatcher.ReceiveMessage(Message message)

[2016-10-04 07:19:17.853 GMT    11      ERROR   101540  Dispatcher      127.0.0.1:11111]        !!!!!!!!!! Error creating activation for Grains1.Manager. Message NewPlacement Request S127.0.0.1:11111:213261543*cli/893aa39f@4423baaf->S127.0.0.1:11111:213261543*grn/913DAEDD/af761896@76d92c9c #4: global::GrainInterfaces1.IManager:AsEmployee()

Exc level 0: Orleans.Storage.BadProviderConfigException: No storage providers found loading grain type Grains1.Manager

   at Orleans.Runtime.Catalog.SetupStorageProvider(ActivationData data)

   at Orleans.Runtime.Catalog.CreateGrainInstance(String grainTypeName, ActivationData data, String genericArguments)

   at Orleans.Runtime.Catalog.SetupActivationInstance(ActivationData result, String grainType, String genericInterface)

   at Orleans.Runtime.Catalog.GetOrCreateActivation(ActivationAddress address, Boolean newPlacement, String grainType, String genericArguments, Dictionary`2 requestContextData, Task& activatedPromise)

   at Orleans.Runtime.Dispatcher.ReceiveMessage(Message message)

What I was missing were the following lines inside my orleansconfiguration.xml:

<OrleansConfiguration xmlns="urn:orleans">
  <Globals>
    <SeedNode Address="localhost" Port="11111" />
    <StorageProviders>
      <Provider Name="AzureStore" Type="Orleans.Storage.AzureTableStorage" DataConnectionString="UseDevelopmentStorage=true"/>
    </StorageProviders>

  </Globals>
  <Defaults>
    <Networking Address="localhost" Port="11111" />
    <ProxyingGateway Address="localhost" Port="30000" />
  </Defaults>
</OrleansConfiguration>

On my grains I had the following attribute added:

[StorageProvider(ProviderName = "AzureStore")]
public class Employee : Grain<EmployeeState>, IEmployee
{

Monday, October 3, 2016

Project Orleans error: System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions

I’m currently experimenting with Orleans and trying to compare it with my experiences using Akka.NET and the Azure Service Fabric actors. So far I like the experience although I encountered some issues in the beginning.

image

I got my first problem when trying the “hello world” of actor model examples; https://dotnet.github.io/orleans/Tutorials/My-First-Orleans-Application.html. After following the tutorial, my Orleans host blew up with the following exception:

ERROR starting Orleans silo name=[MyMachineName] Exception=
Exc level 0: System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions
at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Bind(EndPoint localEP)
at Orleans.Runtime.SocketManager.GetAcceptingSocketForEndpoint(IPEndPoint address)
at Orleans.Runtime.Messaging.IncomingMessageAcceptor..ctor(MessageCenter msgCtr, IPEndPoint here, SocketDirection socketDirection)
at Orleans.Runtime.Messaging.MessageCenter.Initialize(IPEndPoint here, Int32 generation, IMessagingConfiguration config, ISiloPerformanceMetrics metrics)
at Orleans.Runtime.Silo..ctor(String name, SiloType siloType, ClusterConfiguration config, ILocalDataStore keyStore)
at Orleans.Runtime.Silo..ctor(String name, SiloType siloType, ClusterConfiguration config)
at Orleans.Runtime.Host.SiloHost.InitializeOrleansSilo()

Whoops! Not a great start for my first experience with Orleans. A netstat –o brought some insight into the root cause of this issue. The default port used by Orleans(port 22222) was already in use.  I removed the tool(RedGate Ants Profiler in my case) that was using the port and I was good to go!