måndag 9 april 2018

Do your ajax calls block each other so they don't run in parallell? Setting the right SessionStateBehavior might fix it!

Today I tried to optimize an asp.net mvc page. The page did three ajax calls, two of them were fast and one was slow. The slow one executed first and blocked the other two so they couldn't execute and return with their data until the slow one had finished.

I was surprised by this since the ajax calls really should be asynchronous. The problem turned out to be the use of session. When session is passed with the ajax call, the call blocks other calls that passes the same session. Because if the first call alters the session it should have an impact on the other calls so they have to wait.

The solution to this was to add this attribute on the controller.
[SessionState(SessionStateBehavior.ReadOnly)]

When the controller is marked with that attribute asp.net knows that the code in the controller can't alter the session state so the other calls don't have to wait for it.

Here's the blog post that got us on the right track.

söndag 11 mars 2018

Multi-cursor editing in Visual Studio Code, edit many places simultaneously!

Did some pair programming with @nevva and saw him do some multi-cursor editing in Visual Studio Code I hadn't seen before. So here's three different ways to edit your text files at multiple places simultaneously.

Use Esc to exit multi-cursor mode.

1. Ctrl + Alt + arrow down (or arrow up)
A simpler variant of this in the classic Visual Studio is Shift + Alt + any arrow


2. Alt + left mouse click


3. Mark some text => all occurrences gets highlighted
Ctrl + Shift + L => every occurrence gets its own cursor


söndag 28 januari 2018

Two subtle Linq-related bugs that ReSharper highlighted during code review

ReSharper, a productivity tool that helps you automate some of the code writing and also analyses the code written. The biggest drawback I find with it is that it makes the Visual Studio startup a lot slower. Yes, that is annoying, but I still value the code quality help it gives me more than a fast startup.

This is two examples of Linq-related bugs that ReSharper pointed out for me when I was reviewing code. I hope I would have found the bugs anyway, but Resharper made it a no-brainer to find them and almost impossible to miss.
The examples do not show the original code, only the same problems.
The code writers did not use ReSharper.

Example 1

This is example 1, without the help of ReSharper, do you see the problem?

This is the same code, but with ReSharper active, the problem is shown more clearly, isn't it?


The gray code in the if-block tells us that the code isn't used. Ok, so why isn't it used? Hoover over the blue squiggly-lined code and you will see:



Expression is always false. This hopefully makes a programmer with little experience in Linq to do some research to find out why. And then change the if-condition
projects == null 
to 
projects.Count == 0 
or 
!projects.Any()

Because Linq's ToList() does never return null, if no rows are matched an empty list is returned.

Example 2

This is a similar problem, do you see what the problem is this time?


With ReSharper activated it looks like this again, but not for the same reason.


The variable projects is not the resulting list of the query. It IS the query. A query that hasn't been executed. And therefore, since it is a query (or an IQueryable object) that is assigned to a value during creation, it cannot be null when the execution of the code reaches the if-condition.


Conclusions

These two bugs can to a code writer or reviewer be rather subtle, but with the help of ReSharper they are not so subtle. Subtle bugs can easily go under the review radar and if the code isn't tested thoroughly it can even reach production. And bugs having come that far are often more cumbersome/expensive to fix than if they had been caught earlier in the process.
That's why I find ReSharper worth its price, both when it comes to money and performance.

torsdag 25 januari 2018

The Visual Example I Always Search for Before Doing a Feature Branch Rebase

Now and then we discover that we've branched out a feature branch off of the wrong branch. To get the workflow correct, we need to move the feature branch so it branches off of the correct branch, a so called feature branch rebase. 

This happens so seldom that I always have forgotten the command for how to do it, so I google it and hope for finding the same example that I found useful the last time. The example isn't hard to find, but this post is for making sure I don't lose it.

The example is copied from the section More Interesting Rebases at https://git-scm.com/book/en/v2/Git-Branching-Rebasing





tisdag 16 januari 2018

C# Linq Equivalents in TypeScript

I have been looking for something like the C# Linq functions in TypeScript, but didn't have any luck. Today a colleague tipped about this site, where Linqs IEnumerable<T> extension methods are listed together with the methods TypeScript equivalent.

A few examples to give you an idea of what it can look like.






söndag 26 november 2017

Refactoring: Replace Magic Number with Symbolic Constant example i C#

Part three in my series of refactors I've used the most from the book Refactoring - Improving the design of existing code.

Replace Magic Number with Symbolic Constant

You have a literal number with a particular meaning.
Create a constant, name it after the meaning, and replace the number with it.

Example 1

The code before

