navigation
 Friday, March 17, 2006

I'm still playing around with that MakeRegion macro that Philip first posted. Today I added a regular expression to parse the first line of code and extract only the member name instead of the entire line.

For instructions on how to install, see The Blog That Started It All.

Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Imports System.Text.RegularExpressions

Public Module Regions

  Sub MakeRegion()
    Regions.MakeRegion()
  End Sub

  Public Class Regions
    ' MakeRegion inserts #region and #endregion tags
    ' around selected text in the VS editor.
    Shared Sub MakeRegion()
      Dim rName As String = ""
      Dim pad As String = ""
      Dim junk As String
      Dim count, i As Integer
      Dim startpoint, endpoint, tmppoint As EditPoint

      With DTE.ActiveDocument.Selection
        startpoint = .TopPoint.CreateEditPoint()
        endpoint = .BottomPoint.CreateEditPoint
      End With

      If startpoint.EqualTo(endpoint) Then
        Exit Sub
      End If

      'ELR: ADDED THIS, to move the startpoint to the start of the line()
      'so that the Pad function works correctly
      If Not startpoint.AtStartOfLine Then
        startpoint.StartOfLine()
      End If

      Dim DefaultResponse = GetDesc(DTE.ActiveDocument.Selection.TopPoint.CreateEditPoint())
      Dim re As Regex = New Regex("\s(\w+)\s*(?:\(|\:|$)")
      DefaultResponse = re.Match(DefaultResponse).Groups(1).Value

      'IV 2004-12-13: rName = InputBox("Region Name:")
      rName = InputBox("Type the name you want to give to the region, which will appear in the Visual Studio Code Editor.", "Make Region", _
      DefaultResponse)

      rName = rName.Trim()

      If rName.Length = 0 Then
        Exit Sub
      End If

      DTE.UndoContext.Open("Insert A Region")
      Try
        junk = startpoint.GetText(startpoint.LineLength)

        pad = String.Empty
        For count = 0 To junk.Length - 1
          If junk.Substring(count, 1).Equals(" ") _
          Or junk.Substring(count, 1).Equals(vbTab) Then
            pad += junk.Substring(count, 1)
          Else
            Exit For
          End If
        Next

        'ELR: ADDED Test for Languages
        If DTE.ActiveDocument.Language = "CSharp" Then
          ' C Sharp Code
          startpoint.Insert(String.Format("{0}#region {1}{2}", _
           pad, rName, vbCrLf))
          If endpoint.LineLength = 0 Then
            endpoint.Insert(String.Format("{0}#endregion {1}{2}", _
             pad, rName, vbCrLf))
          Else
            endpoint.Insert(String.Format("{0}#endregion {1}", _
             vbCrLf & pad, rName))
          End If
        Else
          ' VB Code
          startpoint.Insert(String.Format("{0}#Region {1}{2}", _
           pad, rName, vbCrLf))
          If endpoint.LineLength = 0 Then
            endpoint.Insert(String.Format("{0}#End Region '{1}{2}", _
             pad, rName, vbCrLf))
          Else
            endpoint.Insert(String.Format("{0}#End Region '{1}{2}", _
             vbCrLf & pad, rName, vbCrLf))
          End If
        End If
      Finally
        DTE.UndoContext.Close()
      End Try
    End Sub

    ' IV: Get the description from the 1st line of code in the region
    ' i.e. ignore c# comment tags (///) or take 1st line of the comments (//)
    ' Requires adjustments for VB and other langs
    Private Shared Function GetDesc(ByVal startpoint As EditPoint) As String
      Dim line As String = ""
      Dim tmppoint As EditPoint

      line = startpoint.GetText(startpoint.LineLength)
      If (line.Length > 0) Then
        line = line.TrimStart(" ", vbTab)
        If DTE.ActiveDocument.Language = "CSharp" Then
          If (line.StartsWith("///")) Or (line.StartsWith("[")) Then
            tmppoint = startpoint
            tmppoint.LineDown()
            line = GetDesc(tmppoint)
          ElseIf (line.StartsWith("//")) Then
            line = line.TrimStart("//", " ")
          End If
          line = line.Replace("{", String.Empty)
        End If
        line = line.TrimEnd(" ", vbTab)
      End If
      Return line
    End Function
  End Class

End Module

posted on March 17, 2006  #    by Adam Anderson  Comments [0] Trackback
 Thursday, March 16, 2006

Here's a little code snippet that will search a collection of Controls for the first control of a specified type.

private object FindControlByType( Control root, Type t )
{
  if ( root != null && root.GetType().Equals( t ) )
    return root;
  foreach( Control c in root.Controls )
  {
    object node = FindControlByType( c, t );
    if ( node != null && node.GetType().Equals( t ) )
      return node;
  }
  return null;
}

