Welcome to MSDN Blogs Sign in | Join | Help

PowerShell indentation for VIM - version 2.0

In continuation to my previous post, I've been working lately on fixes to my PowerShell indentation and they are finally complete.

Right now it looks like everything is indented correctly and i've uploaded the new version (2.0) to vim.org site.

I had 39 downloads for version 1.0 (which is pretty impressive for something as niche as writing the most modern script language using one of the oldest editors around). Hopefully version 2.0 will be just as popular.

So, go ahead and download the new version, it has everything you ever wanted from a PowerShell indentation script.

Download Here

Oh, and please rate if you find it useful.

Posted by Lior Elia | 2 Comments
Filed under: ,

PowerShell indentation file for VIM

I've been writing my PowerShell scripts in VIM for a while now.
I've downloaded the syntax, ftplugin and indent scripts from vim site but I've found one annoying problem.
The original ps1.vim indent script was mostly a stub that assumed PowerShell indentation is exactly the same as C/C++/C#.
Well, mostly it is. There is one little (but annoying) difference.
In PowerShell - a line beginning with the '#' sign is a comment line and should be indented as any other code line in that indentation level.
In the C language variants, however, lines beginning with '#' are precompiler lines which are never indented.

And so, as the old saying goes - "Necessity is the mother of all inventions" - i sat down this morning and started to write my very first VIM script: PowerShell indentation.

