Tag Archives: tip

The case of the missing ‘Process’ Performance counter

I recently had the need to do some monitoring of the Explorer.exe process (like one of the Windows 10 Insider Preview bugs) that every so often went bananas (Minions would like it…) for no reason at all. This is a pain if you have other processes on the same machine that is sensitive to things like running in ‘low’ priority (Like Boinc workloads). This effectively block other processes to run or just plain make the whole machine feel slow and sluggish.

Then I discovered the problem that perfmon could not ‘see’ the ‘Process’ category. This is weird since I  thought this would be one of the most basic performance counters that Windows always had and probably still have. Somehow the ‘Process’ category disappeared or became corrupted or something – I thought.

Anyway, after some digging around (aka Google) I found an old article about similar issues people had with older versions of Windows (even server versions). The culprit (at least in this case) was that for some reason the registry key to enable the ‘Process’ category was disabled. I have no idea how that happen (no I deny any involvement whatsoever… 🙂 ).

To fix do this: (standard registry editing disclaimer: do it at your own risk).

  1. Open Regedit
  2. Find the key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PerfProc\Performance
  3. Check the value of ‘Disable Performance Counters’. If it is anything but 0 it means it is disabled.
  4. Change the value to 0 and save.
  5. Restart whatever performance counter monitoring tool you are using since it will not be aware of the change until that process restart.
  6. Jump up and down for joy! (just because you can).

 

List all .Net versions using PowerShell

A quick tip (script) how to list all the .Net (major) versions of a list of machines.

$serverListFile = "<Path to file>\computers.txt";
$computers = Get-Content -path $serverListFile

$BASEDOTNETPATH = "\c$\Windows\Microsoft.NET\Framework\"

function CheckNet45($computerName){
  $NETROOTKEY = "SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4"
  $keyname = $NETROOTKEY + "\\Full"
  try{
    $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine", $computerName)
    if ($reg -ne $null){
      if ($reg.OpenSubKey($keyname).GetValue("Version").ToString().StartsWith("4.5")){
        return $True
      }
    }
  }
  catch {
    #do nothing
  }
  return $False
}

foreach($computer in $computers)
{
  $computer
  $ok = Test-Connection $computer -Count 1 -Quiet
  if ($ok) {
    $computerBasePath = "\\" + $computer + $BASEDOTNETPATH
    $versionStr = ""
    if (Test-Path ($computerBasePath + "v1.0.3705")){
      $versionStr = $versionStr + "1.0,"
    }
    if (Test-Path ($computerBasePath + "v1.1.4322")){
      $versionStr = $versionStr + "1.1,"
    }
    if (Test-Path ($computerBasePath + "v2.0.50727")){
      $versionStr = $versionStr + "2.0,"
    }
    if (Test-Path ($computerBasePath + "v3.0")){
      $versionStr = $versionStr + "3.0,"
    }
    if (Test-Path ($computerBasePath + "v3.5")){
      $versionStr = $versionStr + "3.5,"
    }
    if (Test-Path ($computerBasePath + "v4.0.30319")){
      $versionStr = $versionStr + "4.0,"

      if (CheckNet45($computer)){
        $versionStr = $versionStr + "4.5,"
      }
    }
    $versionStr = $versionStr.TrimEnd(',')
    "  Installed version(s): " + $versionStr

  }
  else{
   " Is not pingable!"
  }
}

All you have to do is create a text file with a list of machine names (one name per line). It does assume you have Admin rights so you can access the C$ share and read the remote registries.

Deleting a folder with path that is too long

Just a quick tip I came across today after having a problem where I found a directory where some tool went nuts and kept on creating subdirectories recursively. Trying to delete this directory will give you an error – something like ‘Path is too long…’

Lets say the path is something like d:\directory1\directory1\directory1\directory1…..\directory1

Windows Explorer and even Command prompt won’t allow you to delete d:\dir1 (No not even right-click delete will work).

A simple solution is to recursively go and rename all the directories to something much shorter so the overall length is less that the maximum (260 characters).

