Saturday, December 7, 2013

Off-topic: Wiping your hard drive

I want to document how I did this in case I need it in the future. This is a good way to wipe an entire drive quickly with any Linux LiveCD or USB stick. It only uses a program called dd.

Most computers, the primary hard drive is /dev/hda. So, to wipe it, issue this command:

dd if=/dev/zero of=/dev/sda bs=32M

Note that 32MB is a good buffer size for most modern drives. I'm getting 100 MB/s speed wiping using this. For a 500GB drive, that's taking me around 1 hour to wipe.

You can optionally check for a status in a separate terminal tab like so:
while true; do kill -USR1 1234; sleep 5; done

Replace "1234" with the PID of dd (which you can get with a "ps -A | grep dd"). When you flip back to the tab where dd is running, you will get a status update every five seconds. It tells you how much data has been copied, as well as your bytes / sec copied.

Enjoy!

Wednesday, July 31, 2013

Off Topic: Supporting Javascript you didn't write

Hi everyone,

Today's topic doesn't deal with .NET / CLR topics at all. This blog tends to focus on that. But since most .NET developers I know tend to use JS/HTML/CSS with .NET (or ASP.NET), this post should be somewhat beneficial to the "usual" reader of this blog.

I am a support engineer. That means I often get asked to fix code I didn't write. If it's .NET code, I usually turn to debugger breakpoints and/or tracepoints (good info about those here if you are not familiar) or occasionally use a .NET profiler. The first goal behind these tools is often to answer the question "where am I in the code base?" By knowing what code at the function or line level is involved, you can narrow down what things might be broken as you troubleshoot.

And honestly, that is the name of the game with all debugging / troubleshooting, regardless of language or environment. We have a product with a fairly large javascript code base that is difficult for me to keep up with, because I only find myself troubleshooting problems related to it once every 3-6 months. As a result, I often have a large "learning curve" at the beginning of my support issue, as I find out what has changed and what has stayed the same in the code base. Tools like Firebug for Firefox or Chrome's JS debugger are certainly helpful, but sometimes it takes a lot of effort just to figure out what parts of the code base are involved when you click a button, or go to page xyz. You can always view the HTML and see what JS is running, but if the product is designed with a lot of architectural "fluff", you have a hard time deciphering what exactly is going to happen when you click the button. As an example, maybe the button runs a JS function named processAction() that takes a GUID: processCommand('12345-123-123-1234...');

Well that's just not helpful. :) How do I know what that GUID is related to? In our product, it changes every time you hit the page! Ugh.

Enter, JSCoverage. I recently found a great Chrome plugin that can be used to identify functions (or even lines of code) that execute whenever you navigate somehow in your product. This manual page gives you a rundown of how it works. It essentially boils down to these high level steps:

1) Instrument one or more .js source files. These are output in a folder of your choosing.
2) Make sure your output folder is hosted by a web server (such as IIS, aka mapped to a virtual directory, or in a subdir of a virtual directcory).
3) Navigate to the generated jscoverage.html file.
4) Use the Browser tab to launch your app in a separate window or tab.
5) The jscoverage.html tab lets you view live information about coverage as you perform actions in the app launched in step 4.

The architecture is fairly simple. There is a global object named _$jscoverage that contains counters for various JS source code files and different blocks within those files.

_$jscoverage['my-source-file.js'][123]

All of the counters start at 0 and go up from there. The great thing about this architecture is that you can exploit it in a way that the original author may or may not have intended! The _$jscoverage object is only initialized once. Subsequent loads of the page or JS actions/functions that execute just accumulate more hit counts on the counters. They don't clear out. QA people who are interested in *total* code coverage probably like this, but a support developer may be more interested in precise coverage of one or two behaviors instead of all behaviors performed in the web browsing session. So, we can use Chrome's Console to execute some ad-hoc javascript that clears the counters, like so:

for(var propName in _$jscoverage['my-source-file.js']) {
_$jscoverage['my-source-file.js'][propName] = 0;
}

