All posts tagged with .net

Azure Table Storage does not support Decimal

September 17, 2019 - Søren Alsbjerg Hørup

As the title suggests, Azure Table Storage does not support the Decimal fixed-point type of .NET. One needs to be very aware of this, since no warnings or errors are provided when using the Table Storage API.

I have just spent an hour trying to figure out why my decimal values were all zeroed out when retrieving the rows back from the table. Changing decimal to double fixed the issue.

For my application, double is fine, but for applications requiring fixed point arithmetics this is definitly a con.

As far as I can see, CosmosDB has the same limitation.

Oh well…


May 28, 2019 - Søren Alsbjerg Hørup

I am a frequent WebSocket user. WebSocket is perhaps the single-best thing that has happened to web development since the introduction of HTML5, due to its bi-directional and ‘real-time’ characteristics.

I have frequently used a websocket conncetion to keep the client up to date with regards to changes from the server, especially when doing game related development.

Recently, I stumbled upon SignalR which is more or less an RPC library for .NET and JavaScript. It provides the ability for a JavaScript application running in the browser to invoke functions directly on the .NET server application, and vice versa.

The transport channel is simply a websocket connection, thus anywhere websockets are supported SignalR should in theory be supported. In addition, SignalR is 100% open - allowing anyone the possibility to implement a SignalR client or server for any other language.

I have yet to tryout the library myself - but it is definitely on my to do list!

Dapper for .NET

May 06, 2019 - Søren Alsbjerg Hørup

When dealing with databases access in my C# applications I typically use Entity Framework’s code first approach to generate the model. Entity Framework is very nice, but it has two drawbacks:

  1. Generally, it is slow compared to raw SQL - primary reason i believe is that Entity Framework is not able to generate very efficient SQL behind the scene.
  2. Many-To-Many relationships are hard to represent in Entity Framework. Join tables are needed to be explicitly represented using a Join entity.

While researching a project I found another library: Dapper.

Dapper is an light-weight Object-Relational Mapping (ORM) library for .NET. While Entity Framework is primarily used as code-first, Dapper only supports Database first.

To use Dapper, a plain model class is written for each table (very similar to Entity framework) . The class for a User table with an autoincrement Id, Email and a Name would look like this:

class User
   public int Id { get; set; }
   public string Email { get; set; }
   public string Name { get; set; }

Assuming we have an instance of SqlConnection to an SQL DBMS such as MSSQL or MySQL, we can use dapper to fetch our user rows and transform the rows into a collection of User instances like so:

var sql = "select \* from [User]";
var users = connection.Query<User>(sql);

the users variable is an IEnumerable type, which can be iterated using Linq.
Note: the SQL is tightly coupled to the underlying DBMS - meaning that the same SQL cannot be used to connect to different DBMS’.

Dapper also supports the concept of ‘multi-mapping’ which provides the ability to map a single row to multiple objects. This is especially useful when dealing with joins between two or more tables. Consider the following example which joins the Post table with the User and return a Post instance where the User property has been set to the particular user:

var sql = @"select \* from [Post]
            left join [User] on [Post].UserId = [User].Id";