Like this: rename d:\directory1 0  , rename d:\0\directory1 0 etc.

The end result should be like this: d:\0\0\0\0… \0

Now you can simply delete it in Windows Explorer without any ‘Path Too long’ errors.

Should I handle Exceptions or not?

I’ll start this post with a statement or answer that might seem controversial.

The answer is ‘NO’

Why? Let me explain. If your code has reached a state where an Exception has been thrown it means you have already missed something (possible) important that should have been addressed. Sure, throwing (excuse the pun) a ‘try… catch’ around every block of code is nice and all – and you should do it anyway (for other reasons) but it is no excuse for writing bad code.

More details

One reason I say these things I recently (re)discovered myself… again is that ‘Performance’ in an application can greatly be influenced by exceptions since the whole process of encountering/throwing an exception in code is a slow thing. When you have code that relies on catching an exception in order to handle an (possibly) expected condition of some variables it is a sign that you are doing it wrong… It may not be a big issue if the affected code is called only once in a blue moon but once it is in a section that is called repeatedly and is expected to perform at speed it becomes a huge issue.

Have a look at this code. It will run fine but and actually be usable but…

try
{
   SomeType tp = SomeObject.SomeVar;
}
catch // null reference exception or something expected the first time
{
  SomeObject = new SomeObjectType();
  ...
}

Now look at a better way

if (SomeObject == null)

SomeObject = new SomeObjectType();

SomeType tp = SomeObject.SomeVar;

...

This code will actually run faster and does not rely on an Exception to handle something that should be done right to start with.

Ok, there you have it…

Passing a ‘Method’ as parameter in C#

This is actually nothing new but sometimes you might still need a quick reference for to remember how to do this quickly… Say you have a generic class that does something like generating a report and display it somehow (or save or whatever the class do) and want all the ‘calling classes’ to just pass the ‘Method’ that it must ‘run’ in order to generate the report. Yes there are probably nice and fancy tools these days that could also do it if you have the mulla for it…

A solution is to use Anonymous methods that has been with C# (.Net) since version 3 of something.

Reporter r = new Reporter();
r.Report = delegate
{
string stuff = "example report yada yada yada";
return stuff;
}
r.Show();

The generic class that provides the ‘generic’ functionality can then look something like this using a defined delegate so it knows what output it will receive when ‘running’ the method.

public delegate string RefreshActionDelegate();
class Reporter
{
    public RefreshActionDelegate Report { get; set; }

    public Show()
    {
       if (Report != null)
       {
          string theContent = Report();
          DoSomethingWithContent(theContent);
       }
    }
}

This is just a quick example but it shows how you can use the main ‘generic’ class from multiple places each time just passing a different ‘Method’ with its own functionality.

Useful Visual Studio 2010 Keyboard Shortcuts

This might be a bit old news for some but for those that forgot or never knew – here is a quick reference link on keyboard shortcuts inside Visual Studio.

http://microsoftfeed.com/2012/30-useful-visual-studio-2010-keyboard-shortcuts

Firefox tip

Quick tip: This might only work for version 10 (not tested otherwise) but you can type ‘about:memory’ in the URL bar of the browser to see details of what and how memory is used. Nice!

Advanced debugging in VS2010 tips

Just a quick link to an article on codeproject –  Advanced Debugging in Visual Studio

Because you are never to old to learn… or too young!

Creating daily log files

In the (wild) old days when the only thing we had to work with computers were the command line we use to store output of important processes to a (text)file so it can be viewed and worked on afterwards. Event today in a support and administration environment these skills are very handy.

The process of doing this was/is called ‘output direction’ or ‘pipe output to’ since the standard output ‘device’ was the console (command window). So taking the application output away from the console meant redirecting it to a ‘file’ – since in a sense the ‘console’ could also be seen as a file that gets stuff outputted to (a temporary one).

Anyway, say you want to save the output of a command line utility like ‘dir’ to a file – you would use the following:

dir *.txt > dir.txt