Using this technique, we can clear the counters immediately prior to performing our action of interest. Then, once the action completes, switch back to the jscoverage pane to view coverage data for just that action. You may need to navigate off and back onto the Summary tab to see the results update.

For me, this technique greatly simplifies the support process. Now after reproducing my issue, I know that the problem lies within 10 functions instead of 1000 potential functions! That's a money maker, folks. Now, I know where to place breakpoints via Chrome's JS debugger to get the most mileage out of my support discovery process! Some days I just love my job. :)

Many thanks to the developers of JSCoverage.

Thursday, July 18, 2013

System.Xml ImportNode and the .NET Heap(s)

If you work with XML in .NET a lot, you have probably bumped into a scenario a few times in your career where you need to move or copy some XML fragment out of one document and into another. The typical coding sequence for that might look something like this:

XmlDocument source = new XmlDocument();
source.LoadXml("");

XmlDocument dest = new XmlDocument();
dest.LoadXml("");

//move from source to dest
XmlNode n = source.SelectSingleNode("/source/myxml");
XmlNode nImported = dest.ImportNode(n, true);
XmlNode nAppended = dest.DocumentElement.AppendChild(nImported);

I have often wondered (but, until today, been too lazy to investigate) why ImportNode() and AppendChild() return XmlNode objects, and what one is supposed to do with them? Are they the same? Clones of the same? Etc.

Well, IronPython happens to have this nice feature where it shows you the memory address of the .NET object you reference in an expression via the ipy console.

Excerpt from an IronPython Console session

Wednesday, August 1, 2012

RedGate activation blues

So, my company makes use of the RedGate SQL Compare SDK tools. And let me just say, if you haven't bought these yet...totally worth doing. If you've ever wished for SQL functionality related to diff, merge, etc on your schema structures or your data itself, RedGate can do it. Period. I drink their kool-aid.

But this week, I hit a snag as I upgraded to a new developer laptop. It came time to re-activate my RedGate DLLs so that I could use them in development projects in Visual Studio. Typically, you simply compile the project, and a little dialog box asking you to activate your trial install of RedGate pops up while Visual Studio builds. Our projects wouldn't popup the dialog box. Instead, we received a build error in the Error List window:

Error      2             Exception occurred creating type 'RedGate.SQLDataCompare.Engine.ComparisonSession, RedGate.SQLDataCompare.Engine, Version=10.0.1.69, Culture=neutral, PublicKeyToken=7f465a1c156d4d57' System.IO.FileNotFoundException: Could not load file or assembly 'file:///C:\Src\...\Bin\RedGate.Licensing.Client.UI.resources.dll' or one of its dependencies. The system cannot find the file specified.               C:\Src\...\licenses.licx     2


("Real" paths omitted to protect what I work on)


So, I searched for this satellite assembly on my entire hard drive. It was nowhere to be found! Now what do I do?


I had never used RedGate support before, so I decided to give it a try. I e-mailed licensing@red-gate.com, and explained my predicament. Within 24 hours, I received a response from their internal support team.


"Thanks for contacting Red Gate. The issue you've run into is that the Windows Form that asks for a serial number was written against .NET v2 and therefore needs to be invoked using a .NET v2 resource reader. There is no satellite DLL that is missing.
To make a long story short, create a new VS project and ensure the target Framework version is 2. Then add in a sample application and build it. The serial number dialog should pop up and ask for your serial number. Once you have activated successfully, you can then go back and compile your .NET 4 projects, since the licence has been created and there is no more need to ask for the serial number again."


Sure enough, my code was based on .NET 4 and therefore was not allowing RedGate's licensing mechanism to work properly. As suggested, I used a .NET v2 project to activate the copy. Another coworker pointed out that their installer places some samples at this path:


C:\Program Files (x86)\Red Gate\SQL Comparison SDK 10\Samples\Automating SQL Compare


