PowerShell: Writing code snippets in the ISE

This is my scratchpad for a simple talk I’ll be doing on creating code snippets for use in the ISE.

Code

PsPresentation01

Code

PsPresentation02.PNG

code

PsPresentation05.PNG

Example with intentional error to show the contrast:

PsPresentation04.PNG

Advertisements

VSCode: richer snippets

Summary: I want to be able to use or define a constructor snippet in Visual Studio Code for C#. However it achieves it, that means when I press a reserved (by me, if I’m defining it) set of keystrokes, then it has to determine the class name, which at that point is only in memory? And therefore needs to be reflected over? In fact the last question is supposition and pointless.. but it’s staying there. 🙂 Regardless, I feel a bit frustrated that I have burned 3 hours and got nowhere. Diddums.

Like the ones in fullfat Visual Studio, that’s what I need. e.g. ctor. Means nothing in VSCode evidently.
This is the ctor snippet in VS-speak:

 

snippetvs01

I thought I read that VSCode supported a richer syntax, so time to put that to the test.

Firstly there is this link:

snippetvs02

Not a lot right now then. And what is there just uses the lean syntax I have used before. So no use.

Then we have the tutorial here, which contains this promising thang…

So first try

npm install -g yo

Which in my case gives me:

Your npm version is outdated.

Upgrade to the latest version by running:
npm install -g npm

OK…Getting annoyed now:

snippetvs04

Maybe it was my own fault for doing it through PowerShell – now trying cmd/Node:

snippetvs05

snippetvs06

Seems better:

snippetvs07

Now try
npm install -g generator-code

snippetvs08

Now

yo code

snippetvs09

snippetvs10

Do a find for folders with .tmSnippet…

snippetvs11

C:\Users\Dennis\AppData\Roaming\npm\node_modules\generator-code\test\fixtures\tmsnippets

Plug that in:

snippetvs12

snippetvs13

snippetvs14

Really unhelpful. Exactly where have you installed it? Can’t find it using Windows Search, so let’s try PowerShell:

gci -Recurse -Path . -Filter “vsc-extension-quickstart.md” -ErrorAction SilentlyContinue

snippetvs15

snippetvs16

snippetvs17
# Welcome to your VS Code Extension

## What’s in the folder
* This folder contains all of the files necessary for your extension
* `package.json` – this is the manifest file that defines the location of the snippet file
and specifies the language of the snippets
* `snippets/snippets.json` – the file containing all snippets

## Get up and running straight away
* press `F5` to open a new window with your extension loaded
* create a new file with a file name suffix matching your language
* verify that your snippets are proposed on intellisense

## Make changes
* you can relaunch the extension from the debug toolbar after making changes to the files listed above
* you can also reload (`Ctrl+R` or `Cmd+R` on Mac) the VS Code window with your extension to load your changes

## Install your extension
* To start using your extension with Visual Studio Code copy it into the /.vscode/extensions folder and restart Code.
* To share your extension with the world, read on https://code.visualstudio.com/docs about publishing an extension.

https://code.visualstudio.com/docs/tools/yocode

https://code.visualstudio.com/docs/tools/samples

 

https://code.visualstudio.com/docs/editor/extension-gallery

Let’s try this route for an example:

snippetvs18

 

snippetvs19

So the C# XML docs extension clearly works… I just have to work out how now, and then I can use that for ctor. Another night:

snippetvs21

In fact as is often the way, now I am out of time, I’ve found possibly the most useful entries:

https://code.visualstudio.com/docs/customization/userdefinedsnippets

https://code.visualstudio.com/docs/editor/editingevolved

 

 

 

Visual Studio Code: code snippets

Found this (admittedly staring me in the face right now… but it wasn’t a while back, I’m sure)

So looking in VSCode:

So lest I make a mess of it, quick back up of the text:

{
// Place your snippets for C# here. Each snippet is defined under a snippet name and has a prefix, body and
// description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
// $1, $2 for tab stops, ${id} and ${id:label} and ${1:label} for variables. Variables with the same id are connected.
// Example:
"Print to console": {
"prefix": "log",
"body": [
"console.log('$1');",
"$2"
],
"description": "Log output to console"
}

Then add a simple property snippet, using a slightly different shortcut than [prop], as that automatically gets picked up, I’ll find out how another time.

You don’t need to restart VSCode to get this working. It updates on the fly. The ONE thing this lacks right now is the ReSharper type macro language that is very useful for doing the private backing field/public property thing (I know what I mean 🙂 )

"Simple Property by Dennis": {
"prefix": "propdennis",
"body": [
"public ${type:string} ${name} {get;set;}"
],
"description": "Create a Dennis simple property"
}


In fact I will show you exactly what I mean...

My standards say that a private variable starts with an underscore followed by a lower case character, as shown above. However, the best that I can achieve with this snippet manager, with the minimum number of keystrokes, is this, because unlike ReSharper, there is no macro language or mechanism to achieve the above, so I get this:

CodeSnippetsinVsCode11

And this is how you achieve the immediately above anyway:

CodeSnippetsinVsCode12

In the docs, they talk about using $1 etc to represent tab-stops, but that doesn’t work for me, and they have not included a working example. This is good enough:

"Simple Property by Dennis": {
"prefix": "propWithBacker",
"body": [
"\t\tprivate ${type:string} _${name};\n",
"\t\tpublic ${type:string} ${name} {",
"\t\t\tget {",
"\t\t\t\treturn _${name};",
"\t\t\t}",
"\t\t\tset { ",
"\t\t\t\t_${name} = ${name};",
"\t\t\t}",
"\t\t}\n"
],
"description": "Create a property with backing field"
}

Hm, actually you don’t need that string of tabs. The snippet placement is sensitive to the position of your cursor, so this will do:

"Simple Property by Dennis": {
"prefix": "propWithBacker",
"body": [
"private ${type:string} _${name};\n",
"public ${type:string} ${name} {",
"\tget {",
"\t\treturn _${name};",
"\t}",
"\tset { ",
"\t\t_${name} = ${name};",
"\t}",
"}\n"
],
"description": "Create a property with backing field"
}


May 2016...
I didn't want to start a new page, but this is a good starting set of Angular and BootStrap er things, to get started (in Emmet and VSC - this goes in the html.json page)

{
 "Basic HTML boilerplate": {
 "prefix": "BasicHtml",
 "body": [
 "<!DOCTYPE html>",
 "<html>",
 "\t<head>",
 "\t\t<title>From the snippets location in Visual Studio Code</title>",
 "\t\t<meta charset=\"utf-8\">",
 "\t\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">",
 "\t\thttps://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.jsx",
 "\t\t<link rel=\"stylesheet\" href=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css\"></link>",
 "\t\thttp://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js",
 "\t\thttp://BasicStuff.js",
 "\t</head>",
 "\t<body>",
 "\t\t<input type=\"button\" value=\"Press me\" id=\"BasicHtmlPressMeId\">",
 "\t\t<input type=\"text\" value=\"Press mex\" id=\"BasicHtmlCapacityId\">",
 "\t</body>",
 "</html>",
 "<!-- https://validator.w3.org/nu/#textarea -->",
 "<!-- Location is [file:///e:/sandbox/javascript/test.html] -->"
 ],
 "description": "A basic snippet of HTML"
 },
 "BSButtons": {
 "prefix": "B01",
 "body": [
 "
“, “\t

A bunch of big Bootstrap buttons

“, ”

“, “<p>”, “\t<button type=\”button\” class=\”btn btn-lg btn-default\”>Default</button>”, “\t<button type=\”button\” class=\”btn btn-lg btn-primary\”>Primary</button>”, “\t<button type=\”button\” class=\”btn btn-lg btn-success\”>Success</button>”, “\t<button type=\”button\” class=\”btn btn-lg btn-info\”>Info</button>”, “\t<button type=\”button\” class=\”btn btn-lg btn-warning\”>Warning</button>”, “\t<button type=\”button\” class=\”btn btn-lg btn-danger\”>Danger</button>”, “</p>” ], “description”: “Initial bootstrap buttons” }, “Ang01”: { “prefix”: “Ang01”, “body”: [ “\thttps://ajax.googleapis.com/ajax/libs/angularjs/1.5.1/angular.js” ], “description”: “Angular CDN” }, “BSScriptTags”: { “prefix”: “BSScript”, “body”: [ “\t\thttps://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.jsx“, “\t\t<link rel=\”stylesheet\” href=\”http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css\”></link>”, “\t\thttp://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js” ], “description”: “The Bootstrap src, css and jquery bits” } }

Visual Studio: back to snippet editors

Having done some research (there’s this thing called Google), I have found just 2 VS snippet editors that are free, and I’ve had a play with both in VS2015. The newness of 2015 may be the reason that I am struggling to get them to do the right thing. Anyway, quick view on both:

Snippet Editor here on codeplex both for the exe and and the code.

And Snippet Designer here and here. This is a VS plug-in, which I can’t get to do anything simple in VS2015.

So me, I went for Snippet Editor. It lives outside VS, and by default prefers its own location outside the VS defaults, but that location does get picked up by the intellisense.

SnippetEditor01

The UI. I don’t know what Synch does, I don’t know what the UnCatalogued is referring to, the Help does not help at all. But it does what I need – if I know my personal snippets are in that location at the bottom, then I only need that for backing up from time to time. And it feels mean criticising the person at all. So Thanks.

SnippetEditor02

Type the shortcut MyCodex to bring up the snippet:

SnippetEditor03

And because it’s VS’s own XML structure, then the substitutions still happen as you would expect.

SnippetEditor04

Adding some more variablenessness…

SnippetEditor05

That seems to work pretty nicely:

SnippetEditor06

Giving this on replacement:

SnippetEditor07

Yeah, sure, I know. It’s not changing.


The next night…

Keen to go back into Snippet Editor. I had saved the shortcut to the taskbar – good thinking. But I open it and then is nothing in the File Explorer to the left, and no visible means of opening a file. Yet then, super-unintuitive, there is a plain bar at the bottom, which when you click on it, opens Windows Explorer. And probably more useful, you will find that your snippets outside of VS are associated with Snippet Editor. So if you double-click on a snippet in Explorer, it will open that snippet in Snippet Editor. And if you change the shortcut for that given snippet, it is immediately recognised in VS.

PowerShell: The basic template in ISE

The basic Ctrl-J template in the PowerShell ISE is a bit noisier than I need. This is all I want:

PSTemplate01

<#
.Synopsis
Drop set of databases
.Example
Drop-Database -DatabasePrefix “TestSet”
#>
function Drop-Database
{
[CmdletBinding(SupportsShouldProcess=$true)]
Param (
[Parameter(Mandatory=$true)]
$DatabasePrefix
)
Begin {
}
Process {
}
End {
}
}

Beyond that, you can use the New-IseSnippet function to make it part of the ISE, and use Ctrl-J to invoke it. Straight from msdn…

$m = @'
Param
(
  [parameter(Mandatory=$true)]
  [String[]]
  $<ParameterName>
)
'@

PS C:\>New-ISESnippet -Text $m -Title Mandatory -Description "Adds a mandatory function parameter." -Author "Kim Akers, Fabrikam Corp." -Force

So applying that principle to our very basic snippet at the top, we get..


$m = @'
<# .Synopsis Drop set of databases .Example Drop-Database -DatabasePrefix "TestSet" #>
function Drop-Database {
[CmdletBinding(SupportsShouldProcess)]
Param (
[Parameter(Mandatory)]
$DatabasePrefix
)
Begin {
}
Process {
}
End {
}
}
'@

New-ISESnippet -Text $m -Title DropDatabases -Description “A snippet to drop databases.” -Author “Dennis Wells, The Things I Do” -Force

Not so fast… So this was OK to execute…

PowerShellSnippetISE01

 

But then…

PowerShellSnippetISE02

Exception calling “Load” with “1” argument(s): “Unable to find or access the file C:\Users\denni\Documents\WindowsPowerShell\Snippets\DropDatabases.snippets.ps1xml”
At C:\Windows\system32\WindowsPowerShell\v1.0\Modules\ISE\ISE.psm1:102 char:9
+ $psise.CurrentPowerShellTab.Snippets.Load($params[“FilePath”] …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : InvalidOperationException

Looking at the file location, the offending file is clearly there…

PowerShellSnippetISE03

, with this content:

PowerShellSnippetISE04

Executing the command line a second time also gives the error.

Hang on…

I recently rebuilt this machine.

If we try this…

New-Item -ItemType File -Path $profile -Force

PowerShellSnippetISE05

And from then on just refer to my old post here

PowerShellSnippetISE07

PowerShellSnippetISE08

PowerShellSnippetISE09

, and as admin..

PowerShellSnippetISE10

Now we shall try again…

PowerShellSnippetISE11

That means I expect to find a snippet with a title of [Mandatory] when I press Ctrl-J in the ISE.

PowerShellSnippetISE12

Hm, so that all works, but it doesn’t seem keen on the carats in the $<parametername>. Fine, don’t care.

I won’t bother with the evidence, but following that little trial, I then ran the DropDatabases snippet through the New-ISESnippet command, and it also appears in the selection list, and can be invoked.

No matter how irritating it is to get these automation-related things working, they SO pay you back for the effort.