All this does is execute the normal ‘dir *.txt’ command but store the output to the file ‘dir.txt’. This only outputs the standard ‘console output’ to the text file. If the output file already exists it gets overwritten. Actually there are two types of ‘standard outputs’: 1 – the normal successful and 2 – the standard error output. Using only the ‘>’ operator is just a shortcut for ‘1>’ which only outputs the ‘standard successful’ output i.e. the previous example is the same as:

dir *.txt 1> dir.txt

The second type of output is the ‘standard error’ output. To get this output you use the ‘2>’ operator e.g.

Someexe.exe 2> errors.txt

If you want to combine the outputs – that is both normal and error outputs you can use this:

Someexe.exe > errors.txt 2>&1

Lets say you want to keep a history of all previous outputs – then you want to use the ‘append’ operator ‘>>’:

Someexe.exe >> output.txt

If the file ‘output.txt’ does not exist yet it will be created. Otherwise and new output will simply be appended. If you want to combine all of these – that is combine normal and error ouputs plus append to the output file you can use this:

Someexe.exe >> output.txt 2>&1

Now, say you want to use part of the date when creating, listing etc. files. Unfortunately this tip depends on the date-time format settings of the machine you are running it on. For my example I use the ‘yyyy/mm/dd‘ format. To get the year you can use the following:

set year=%date:~0,4%

To get the month you can use ‘%date:~5,2%’ or day ‘%date:~8,2%’ – again this only works for the ‘yyyy/mm/dd’ format. If your date-time format is different you have to change the ‘~x,y‘ parts where x is ‘from’ and y is ‘to’ character positions.

Now using the example above you can use:

dir %year%*.txt

to file all files with a name that start with the current year (e.g. 2012blablabla.txt)

You can use the same technique when creating output files, e.g.

dir *.txt > %year%List.txt

This way you can create daily log files e.g.

set year=%date:~0,4%
set month=%date:~5,2%
set day=%date:~8,2%
Someexe.exe >> %year%%month%%day%.log

Mission accomplished… for now.

Launch apps as Admin without prompt

This is a tip intended to ease the pain of continuously having to click the ‘Yes’ prompt when you want to launch an app in ‘Admin mode’.

The trick is to use the built-in Windows Task scheduler.

1. First you create a new task (not a basic task) and specify a name e.g. ‘CommandLine’ plus check the ‘Run with highest privileges’ check box.

2. On the actions tab you add a ‘Start a program’ action and select the executable e.g.’C:\Windows\System32\cmd.exe

3. Optionally under the Settings tab you can choose ‘Run a new instance in parallel’so you can run multiple instances of the app if required.

4. Click OK to create the task

Next you create a Windows shortcut (say on the desktop by right clicking and choosing new -> Shortcut)

1. Specify the following as the ‘Target’: e.g.  ‘C:\Windows\System32\schtasks.exe /run /tn CommandLine
Pay attention that the last parameter must match the task name.

2. You may want to manually select an icon for the shortcut as it won’t select the app icon by itself.

Now if you click (double-click) the shortcut a brief command line window before opening your app (in admin mode) – without prompting you! One big disadvantage is that you cannot pass command line parameters this way so launching say notepad with a specified txt file this way won’t work.

Of course, it would have been easier if MS built in a way you can choose (at your own risk) which apps you would like to launch in admin mode without prompting. There is a potential security risk in allowing functionality like that but if they wanted to it could be done with a big warning dialog at the start – that tells you you’re doing this at your own risk. It could use something like signing the required exe with a local (only) certificate to mark it trusted only on the local machine or generating a hash that gets stored in an encrypted system location or something, to tell the OS that particular exe can be trusted (when launched). The way to set up this hash and stuff would need to be a secure process in itself (requiring a ‘human’ user input) and letting you jump through a couple of hoops – once off. The idea is to allow only that particular exe on the particular machine as trusted. Copying it to another machine or changing it would require setting up the ‘trust’ again. Just an idea… (throwing a hint… to Microsoft)