Find a specific line of code using Powershell so that I can insert or remove

Topics: General
Apr 1, 2015 at 9:01 PM
I have a few NuGet packages that I've put together, with one of them being a common project referenced by all the others.

This common project inserts a config class into the App_Start folder, and a method on this class is then invoked by WebActivator.

For some of the other packages I wish to add one or two more lines of code to this configuration method - it's a case of making a small modification to this class or adding a whole other class into App_Start, which I think is wasteful - and I achieve this using install.ps1.

Now, because I'm a diligent NuGet package developer, in order to find the best place to add these additional lines of code - as well as removing this code if the package is uninstalled
  • I want to find a specific location within this method on this config class.
To achieve this I've tried using the FindPattern method of the FileCodeModel to find the line of code, but haven't had any luck in getting it to work.

This is what I have so far:
$app_start = $project.ProjectItems.Item("App_Start")
$item = $app_start.ProjectItems.Item("my-config-file.cs")
$namespace = $item.FileCodeModel.CodeElements | ? {$_.Kind -eq 5}
$class = $namespace.Members.Item("My-Config-Class")
$method = $class.Members.Item("My-Method-Name")
$startPoint = $method.GetStartPoint([EnvDTE.vsCMPart]::vsCMPartBody)
$startPoint = $startPoint.CreateEditPoint()
$endPoint = $method.GetEndpoint([EnvDTE.vsCMPart]::vsCMPartBody)
$endPoint = $endpoint.CreateEditPoint()     
$startPoint.FindPattern("known-line-of-code", [EnvDTE.vsCMPart]::vsFindOptionsFromStart, ref $endPoint)
[I know that could be shortened - that's the debug version.]

Specifically, it's the method call on that last line, FindPattern, that I'm having trouble with. The docs list another optional parameter, and judging by Visual Studio's exception message...
Exception calling "FindPattern" with "3" argument(s): "Type mismatch.
...I guess I'm supposed to supply this parameter. But what do I supply it with?

And even if I could find the line of code, how do I then delete it or insert code after it?

Or is FindPattern the wrong way to proceed? Is there another way to remove a known line of code?