So, I opened one of those, built, was prompted for my license, activated, and the sample built successfully.  I then opened my original project (.NET v4), and compiled it successfully! Yes!


So, I was unable to find much online about this issue. I wanted to blog so that others might experience less pain. This is for RedGate v 10.x, and possibly other versions.

Wednesday, July 13, 2011

ScintillaNET starter kit



I have searched long and hard across the Internet for a simple "hello world" style example of using ScintillaNET's control. This thing has it all. You name the language, and it will give you a textbox that can syntax highlight for that language, plus dozens of other features like code folding and so forth.
But how to use it? For those of us without much "unmanaged code" experience, the Scintilla web site's documentation can be very initimidating. ScintillaNET's documentation (at least at this point in time) is fairly thin. It simply says "for the details, look at Scintilla's documentation". Today I discovered the reason for that--it's actually surprisingly easy to use the ScintillaNET control! With a very flexible licensing agreement, it's a wonder this thing hasn't gone mainstream in the .NET community. Perhaps with this simple example, I can get that started.

I used Visual Studio 2010 to do this, but any version for .NET 2.0 or higher should suffice.

Step 1): Get the source code, build ScintillaNET, and reference ScintillaNET.dll from a Windows Forms project. (Note: WPF may or may not work with the WindowsFormHost XAML tag allowing Windows Forms controls to be loaded into the XAML structure. I haven't tried that.)

Step 2): Go to your visual designer, and look in the toolbox. There is a control named "Scintilla". Drag that to your form.


Step 3): You'll need to tell it what language to use for syntax highlighting. Scintilla supports a TON of languages: http://scintillanet.codeplex.com/wikipage?title=HowToSyntax&referringTitle=Documentation
In my case, I was making an XML editing control, so I chose to set the language to "xml" in my form's onload event (note, in this code snippet, scnMain is the name of the Scintilla control I dragged onto the form):
private void ctlScintillaNETXml_Load(object sender, EventArgs e)
{
scnMain.ConfigurationManager.Language = "xml";
}


Step 4): Set or get scnMain.Text as appropriate to get a string of code (or in my case, XML markup). That's it! Fire it up and watch the awesomeness that is Scintilla. How easy was that? Enjoy.

Friday, December 3, 2010

Powershell Functions - Evil Calling Convention Problem

In powershell, one might think that calling a function would look like this:

FindReplaceMany_Directory($SubDir, $fileType, $recursive, $findArray, $replaceArray)

given a function like this:
#Find replace files of a certain file type in a given directory.
#$recursive = true to parse sub-dirs as well
#$fileType = ""*.*"", ""*.txt"", etc.
function FindReplaceMany_Directory($dir, $fileType, $recursive, $findArray, $replaceArray)
{
... (omitted) ...
}

This is not the correct syntax. But surprisingly, it still works and ONLY the first parameter gets a proper value. Everything else gets a null.

To properly call this function, do this:
FindReplaceMany_Directory $SubDir $fileType $recursive $findArray $replaceArray

Wednesday, December 1, 2010

Mass Rename files

Here is a script I wrote to rename a bunch of pictures I had on my computer. It lets me put a prefix on the front, so that I can tell what it is by the title in the taskbar at the bottom of the computer when the picture previewer is minimized. This script could easily be tweaked for many other mass renaming jobs without much programming knowledge. Enjoy!

=========(Begin File...just name it something.ps1)========================

Write-Host "Tell me a prefix to put on the front of all *.jpg files in this folder:"
$Prefix = (Get-Host).UI.ReadLine()

if($Prefix.Length -gt 0)
{
$Files = Get-ChildItem *.jpg

foreach($File in $Files)
{
$NewName = $Prefix + $File.Name

Write-Host "Renaming $File to $NewName"

Rename-Item $File $NewName
}
}
else
{
Write-Host "No prefix. Doing nothing."
}

Write-Host "Press any key..."
(Get-Host).UI.ReadLine()

=========(End File)========================