Tech Blog

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'));
    clickArea.addClass('click-area');
    clickArea.appendTo(sliderControl);
});

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:
- http://mkrtchyan.co.uk/extending-the-clickable-area-for-jquery-ui-slider/


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

alert("Hello");

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) {
        this.name = name;
    }

    sayHello() {
        alert("Hello, " + this.name);
    }
}

var a = new SayHello("Victor");
a.sayHello();

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. 

Summary
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 http://stackoverflow.com/a/25023688/897326 </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)
            {
                output.Append(normalizeTo);
                skipped = true;
            }
        }
        else
        {
            skipped = false;
            output.Append(c);
        }
    }

    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);
        environmentStackTraceLines.RemoveAt(0);

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

        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))
            {
                continue;
            }

            outputList.Add(stackTraceLine);
        }

        return outputList;
    }
}
Usage is simple:
try
{
    //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:

Corsair Flash Voyager GO USB3 Mini Flash Drive 64GB - Performance Test

posted Nov 22, 2014, 5:25 PM by Victor Zakharov   [ updated Nov 22, 2014, 5:26 PM ]

When I was making a decision to buy this little thing, my only concern was performance.
I found different figures, going as high as 150MB read speed over USB3 (this is a USB3 drive).
Here are my results, measured over USB3 as well as USB2 (two tests). Not a significant difference.


Did I make the right choice, even though the speeds are lower than I expected?
Absolutely. It's still the fastest mini flash drive I've owned. I paid 37 CAD + tax, for a 64GB flash drive, shipping to Mississauga was free.
And yes, it's tiny, this is compared to my index finger, as small as the USB connector can be.

 

Fix Ugly Fonts in Google Chrome 37

posted Sep 5, 2014, 6:49 PM by Victor Zakharov   [ updated Sep 5, 2014, 6:49 PM ]

Problem - after updating to the latest Chrome version (37), fonts look ugly.
I'm using a non-standard 125% Windows DPI, it could be why they are ugly for me.


type "chrome://flags/#disable-direct-write" in your Chrome window and click "Enable" on "Disable DirectWrite". DirectWrite should be off.

1-10 of 130