Friday, June 1, 2007

Truncate the last n bytes of a file

Use FileStream.SetLength():

Dim strFile As String = "C:\Path\To\File.txt"
Dim fi As New FileInfo(strFile)
Dim fs As New FileStream(strFile, FileMode.Open, FileAccess.Write)
fs.SetLength(fi.Length - n)
fs.Flush()
fs.Close()

Thursday, May 24, 2007

Opening a Windows Explorer window in VB.NET

Use Process.Start:

Dim ps As New ProcessStartInfo("explorer")
ps.Arguments = "C:\Directory\to\open"
Process.Start(ps)

Friday, May 18, 2007

.NET Regular Expression Escape Characters

\w - matches any word character
\W - matches any non-word character
\s - matches any whitespace character
\S - matches any non-whitespace character
\n - newline
\f - formfeed
\r - carriage return
\t - tab
\v - vertical tab
\0x0020 - space
\d - digit
^ - beginning of string
$ - end of string

Tuesday, February 13, 2007

Filling in gaps in incrementing INT column in SQL Server

Suppose you have a unique integer column i in a table T. i may contain gaps. i contains m rows.

Suppose you wish to insert n values into i starting at some value x0 and incrementing. Let x equal the first integer greater than or equal to x0 not found in i.

In general, this can be solved by performing the following:

SELECT TOP n * 2 IDENTITY(INT, x, 1) AS j
INTO #temp
FROM T T1
CROSS JOIN T T2
GO

INSERT INTO T (i)
SELECT TOP n j
FROM #temp
LEFT OUTER JOIN T
ON T.i = #temp.j
WHERE T.i IS NULL
GO

There should now be m + n rows in T.

Thursday, January 25, 2007

Getting System Icons into a PictureBox control

A simple solution for getting system icons into a PictureBox control at runtime is to set the PictureBox's Image property to SystemIcons.xxxxxx.ToBitmap().

Monday, December 11, 2006

sp_msforeachdb

To iterate a command over all databases on a server, the undocumented sp_msforeachdb stored procedure fits the bill nicely. For example, I was given the task to set all databases on a particular server to a bulk-logged recovery model; this was easily accomplished with a single command:

master..sp_msforeachdb 'exec sp_dboption ''?'', ''select into/bulkcopy'', ''on'''

Note that this procedure executes dynamic SQL, replacing the ? with the name of the database as it iterates.

Monday, December 4, 2006

ADODB.Recordset to ADO.NET DataTable

It turns out that an OleDbDataAdapter can be used to fill an ADO.NET DataTable object from an ADODB.Recordset object:

Imports System.Data.OleDb

...

Public Function RecordSetToDataTable(ByVal objRS As ADODB.RecordSet) As DataTable
    Dim objDA As New OleDbDataAdapter()
    Dim objDT As New DataTable()
    objDA.Fill(objDT, objRS)
    Return objDT
End Function