1:  double PotentialEnergy(double mass, double height)  
2:  {  
3:    return mass * 9.81 * height;  
4:  }  

The code after

1:  private const double GravitationalConstant = 9.81;  
2:    
3:  double PotentialEnergy(double mass, double height)  
4:  {  
5:    return mass * GravitationalConstant * height;  
6:  }  

Example 2

I thought I would find a better example, but it wasn't that easy, so I settled with just another example. The example below is from the page https://www.eliotsykes.com/magic-numbers, but I think the real world examples in the bottom of that page might give you a better understanding of how you can use constants.

The code before

1:  public bool AllowedToComment()  
2:  {  
3:    return _age >= 13 && CommentsInLastHour.Count < 20;  
4:  }  

The code after

1:  const int CommenterMinAge = 13;  
2:  const int MaxCommentsPerHour = 20;  
3:    
4:  public bool AllowedToComment()  
5:  {  
6:    return _age >= CommenterMinAge && CommentsInLastHour.Count < MaxCommentsPerHour;  
7:  }  

Motivation

Magic numbers are one of the oldest ills in computing. They are numbers with special values that usually are not obvious. Magic numbers are really nasty when you need to reference the same logical number in more than one place. If the numbers might ever change, making the change is a nightmare. Even if you don't make a change, you have the difficulty of figuring out what is going on.

The source code



måndag 13 november 2017

Refactoring: Introduce Explaining Variable example i C#

Part two in my series of refactors I've used the most from the book Refactoring - Improving the design of existing code.

Introduce Explaining Variable

More known as Extract Variable

You have a complicated expression.
Put the result of the expression, or parts of the expression, in a temporary variable with a name that explains the purpose.

Example 1: The code before

1:  if (platform.ToUpper().IndexOf("MAC") > -1 &&  
2:    browser.ToUpper().IndexOf("IE") > -1 &&  
3:    WasInitialized() && resize > 0)  
4:  {  
5:    // do something  
6:  }  

Example 1: The code after

1:  bool isMacOs = platform.ToUpper().IndexOf("MAC") > -1;  
2:  bool isIEBrowser = browser.ToUpper().IndexOf("IE") > -1;  
3:  bool wasResized = resize > 0;  
4:    
5:  if (isMacOs && isIEBrowser && WasInitialized() && wasResized)  
6:  {  
7:    // do something  
8:  }  

Example 2: The code before

1:  public double Price()  
2:  {  
3:    // price is base price - quantity discount + shipping  
4:    return _quantity * _itemPrice -  
5:        Math.Max(0, _quantity - 500) * _itemPrice * 0.05 +  
6:        Math.Min(_quantity * _itemPrice * 0.1, 100);  
7:  }  

Example 2: The code after

1:  public double Price()  
2:  {  
3:    var basePrice = _quantity * _itemPrice;  
4:    var quantityDiscount = Math.Max(0, _quantity - 500) * _itemPrice * 0.05;  
5:    var shipping = Math.Min(_quantity * _itemPrice * 0.1, 100);  
6:    return basePrice - quantityDiscount + shipping;  
7:  }  

Example 2: The code after (using Extract Method)

1:  public double Price()  
2:  {  
3:    return BasePrice() - QuantityDiscount() + Shipping();  
4:  }  
5:    
6:  private int BasePrice()  
7:  {  
8:    return _quantity * _itemPrice;  
9:  }  
10:    
11:  private double QuantityDiscount()  
12:  {  
13:    return Math.Max(0, _quantity - 500) * _itemPrice * 0.05;  
14:  }  
15:    
16:  private double Shipping()  
17:  {  
18:    return Math.Min(_quantity * _itemPrice * 0.1, 100);  
19:  }  

Example 2: The code after (using Expression Body Definitions)

If you're using C# 6 or above you can use Expression Body Definitions to shorten your methods.

1:  public double Price()  
2:    => BasePrice - QuantityDiscount + Shipping;  
3:    
4:  private int BasePrice   
5:    => _quantity * _itemPrice;  
6:    
7:  private double QuantityDiscount   
8:    => Math.Max(0, _quantity - 500) * _itemPrice * 0.05;  
9:    
10:  private double Shipping  
11:    => Math.Min(_quantity * _itemPrice * 0.1, 100);  

Motivation

Expressions can become very complex and hard to read. In such situations temporary variables can be helpful to break down the expression into something more manageable.
Introduce Explaining Variable is particularly valuable with conditional logic in which it is useful to take each clause of a condition and explain what the condition means with a well-named temp.

The source code


Personal thoughts

An easy-to-do refactoring that can do so much for the code readability. Low hanging fruit!