Tech Blog

.NET Core 2.0 Worth Using? Looks Like It

posted Sep 24, 2017, 6:34 PM by Victor Zakharov   [ updated Sep 24, 2017, 6:34 PM ]

September of 2017 is almost gone, and only now I had a chance to look at the most recent issue of the monthly MSDN magazine. What's the hot topic in September? .NET Core 2.0 / Standard 2.0 is highly praised by most MSDN authors. One of the articles mentions a feature I did not know existed. It's called Razor pages. In short, it's the new Web Forms. It allows you to finally transition to Razor even for small websites, which do not require a full blown MVC structure (where files live in 3 different folders, and you are constantly switching between them). The simplicity of having 1 markup file + 1 code-behind file is what kept people from defaulting to MVC. Now you can have the best of both worlds, and once your project evolves in complexity, separate into more classes. For more details, check here:
I decided to go online regarding .NET Core 2.0 in regard to performance improvement, since it is now open source.
There were quite a few notable improvements (iterators, lists and other common data structures), and some areas were improved 100x and more.
Also .NET Core 2.0 is now able to reference Full Framework libraries (for example, .NET 4.7).
Which means we can write new code in .NET Core while still referencing the old code.
Another good sign is that MS got rid of xproj / project.json experiments in favor of csproj, the extension we are so much used to.
The benefit is we can continue to use MSBuild now, whereas for experimental project types we would need to use other build tools (so no easy path from .NET 4.7 to Core 1.0).
In a way, .NET Core 2.0 to Core 1.0 is like .NET 2.0 was to 1.1 in the old days of early .NET – it is mature enough to use, in both performance and integration aspects.

TSQL - Get Index By Table Name + Column Name, Skip Composite Indices

posted Sep 24, 2017, 6:14 PM by Victor Zakharov   [ updated Sep 24, 2017, 6:15 PM ]

Below SQL code will find an index name that corresponds to the given table name and column name pair, and only include those indices with one column (exclude composite indices). Indices can be changed / added / removed by a DBA without impact to the application (part of DB tuning), so it's best not to assume their naming in an application deployment script. This can be useful to remove / replace certain indices without relying on index name.

Based on this Stack Overflow's answer:
- List of all index & index columns in SQL Server DB
DECLARE @indexName VARCHAR(256)