Example: the following example returns the first instance of an HtmlForm in a Page's Control collection:

HtmlForm form = (HtmlForm) FindControlByType( Page, typeof( HtmlForm ) );
posted on March 16, 2006  #    by Adam Anderson  Comments [0] Trackback

Here's a mysterious bit of code that doesn't look like it ought to work, but yet it does

select top 1 *
from table
order by newid()

posted on March 16, 2006  #    by Adam Anderson  Comments [1] Trackback
 Tuesday, March 14, 2006

Sometimes you need to comment out blocks of code, but you don't necessarily want to comment out each entire line. As I was performing this very chore today, I thought to myself, "Hey, wouldn't it be nice if there was a keyboard shortcut I could use to comment a selected block of text using comment delimiters?" Then I thought to myself, "I already know how to create macros thanks to Philip's great blogs on macros. Why don't I try writing my own?" So I did. Source code within.

See Philip's great blogs for instructions on how to install macros.

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics

Public Module SolutionExplorer

  Sub CollapseNodes()
    ' Get the the Solution Explorer tree
    Dim UIHSolutionExplorer As UIHierarchy
    UIHSolutionExplorer = DTE.Windows.Item( _
     Constants.vsext_wk_SProjectWindow).Object()

    ' Check if there is any open solution
    If (UIHSolutionExplorer.UIHierarchyItems.Count = 0) Then
      Return
    End If

    ' Get the top node (the name of the solution)
    Dim UIHSolutionRootNode As UIHierarchyItem
    UIHSolutionRootNode = UIHSolutionExplorer.UIHierarchyItems.Item(1)

    ' Collapse each project node
    Dim UIHItem As UIHierarchyItem
    For Each UIHItem In UIHSolutionRootNode.UIHierarchyItems
      UIHItem.UIHierarchyItems.Expanded = False
    Next

    ' Select the solution node, or else when you click
    ' on the solution windows scrollbar, it will synchronize the open document
    ' with the tree and pop out the corresponding node which is probably not
    ' what you want.
    UIHSolutionRootNode.Select(vsUISelectionType.vsUISelectionTypeSelect)
  End Sub

  Sub ExpandNodes()
    ' Get the the Solution Explorer tree
    Dim UIHSolutionExplorer As UIHierarchy
    UIHSolutionExplorer = DTE.Windows.Item( _
     Constants.vsext_wk_SProjectWindow).Object()

    ' Check if there is any open solution
    If (UIHSolutionExplorer.UIHierarchyItems.Count = 0) Then
      Return
    End If

    ' Get the top node (the name of the solution)
    Dim UIHSolutionRootNode As UIHierarchyItem
    UIHSolutionRootNode = UIHSolutionExplorer.UIHierarchyItems.Item(1)

    ' Collapse each project node
    Dim UIHItem As UIHierarchyItem
    For Each UIHItem In UIHSolutionRootNode.UIHierarchyItems
      UIHItem.UIHierarchyItems.Expanded = True
    Next

    ' Select the solution node, or else when you click
    ' on the solution windows scrollbar, it will synchronize the open document
    ' with the tree and pop out the corresponding node which is probably not
    ' what you want.
    UIHSolutionRootNode.Select(vsUISelectionType.vsUISelectionTypeSelect)
  End Sub

End Module

posted on March 14, 2006  #    by Adam Anderson  Comments [0] Trackback
 Thursday, February 23, 2006

My colleague John recently blogged about the unexpected results of using the T-SQL IN operator on a set that contains NULL. Here is another solution to the problem.There are three main ways to test for existence in another table, listed here in order of increasing performance

  1. LEFT JOIN and look for NULLs in the right table
  2. Use the IN operator
  3. Use the EXISTS operator

In general, the EXISTS operator will generate the most efficient query plan, and it also isn't subject to the very NULL pitfall that plagues the IN operator. The query that John posted:

SELECT COUNT(*)
FROM TableTarget
WHERE PrimaryKeyField NOT IN (
  SELECT ForeignKeyField
  FROM TableSource
  WHERE ForeignKeyField IS NOT NULL
)

Could be writtten like this:

SELECT COUNT(*)
FROM TableTarget t
WHERE NOT EXISTS (
  SELECT *
  FROM TableSource
  WHERE ForeignKeyField = t.PrimaryKeyField
)

posted on February 23, 2006  #    by Adam Anderson  Comments [0] Trackback
 Wednesday, February 22, 2006

Danc of Lost Garden has written many interesting and thought-provoking articles, mostly about game design. Today's article, however, is wider in scope, addressing the evolution of product design, and is well worth the read.

posted on February 22, 2006  #    by Adam Anderson  Comments [0] Trackback
 Saturday, February 18, 2006