var postsWithUsers = connection.Query<Post, User, Post>(sql, (post, user) =>
  post.User = user;
  return post; 

postsWithUsers is an IEnumerable returned by the query. Each Post instance will have a User property pointing to the User instance found during the join.

Dapper makes this work by automatically splitting the joined row on the Id columns. This can be changed through configuration if needed by providing a value on the splitOn parameter of the Query method.

Dapper is very fast, primarily due to raw SQL is being used. Many to many relations can also be expressed using Dapper’s multi-mapper, however, the same drawback naturally exists regarding the join table - but this problem is “pushed” to the database since it does not have to be represented as a model in the code.

If you know SQL and have no problems with being tighter coupled with the underlying database, I highly recommend Dapper.

Windows Hooks as non-admin

July 19, 2017 - Søren Alsbjerg Hørup

My most recent productivity application, Shortcutty, requires the ability to hook into Windows to capture keydown events. The purpose is to show (or hide) the application whenever the user pressed CTRL+~.

I easily got this to work using the Win32 API + PInvoke in my .NET application. But, on some applications such as my Visual Studio instance, the hook failed by unknown reasons.

After a bit of debugging and digging through online archives on the matter, I quickly realized that the issue was as simple as my application not having administrator rights. The latter is required if I want my application to interact with other applications having higher privileges.

Visual Studio, as it happens, was running with admin-rights - thus my application was unable to hook into it, obviously for security reasons. Generally: a non-administrator process cannot interact with a process having administrator rights. You cannot even drag and drop between applications.

.NET Core

June 30, 2017 - Søren Alsbjerg Hørup

.NET Core is yet another .NET framework implementation implementing .NET Standard 1 (production) and .NET Standard 2 (beta) while also extending the standard with .NET core specific API’s such as Console and Thread (which are not part of the .NET Standard).

The cool thing with .NET Core is that it is: 100% open-source, 100% cross-platform and very modular. This stands in contrast to .NET and Mono since these are very monolithic implementations and huge in size. The source is available under MIT on GitHub:

Since .NET Core is very crossplatform, one can write .NET applications for x86/ARM Windows and x86/ARM Linux - and since it is very modular, the framework does not occupy much space compared to the desktop implementations.

API’s are generally not available in the framework but needs to be downloaded from NuGet, e.g. EntityFramework, ASP.NET, and even some Reflection support are an “add-on”.

I measured the raw framework installation on my Win 10 x64 box to about 70MB, while the .NET 4.6 framework is roughly 2000MB in size, that is, 28 times larger! Deployment wise, .NET Core SDK supports deploying application + framework meaning that the target does not have to have the specific framework installed.

The SDK will automatically pull all the dependencies into the publish package, which includes all NuGet dlls + native assemblies where applicable (e.g. if using sqlite .NET core wrapper). One can also publish to a specific target, such as Linux-x86 or Linux-arm, which will produce a platform specific package with an elf executable that can be executed.

Referencing .NET assemblies which does not target .NET Standard or .NET Core is not possible in .NET Core 1.1 since the APIs are incompatible. .NET Core 2.0 will include a compatibility layer making it possible to reference assemblies targeting other frameworks - although this sounds awesome, I have not experimented with this feature yet.

.NET Core is without a doubt the future of .NET!

.NET Standard

June 23, 2017 - Søren Alsbjerg Hørup

The .NET framework has been branched into several implementations to match the constraints of the target platforms, e.g. Compact Framework for Pocket PC, Mono for Linux and the full .NET Framework for Windows.

This poses a problem regarding library compatibility between them. Writing a library is not straightforward since one has to target the specific framework in which the library is consumed.  This has somewhat been alleviated by Portable Class Libraries (PCLs), since this type of library can target multiple frameworks. It is not a 100% solution, since when a new framework emerges the library in question is not automatically compatible with the new framework.

The solution has been to introduce a versioned formal API specification called .NET Standard. This standard is implemented by all the most common framework implementations. Writing a library targeting .NET Standard 1.0 ensures that the library can be consumed across different frameworks, if they implement the .NET Standard 1.0.

The .NET Framework 4.5 implements .NET standard 1.1 while .NET Framework 4.6 implements .NET Standard 1.4. Writing a library for both .NET Framework 4.5 and 4.6 can easily be done by targeting .NET Standard 1.1. Also, Windows Phone 8.1 and Mono implements .NET Standard 1.3 or above making the said library compatible with these implementations.

Each new version of the .NET Standard inherits from the previous version, making a new version a super-set of the old version. The API specification is written i C#, making it straight forward to read and adapt the API to a new implementation.

.NET Core is the latest framework implementing .NET Standard, more on this later.

Linq To Sql .Attach

June 12, 2017 - Søren Alsbjerg Hørup

Linq to SQL is a very nice abstraction when dealing with MSSQL, specifically the ability to conduct Linq queries in C# against MSSQL is pretty sweet. Updating a row through an ORM object, e.g. a HTTP Put, into the DB without doing manual field copying between the tracked entity and the de-serialized entity from the PUT is however a bit troublesome.

.Attach allows one to attach an entity to a Context, however calling SubmitChanges will not submit the changes of the attached object due to it not being marked as modified. Calling Attach(entity, asModified) with asModified = true did not work for me - an exception was thrown.

Apparently, this overload can only be called with asModified = true IFF Update Check is set to Never in the DBML file. This needs to be done for all properties of the given entity class, not sweet, but at-least it avoids the need to manually copy each member to an existing tracked Entity in the Context.

Jira SDK nuget

June 06, 2017 - Søren Alsbjerg Hørup

Accessing Atlassian Jira from a .NET application can be done very easily by installing the Atlassian Jira SDK.

Install-Package Atlassian.SDK

From the nuget console.

This introduces the Jira assembly with alot of different classes and helper functions. E.g. one can connect to Jira using:

Jira.CreateRestClient(url, username, password)

which instantiates the Jira class which can be used to get Versions, Issues, etc. from Jira. A real treat using this library is that it proved Async methods, i.e. await keyword can be used throughout the usage.

getting all Versions of a specific project/key can be done using:

var results = await jiraConn.Versions.GetVersionsAsync(key)

getting issues using a specific JQL query can be done using:

var results = await jiraConn.Issues.GetIssuesFromJqlAsync(jql)

super easy!

System.AccessViolationException and .NET 4.0

May 29, 2017 - Søren Alsbjerg Hørup

The  System.AccessViolationException is thrown if one tries to marshal unamanaged memory from an invalid location, e.g. using a bad pointer. Prior to .NET 4.0, this exception was catch-able from within the CLR.

With .NET 4.0,  System.AccessViolationException exception is no longer catched within the CLR, meaning that the application now crashes without necessarily logging the information in log4net. The stack trace can however be seen in windows’ event viewer.

It is possible to mark the method in which the exception is thrown using HandleProcessCorruptedStateExceptionsAttribute, thus making the method throw the exception into the CLR and making it catchable.