WITH indices AS (
    SELECT TableName = MAX(,
           ColumnName = MAX(,
           IndexName =,
           COUNT(*) as FieldCount
      FROM sys.indexes i
      JOIN sys.index_columns ic
        ON i.object_id = ic.object_id and i.index_id = ic.index_id
      JOIN sys.columns c
        ON ic.object_id = c.object_id and ic.column_id = c.column_id
      JOIN sys.tables t
        ON i.object_id = t.object_id 

SELECT @indexName = i.IndexName FROM indices i
WHERE i.TableName = 'Person' --table name filter  
  AND i.ColumnName = 'FirstName' --column name filter
  AND i.FieldCount = 1 --index only contains this column, not a composite index 

SELECT @indexName

Powershell - Get CPU Usage by Process (remote)

posted Apr 19, 2017, 1:24 PM by Victor Zakharov   [ updated Apr 19, 2017, 1:25 PM ]

You would expect Get-Process to do the job, but it turns out that its CPU metric is not on a 0..100% scale.

Here is a one-liner (find who's eating into your CPU - or that of a remote server):

gwmi Win32_PerfFormattedData_PerfProc_Process -filter "Name <> '_Total' and Name <> 'Idle'" -Computer $servername | where { $_.PercentProcessorTime -gt 0 } | select Name, PercentProcessorTime

For some reason, the total percentage of all selected processes can be greater than 100, I'm guessing there was a measurement lag.
Don't forget to initialize $servername (or hard code it before executing).

Credit goes here.

Extend Clickable Area For jQueryUI Slider

posted Feb 15, 2017, 11:53 AM by Victor Zakharov   [ updated Feb 15, 2017, 11:59 AM ]

Even using the default jQueryUI's slider style, the handle is larger than its container. Now suppose your container is 3x smaller than the handle (specific design requirement). There is a problem - you have to hit the container precisely to be able to change slider's value. Otherwise nothing happens. Here is what I mean:

It would be nice to extend the slider clickable area to pretend it's actual height matches slider or its handle, if handle is taller. You can do this by appending a bigger element to the slider, and then adjusting its position within the element.

Here is the code (jQuery):

$(document).ready(function() {
    var clickArea = $(document.createElement('div'));

Then your .click-area class would be defined similar to the following:

.click-area {
    top: -15px;
    width: 100%;
    height: 29px;
    position: absolute;

You'll need to play with these values to fit your needs. Also for best relative positioning, don't forget to add position: relative on the parent element.
Note that createElement is faster than other available methods.

My solution is based on this one:

TypeScript 101 - Getting started in Visual Studio 2015

posted Nov 23, 2016, 7:38 AM by Victor Zakharov   [ updated Nov 24, 2016, 6:22 PM ]

I decided to write this article simply because there are so many outdated answers to this question linked from Google.
Here are some of the things you should NOT do:
  • Install Web Essentials
  • Install Node Package Manager
  • Manually adjust project files to enable Typescript transpiler
  • Automatically adjust project files by installing a nuget package
  • Install something that downloads 1000s of files into a folder inside your project and works with fingers crossed.
Why? Because there is a easy way. In short, just add a .ts file to your project and link the corresponding .js from the web page. Longer version of answer follows, with screenshots and detailed instructions.

Suppose you are starting a new project.
In Visual Studio 2015 select File -> New -> Project -> under Visual C# / Web / choose ASP.NET Web Application and click OK.
Select "Empty" template, ensure that none of the checkboxes are checked (Web Forms, MVC, Web API, Add unit tests, Host in the cloud) and click OK.

Right click on Project -> Add -> New Item... -> under "Search Installed Templates" in the top right corner search for "types" and select "TypeScript File" from the list, call it "script.ts" for now and click "Add" (the name can be anything you want). Notice the file should have a .ts extension.

Although the most logical option here would be "Yes", click "No". Ultimately (I think there is a bug in Visual Studio 2015), it will not load anything regardless of your selection.
If you are wondering - yes, you will still have typings for standard Javascript objects, and I will prove it later on.

You are done! Typescript should be fully operational at this point. Let's see how to make it do some useful work. First, we need to verify that Visual Studio can transpile into Javascript.
In your .ts file type


and hit save (CTRL+S). Nothing happened? Where is my .js file?
Okay, the transpiled .js file is hidden by default. You need to click "Show all files" icon in Solution Explorer:

We are going to add a .html page to be able to see it working inside the browser. Right click Project -> Add -> New Item... -> search for "html", select "HTML Page", name it Default.html and click Add. Put "Hello World" between the body open/close tags just so we can see something when it loads. Press F5 or click the green "play" button to start the project. When it loads in your browser, you should see something like this:

It works. Now close the browser window and go back to your Default.html file. Right before the closing </head> tag make a newline. Drag a .ts file into that line. It should paste something like this:

<script src="script.js"></script>

Yes, you could have typed this manually, but it would not be as cool. In your script you have an alert, so that's what you are supposed to see when you start your project again.

Ok, but we didn't do any TypeScript yet? Go inside your .ts file and paste the following:

class SayHello {
    name: string;

    constructor(name: string) { = name;

    sayHello() {
        alert("Hello, " +;

var a = new SayHello("Victor");

Hit save (CTRL+S) and... actually, there is one more thing to do. Right click on "Default.html" and choose "Set as Startup Page", this way we just save a few clicks. There:

Now I promised to prove that we have typings and also show the debugging support (because it would be quite useless without it).
Back to your .ts file at the very bottom type "document.get":

Press tab to perform auto-complete:

Notice the argument is expected to be of type "string". Our typings work, you now have typed intellisense support for standard Javascript objects.
Remove this line and put a breakpoint inside the class beside the "alert" line and run it again.

See, debugging works just as fine as with a regular Javascript file, which means real coding can start now!

The rest you should be able to figure out using google.
Any questions or comments - shoot me an email.

Atom Editor by GitHub - Worth It?

posted Mar 17, 2016, 5:52 PM by Victor Zakharov   [ updated Mar 17, 2016, 5:55 PM ]

In short, Atom editor by GitHub is well-built, focused on code (there isn't really anything getting in your way), similar to Sublime. Now I haven't used Sublime beyond basics and generally favour GUI, rather than command line. Everything can be found via CTRL+SHIFT+P. However, if something can be typed with 5 characters, and it could have also been called with 2 keystrokes, I'd choose the keystrokes approach. I'm not a Sublime user, you guessed it right, won't be paying 70$ for a fancy text editor, if WebStorm is worth 59$. Not an affiliate of JetBrains, just common sense.

TL;DR version is at the bottom of this page - under Summary.

Options for color schemes are very good, I found a really great dark theme, this coming from a user who never used dark themes on anything yet. If you are like me, try it out, their dark theme is excellent. I used "One Dark" for UI Theme and "Base16 Tomorrow Dark" for Syntax Theme. In my opinion, these make a great combination together. Not to mention that you can install custom themes as well. With all my current plugins, Atom looks like this (details to follow):

To me it looks great, makes you want to write some code. Unfortunately, it does not work like this out of the box, so below I will describe plugins, which help make Atom more usable.

The good - what worked:
  • color picker package - somehow the key combination does not do anything (CTRL+ALT+C), so I had to use the right click menu. Nothing bad really, but it could have been integrated as part of "pigments" package - see below.

  • minimap - very useful, gives you overview of your code, so you can easily navigate to the relevant part. It's not commonly recognized that code has shape, but I believe in this. In fact, if you can distinguish the place in code by shape, you probably have good quality code. On the other hand, if without reading line by line, your code looks the same, it probably was not yet refactored.

  • pigments - displays color inside the CSS file, but does not allow you to change it. Really? Would you not want to change it by clicking on the icon with a particular color? I have to install a separate package, which has other issues, already described above. Side note here - if you don't like how it displays the color, there are ways to change it in configuration, so don't give up just because the default isn't very sexy. For the screenshot of how I had it set up - see color picker bullet point, to the left of line 37 (and 51 too).

  • remote-sync - works well over FTP after several hickups. For those of you who don't know what this does - it uploads a file to a remote server after every change. Very convenient to see live changes immediately, whether on production or staging server. The only issue - does not report status, i.e. you never know if it's working or not. You can expand its window, but then it's taking desktop space, where code should be instead. I'd expect a popup whenever files are uploaded, or some status bar showing upload progress. Even a simple indication would be nice (spinning wheel, anything really). Internally has a JSON config, but there is GUI to do the same, I used GUI.

The bad - what didn't work (and I really hoped it would):
  • Git integration from the IDE (and probably source control in general, haven't tried SVN or other VCS). Tried several plugins - all of them were either garbage or inefficient. Commit/push is probably the most common operation I would do - it should be one-click operation. Toolbox, keystrokes, does not matter, what's important is that I must be able to review my changes before commit, diff included. If conflicts, resolve. Ideally some validation on HTML/CSS, and do not commit if there are "common" issues, like HTML5 not passing W3 validation. Important here - Atom knows which files were changed, highlighted with different colors, but cannot explain why and what exactly was changed.
People can say "use command line" or TortoiseGit (which I have installed, just lazy to minimize Atom, navigate in Explorer/Total Commander and use from the right click menu) - I prefer the IDE to have everything in it.

Good example - there simply isn't anything to compare with the level of convenience offered by WebStorm/PhpStorm (click on below image to see full size):

Challenge - if you know better than the above diff view, feel free to drop me an email. If I find it decent, the article will be updated and you will get a credit.
Side note - I already know about Beyond Compare, Araxis Merge, Code Compare by Devart, WinMerge and many others. 

Overall, I spent 2 hours straight (no breaks for coffee), trying to make things work and really hoping it would suffice my basic needs. Unfortunately, integrated support for version control is crucial. Atom editor is fairly new, many important plugins are community authored, and most of them are poor quality, i.e. they work, but often you see display artifacts/glitches. Not a production quality product, but hopefully in 2-3 years from now, we'll see a strong competitor to JetBrains and others. It's free though, so you may still give it a try and - because it's open source - help develop.

Lock File Tool - Test Exception Handling In Your Application

posted Aug 25, 2015, 8:24 AM by Victor Zakharov   [ updated Aug 25, 2015, 8:25 AM ]

This command line tool did not work for me (access denied):
This Windows UI tool worked perfectly:

It has less options, but it does a read lock, which is what I was looking for.

C# - Normalize Whitespace Inside String

posted Aug 14, 2015, 11:42 AM by Victor Zakharov   [ updated Aug 14, 2015, 11:42 AM ]

Simple task - replace all sequential whitespace (tabs, spaces, newlines) with your character of choice, usually a space.
Fact - StackOverflow is on top in google results, when searching for "C# normalize whitespace". Namely:
Why this article? Highest voted answers are not the best performing, and some answers are just wrong.
I propose a solution which is based on this StackOverflow answer. Referenced answer has a problem - it fails when input = " " (single space).
I wasn't sure about it being the only unhandled corner case, so I changed method to use StringBuilder, to simplify string manipulation. Probably the same level of performance, just easier to read.
Below version should be much faster than using Regex (link 1 - highest voted) and slightly faster than NormalizeWithSplitAndJoin by @JonSkeet.
/// <summary>
///  Any consecutive white-space (including tabs, newlines) is replaced with whatever is in normalizeTo.
/// </summary>
/// <param name="input">Input string.</param>
/// <param name="normalizeTo">Character which is replacing whitespace.</param>
/// <remarks>Based on </remarks>
private static string NormalizeWhiteSpace(string input, char normalizeTo = ' ')
    if (string.IsNullOrEmpty(input))
        return string.Empty;

    StringBuilder output = new StringBuilder();
    bool skipped = false;

    foreach (char c in input)
        if (char.IsWhiteSpace(c))
            if (!skipped)
                skipped = true;
            skipped = false;

    return output.ToString();

C# - Capture Full Stack Trace For Exception Inside Catch Block

posted Aug 13, 2015, 2:03 PM by Victor Zakharov   [ updated Aug 13, 2015, 2:06 PM ]

The problem is very clearly described in this article on CodeProject:
In short, when you catch the exception, you only have stack trace relative to the catch point. Why is this important?

For example, suppose the error occurs when sending email and this is a non-critical part of your application.
Let's say you send confirmation emails to clients as part of the ordering process.
Yes, it's bad if the email cannot reach your client (say, their email address is invalid), but your web server should not crash because of that.

In most generic case, you want the full stack trace, i.e. to investigate later, but the application should continue running (skipping the faulted area).
Problem here is that with how .NET exceptions work you either get the full trace (global exception handler) OR your application continues running and you only get partial stack trace.
Depending on where you would like to log your error, partial stack trace can be completely useless to developer.

If you want to have full trace, i.e. for logging purposes, and have your application continue running, you will need to write custom code.
The approach I used below is using Environment.StackTrace, wiping unnecessary information from there (external calls - without a line number), and merging with stack trace coming from ex object inside the catch block.
Another possible way to solve it is by using StackTrace object, if you want to go this direction, check this article:
I tried using StackTrace, looks like you would need a custom ToString() to mimic ex.StackTrace output. Otherwise the stack trace information is not full. To me it was not worth the extra effort.
Below is an extension method I wrote wrapped in a static class (C#).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

/// <summary>
///  Extension methods for Exception class.
/// </summary>
static class ExceptionExtensions
    /// <summary>
    ///  Provides full stack trace for the exception that occurred.
    /// </summary>
    /// <param name="exception">Exception object.</param>
    /// <param name="environmentStackTrace">Environment stack trace, for pulling additional stack frames.</param>
    public static string ToLogString(this Exception exception, string environmentStackTrace)
        List<string> environmentStackTraceLines = ExceptionExtensions.GetUserStackTraceLines(environmentStackTrace);

        List<string> stackTraceLines = ExceptionExtensions.GetStackTraceLines(exception.StackTrace);

        string fullStackTrace = String.Join(Environment.NewLine, stackTraceLines);
        string logMessage = exception.Message + Environment.NewLine + fullStackTrace;
        return logMessage;

    /// <summary>
    ///  Gets a list of stack frame lines, as strings.
    /// </summary>
    /// <param name="stackTrace">Stack trace string.</param>
    private static List<string> GetStackTraceLines(string stackTrace)
        return stackTrace.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList();

    /// <summary>
    ///  Gets a list of stack frame lines, as strings, only including those for which line number is known.
    /// </summary>
    /// <param name="fullStackTrace">Full stack trace, including external code.</param>
    private static List<string> GetUserStackTraceLines(string fullStackTrace)
        List<string> outputList = new List<string>();
        Regex regex = new Regex(@"([^\)]*\)) in (.*):line (\d)*$");

        List<string> stackTraceLines = ExceptionExtensions.GetStackTraceLines(fullStackTrace);
        foreach (string stackTraceLine in stackTraceLines)
            if (!regex.IsMatch(stackTraceLine))


        return outputList;
Usage is simple:
    //some code here throws exception 
catch (Exception ex)
    string logMessage = ex.ToLogString(Environment.StackTrace);
    //write logMessage to file

ADATA UV131 32GB USB3.0 Flash Drive performance

posted Dec 20, 2014, 10:35 AM by Victor Zakharov   [ updated Dec 20, 2014, 10:35 AM ]

This is a well-built metal case unibody flash drive (rugged zinc alloy, according to the manufacturer).
It was actually slightly smaller than it looked on the pictures.
I got a 32GB version for less than 15 CAD before tax, with shipping included.

It's not the fastest flash drive I've seen on the market, but for the money, I think it's a good investment.

Here are the numbers measured with CrystalDiskMark, USB2 and USB3 respectively:

1-10 of 132