You can find it in the scripts repository here. Free for all.
I think that for a first-timer it's not too bad.
Please let me know if you find any bugs or wish to add functionality (but I don't promise anything).

Posted by Lior Elia | 0 Comments
Filed under: ,

Finding lines NOT containing certain words - RegEx magic

Regular expressions are full of surprises. Just when you thought you’ve seen it all, out comes a “what if I want to do this, but also that and match these but not those” - and the worse thing is that it is usually my idea in the first place!

So here’s an interesting one: While working on the FxCop reports for our product, I wanted to find (and eventually replace) all public members in the code.
My first thought was this:

public.*;$

But this expression brought back thousands of false-positives like delegates, events, read-only fields, constants, etc. which are perfectly legal, even under the strict rules of FxCop. I needed something that would filter out the lines that contain certain keywords.

After rummaging the MSDN page for regular expressions and some trial and error I found that the following regular expression did the trick quite nicely, while keeping a good false-positive ratio:

public ~(const|event|delegate|readonly|static readonly|static extern|abstract).*;$

In English: look for lines with the word public, not followed by any of the words const, event, delegate, etc. and that end with ';'

The rarely used  ~() syntax allows for specifying words that will break the match if found in the specified location.

You can also modify the above RegEx to support replacing the faulty line with auto-implemented properties (new in .NET 3.0).

{public ~(const|event|delegate|readonly|static readonly|static extern|abstract).*};$ 

And use the following string in the “Replace with” field to make an auto-implemented property:

\1 { get; set; }

A word of warning: Do not run a solution-wide find-replace using this method, as you might break things without noticing. Hand-pick your changes!

Posted by Lior Elia | 0 Comments
Filed under:

What, no HKCR in PowerShell?

This article was originally published here. 

Introduction

If you’ve been working with PowerShell for registry access, you’ve probably noticed by now that something is missing.

PowerShell has two registry “drives” defined:

HKLM for HKEY_LOCAL_MACHINE

HKCU for HKEY_CURRENT_USER

The other registry roots are not defined.

The story behind this post

A while ago, a colleague of mine was trying to find and remove some entries from HKEY_CLASSES_ROOT and was having a hard time using RegEdit.

So, I offered my help, while promoting my latest obsession – PowerShell.

Imagine my embarrassment when I found out a minute later that there is no HKCR drive defined in PowerShell.

The solution

Fear not, my friends, for the HKLM and HKCU are merely there for convenience. 

You can define by yourself, with a simple command, any registry drive you want.

So, before working on the HKCR drive, we simply define it like so:

New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT

New-PSDrive

-Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT

Now, you have full access to HKEY_CLASSES_ROOT via HKCR.

Have fun. Be responsible.

P.S.

While on this subject, Ever noticed how you can’t use ‘-filter’ with the ‘dir’ command on registry drives?

Well, you can pipe the results through the question mark filter to do the same job, though I’m quite sure there’s some performance penalty. Still, better than the old RegEdit.exe, right?

Here’s an example:

cd HKLM:\SOFTWARE\

dir | ?{$_.Name -like “*Int*“}

Posted by Lior Elia | 0 Comments
Filed under: ,

Microsoft bing to replace Google as favorite search engine

I-Love-Bing

Well, at least on my computers.
I’ve been using Google as my search engine for an eternity now. Frankly, I don’t even remember what came before that. It was that long ago. Of course, being the Microsoft enthusiast that I am - I gave live.com a ping now and then, promising myself to try it for a few days and giving up rather shortly after. Yes, I admit, there was never a click between me and Microsoft’s search engine.

Then came “bing”

Given the supposition that bing is “live.com revamped” and that it is probably emerging from the very same codebase, I had little expectations from the new search engine. An improved live.com? possibly. A re-packaged, re-branded but otherwise unchanged live.com? probably. An exciting new search engine that will replace Google search in my world? well, that thought didn’t even occur to me. That is, until I actually used bing.

Bing is fast, smart, versatile, easy to use, and has tons of useful features. Among the most notable features I count:

Smart video preview: Hover your mouse cursor on the video thumbnail and you’ll get an instant preview of several scenes from that video, with sound, inside the thumbnail.

Image search to die for:

  1. Several zoom levels for image thumbnails, with and without textual details. Changing zoom level is done instantly, no waiting for reload.
  2. Filter by size, layout, color, style (photo or illustration), and “people” which lets you filter images showing just faces or head & shoulders.
  3. Seamless, continuous results scrolling - just scroll down with your mouse wheel and more images are revealed. All the results are in a single page but since they load “on-demand” when scrolling to them - there’s no delay in the search.
  4. Hover over thumbnail to expose more details and actions - like getting similar results.

Suggestions and auto-corrections - Yes, I know Google had that for a long time, now bing has that too.

There are other interesting features, like the maps, news and shopping search categories, but since I’m not actually living in the states, it’s of little use to me.

In addition to these features, I must point out that bing just looks great. It is certainly more colorful and interesting than the competition’s Spartan search page. And yet, it loads (almost) instantly.

So, in conclusion: There’s a new search engine in town, and it’s awesome. bing!

Posted by Lior Elia | 1 Comments
Filed under: , ,

Introducing new blog series - Bag of toys

PS C#

Introduction

I have many PowerShell scripts and functions lying around, some are preloaded in my profile, some I just use from time to time and can be found in PowerShell’s folder on one of my computers.

Every time I am faced with a computer task (or a whim) that takes more then 2 minutes to accomplish by hand – I turn to PowerShell (or VIM console for text manipulations, but that’s another story).

So, I decided to share these tiny-but-useful scripts and functions by launching a blog series named “Bag of toys”.

Script #1 – Get your external IP

This little one-liner tells you your external IP address, the one exposed to the world, not the one you got from your ISP (which is much easier to find out, using IpConfig util).

(New-Object net.webclient).downloadstring("http://checkip.dyndns.com") -replace "[^\d\.]"

While this is quite self-explanatory to most PowerShell users, let’s just do a quick run-through to make sure we covered all the bases. So, from left to right:

  1. We create a new WebClient object.
  2. And call its DownloadString method to get a string response from a web server.
  3. DynDns service is kind enough to expose a rather straight-forward url for getting our IP.
  4. If you try to execute this URL in your browser, you’ll get a plain-text page with the text - “Current IP Address: your-ip-address
  5. We don’t want the text, just the IP itself, so we use a -replace to remove any character that is neither a digit (\d) nor a dot.
Posted by Lior Elia | 1 Comments
Filed under: , , ,

Creating a debugger visualizer for Visual Studio (C# tutorial)

This article was originally published here.

What is a “debugger visualizer”?

Here’s a direct quote from MSDN:

A visualizer creates a dialog box or other interface to displays a variable or object in a meaningful way that is appropriate to its data type. For example, an HTML visualizer interprets an HTML string and displays the result as it would appear in a browser window, a bitmap visualizer interprets a bitmap structure and displays the graphic it represents, and so on. Some visualizers allow you to edit as well as view the data.

Considering the context – custom debugger tools – creating a custom debugger visualizer is surprisingly easy. I would expect this to involve native code, COM objects, cumbersome registry editing and a week at a forced labor camp, or any combination of the above. Turns out it’s a walk in the park.

Wanna get started?

For those of you eager to begin, here is a summary of the steps needed. I’ll explain everything in detail after the jump.

  1. Create a class library project.
  2. Add reference to Microsoft.VisualStudio.DebuggerVisualizers (.NET reference)
  3. Add reference to System.Windows.Forms (.NET reference)
  4. Create a class that inherits from DialogDebuggerVisualizer
  5. Implement the single method required (very easy implementation).
  6. Add the DebuggerVisualizer assembly attribute to indicate which type are you handling and what is the class handling that type.
  7. Build the DLL and copy it to <My Documents>\Visual Studio 2005\Visualizers
  8. When you’re debugging – hover over a variable of the type you’re handling and click the magnifying glass icon.

That’s all you need to do.

Details explained

Steps 1-4 in the above list are pretty straight forward, so let’s jump right into step 5.

I’ve decided to create my visualizer for the type Color. The visualizer will display a small form filled with the color specified in the variable inspected by the debugger.

   1:  using System.Diagnostics;
   2:  using System.Drawing; // add reference to System.Drawing .net lib for this line to compile.
   3:  using System.Windows.Forms;
   4:  using Microsoft.VisualStudio.DebuggerVisualizers;
   5:  [assembly : DebuggerVisualizer(
   6:    typeof (ColorVisualizer),
   7:    Target = typeof (Color),
   8:    Description = "Color Visualizer")]
   9:   
  10:  public class ColorVisualizer : DialogDebuggerVisualizer {
  11:    protected override void Show(IDialogVisualizerService svc, IVisualizerObjectProvider provider) {
  12:      Color c = (Color) provider.GetObject();
  13:      using (Form form = new Form()) {
  14:        form.Text = "Color Visualizer - by Lior Elia";
  15:        form.BackColor = c;
  16:        form.Size = new Size(400, 400);
  17:        svc.ShowDialog(form);
  18:      }
  19:    }
  20:  }
  21:   

As you can see, the code is really straight forward. Get the object, create a form (can be a pre-prepared form if it's a complex visualizer) and display the data. That's it!

Another interesting thing to notice is regarding steps 7-8. You don't need to restart visual studio in order to use your new visualizer. This means that you can make changes and fixes to your code and just drop the new DLL in the visualizers folder in order for Visual Studio to use it. It's that easy!

Important note: you need a reference to System.Drawing for the Color class to be accessible in your code.

Converting icons from 32bit to 16bit

The story behind this post

Last week I ran into an interesting bug at work. We were extracting icons on one windows machine and saving them on an another windows machine as part of one of our features. This was a mechanism developed a while ago and it worked fine so far. Recently though, we began to notice certain icons on the target machine had variations of pinkish overlay clearly visible. Upon closer inspection of the icons and comparison to the originals it became clear that semi-transparent areas of the icon did not retain their transparency property at all. Instead, the color used for transparency marking (traditionally cyan) was saved to the colors layer; creating a visible pink-like overlay in the relevant areas of the icon.

A little more testing and we found the culprit, sort of. We know it has something to do with moving an icon from a 16bit color depth machine to a 32bit one. Normally, we would investigate further and try to pin-point the root of this problem. However, since we are planning to move both systems to 32 bit color depth soon (before the product is released) we just needed something that would work for now, and that would be easy to cancel out once we make the move to 32bit. In short, a band aid.

How we got to downgrading the color bit depth of an icon

Now, if you read the previous section, you’d be a bit surprised to find out we want to downgrade the icon from 32bit to 16bit. Wasn’t it the other way around? you ask. And you’re right, we are extracting the icon on the 16bit machine, and my instinct was converting 16bit to 32bit. However, on our specific configuration (which is a bit non-standard) we need to do the exact opposite. We extract the icon from whatever resource file it is in (exe, dll, icon file, icon library) and convert it to 16bit. When we send this converted icon to the 32bit machine – the pink overlay is gone! As simple as that.

I’d like to add some final disclaimer note here though: Like I mentioned before, the configuration on the source machine is rather not-standard and there might be some bit depth duality in that system where several processes or even sessions run a different color bit depth at the same time. This might have caused that pink overlay anomaly but we’re not sure, and as I said in the previous section, it is not worth pursuing at the moment.

Converting an icon using the Bitmap class

It’s really quite easy. The Bitmap class contains a clone method which allows you to control the result’s bit depth as well as other useful parameters. The following code is a simplification of what we did in production code, done for clarity.

 
   1:  using System.Drawing;
   2:  using System.Drawing.Imaging;
   3:  using System.IO;
   4:   
   5:  class Sample {
   6:      public void ConvertIcon() {
   7:   
   8:          // Loading the original icon
   9:          Icon icon = new Icon("originalIcon.ico");
  10:   
  11:          // Converting it to bitmap, to allow image manipulation
  12:          Bitmap bitmap = icon.ToBitmap();
  13:   
  14:          // This rectangle has no meaning for us, it just has to encompass the entire image
  15:          Rectangle r = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
  16:   
  17:          // Using the clone method to convert the icon
  18:          Bitmap bmp = bitmap.Clone(r, PixelFormat.Format16bppArgb1555);
  19:   
  20:          // And we claim back the icon (to retain the ico format) and save it.
  21:          icon = Icon.FromHandle(bmp.GetHicon());
  22:          FileStream stream = new FileStream("convertedIcon.ico", FileMode.Create);
  23:          icon.Save(stream);
  24:          stream.Close();
  25:      }
  26:  }
Posted by Lior Elia | 2 Comments

The unwritten rules of changing the console window's size

When changing the console window size in PowerShell you must also change the underlying buffer size. Doing so might require a bit more than just copy-paste-replace-window-keyword-with-buffer-keyword. There are apparently special rules for doing this without failing.

 

These are the unwritten (but carefully upheld) rules of resizing the console window via a PowerShell script:

   1. The buffer width can't be resized to be narrower  than the window's current width.
   2. The window's width can't be resized to be wider  than the buffer's current width.

So, if you want to make the console window narrower, you set the window size first.
But if you want to make the console window wider, you must set the buffer size first.


Try not to follow these rules - and you get a lovely exception + the console window isn't resized.

Now we have only one problem - The starting width of the console window may vary on different machines/resolutions.

The solution - check the width before setting and act accordingly.

Here's an example:

   1:  $width = 127
   2:  $sizeWindow = new-object System.Management.Automation.Host.Size $width,50
   3:  $sizeBuffer = new-object System.Management.Automation.Host.Size $width,9999
   4:   
   5:  if ($Host.UI.RawUI.WindowSize.width -gt $width) {
   6:      $Host.UI.RawUI.WindowSize = $sizeWindow
   7:      $Host.UI.RawUI.BufferSize = $sizeBuffer
   8:  }
   9:  else {
  10:      $Host.UI.RawUI.BufferSize = $sizeBuffer
  11:      $Host.UI.RawUI.WindowSize = $sizeWindow
  12:  }
Posted by Lior Elia | 0 Comments
Filed under:

Hello MS World (ver 1.1)

Writing the first post in my blog as "Hello World" became a habit, which probably means I should stop moving blogs all the time.

That said, I'm happy to open my brand new spanking MSDN blog.

It's just a move from one Microsoft site to another (more global and more technical) but just the same, I had to do the inevitable, and post a "Hello Wolrd" item.

As before, you are welcome to read the (updated) about page.

You may also want to read past posts in my previous blog.

Have fun reading, and always remember: We are here to learn, Knowledge is Power.

Lior

Posted by Lior Elia | 0 Comments
 
Page view tracker