Krugle is a search engine for source code that is supposed to make life easier for us developers. You can sign up for the Beta on their website and try it out sometime next month.  http://www.krugle.com/

posted on February 18, 2006  #    by Mike Dugan  Comments [0] Trackback
 Monday, February 06, 2006

Is Courier New just not doing it for you anymore? This page summarizes and rates different fixed-width fonts based on their suitability for use in a programming environment. The reviewer evaluates several factors including how easily the characters 'l', '1', and 'i' are distinguised, as well as the characters '0', 'o', and 'O'. After browsing several of the handy font previews, simply follow the associated link to download your new favorite programming font. The top-rated font, Bitstream Sans Vera Mono, looks great without ClearType and awful with it, so if you have font smoothing enabled, I recommend you look further down the list for something that plays better with ClearType

posted on February 6, 2006  #    by Adam Anderson  Comments [0] Trackback
 Friday, January 27, 2006

Being able to compare the results of two different SQL queries and verify that they match 100% is a useful ability for any database application developer. I've encountered two main reasons for wanting to compare query results in the course of development:

  1. After importing data from an older system, verifying that equivalent reports in the old system and the new one agree
  2. When refactoring a complex query, to verify that the changes made haven't altered the output

In both cases, I find it convenient to run data comparisons of queries run in SQL Server Query Analyzer by using MS Excel. The technique is simple, but the payoff is huge: 100% confidence that every row and every column matches. Here are the steps I use:

  1. Create a new 3-page workbook and rename the tabs "Old", "New", and "Compare" 
  2. Hand-enter column names in the top row of each worksheet. I like to make them bold and underlined so Excel can tell that they're headers. 
     
  3. Run the "old" query in Query Analyzer. Once the results come back, click in the result pane and select all using Ctrl+A or Edit | Select All
  4. In the "Old" worksheet, select the leftmost cell in the row under the header and paste the results.
  5. Repeat the same steps for the "New" query and worksheet.
  6. If the queries don't explicitly set their own sort order, I recommend sorting both the "Old" and "New" data in a way that should guarantee that they are ordered the same on the two worksheets.
  7. In the "Compare" worksheet, enter the following formula in the leftmost cell under the header row: =Old!A2=New!A2. This formula will return TRUE if the cells match, and FALSE if they don't. 
  8. To make mismatches easier to spot, I like to apply some conditional formatting as well.

    1. Select the cell and then select Format | Conditional Formatting...
    2. Set up the condition so that it reads "Cell Value Is" "equal to" "FALSE"
    3. Click the Format... button. On the Patterns tab, select a nice bright color that will stand out, like red. Click OK.
    4. Click OK on the Conditional Formatting dialog
  9. Select the span from this initial cell to the rightmost column in the result set and press Ctrl+R or Edit | Fill | Right.
  10. Check the "Old" and "New" worksheets and note the number of the last row containing query results.
  11. In the "Compare" worksheet, select all the cells that contain data in the same row and column on the other two sheets and press Ctrl+D or Edit | Fill | Down.
  12. Differences in data will result in a value of FALSE (optionally highlighted if you used conditional formatting). The values can be scanned for visually, or you can use the Find dialog to search for them. When using the Find dialog, make sure to click the Options button and change "Look in" from "Formulas" to "Values" 
  13. Once differences are found, the old and new data can be examined to determine the cause for the difference.
posted on January 27, 2006  #    by Adam Anderson  Comments [0] Trackback

The MSDN Library says this about the DataGrid.Items property:

"Only items bound to the data source are contained in the Items collection. The header, footer, and separator are not included in the collection."

So how do we get to these other items? Most people handle the ItemCommandEvent for the grid, but there is a way to access them directly.

If these items are not in the DataGrid.Items collection, then where are they? To find out, turn on tracing for your ASP.NET webpage. You will see that the grid is rendered something like this:

DataGrid
   DataGridTable
      DataGridItem
         TableCell
         TableCell
      DataGridItem
         TableCell
         LiteralControl
         Label
      DataGridItem
      ...

What we are seeing is that the first object in the DataGrid's Control hierarchy is a DataGridTable. That DataGridTable contains ALL of the DataGridItems, including the header and footer. To get these DataGridItems we just need to grab the first or last control out of the DataGridTable's control collection.

So to get a DataGrid's footer, this code will do this trick:

//First get the DataGridTable (the first control in DataGrid's control collection.)
//Then grab the last control in the DataTable's Collection
DataGridItem footer = 
    DataGrid1.Controls[0].Controls[DataGrid1.Controls[0].Controls.Count -1] as DataGridItem;
posted on January 27, 2006  #    by Mike Dugan  Comments [0] Trackback