How to calculate age in C#

Seems like a simple thing, but the fact that you need to subtract a year if the person hasn’t had their birthday yet in the current year made it more involved. There were a lot of different ways to do it online, some of them more clunky than others. I cobbled this together from the various posts I found (assume a Person object with a DOB field).

public int Age {

  • get {
    • var now = DateTime.Now;
    • var age = now.Year - this.DOB.Year;
    • return (this.DOB.DayOfYear <= now.DayOfYear) ? age : age - 1;
  • }

}

Make disabled DataGridView appear grayed out

Usually, when you set a control’s Enabled property to False, the control will appear grayed out in the form.  However, a DataGridView control whose Enabled property is False looks the same as one whose Enabled property is True.  Once you try to click in to the DataGridView to edit or add something, you’ll find that it is not enabled, but it doesn’t look any different – which can be confusing to users, especially if it is on a form with other disabled controls that are grayed out.

Here is a little utility function that will manually gray out the headers and cells of a DataGridView.  It doesn’t gray out check box columns, but then the checkboxes aren’t grayed out in a disabled CheckedListBox, either, so I figure this is close enough:

    Private Sub DisableGrid(ByVal grid As DataGridView)
        With grid
            .Enabled = False
            .ForeColor = Color.Gray
            For Each col As DataGridViewColumn In .Columns
                col.HeaderCell.Style.ForeColor = Color.Gray
            Next
        End With
    End Sub

CellValueChanged event doesn’t fire when in DataGridView

So here’s the scenario – you’ve got some kind of code that you want to run whenever the value of a cell changes in a DataGridView.  You write some code in the DataGridView’s CellValueChanged event, but you notice that it doesn’t fire if you are editing a cell and then you close the form without first tabbing/clicking out of the DataGridView (I noticed this when working on my IsDirty class, described in my last post).

There is a very quick and dirty solution to this problem – in the FormClosing event, set focus on another form element, like a textbox (for example, txtFirstName.Focus()).  This will cause the focus to leave the DataGridView, which will cause the CellValueChanged event to fire, which will cause your CellValueChanged code to run.

IsDirty Change Tracker for WinForms

Here is a ChangeTracker class I developed for use in WinForms scenarios – it is adapted from an article I found at The Code Project site.  In testing it, I also came across a problem and work-around for DataGridView controls – see the next blog post for details.

To use this class, download the class file and add it to your project.  In the form in which you want to track changes, add a form level variable:

Private changeTracker As TKS.ChangeTracker

In the form’s Load event, put the following code:

'set up change tracking
Me.changeTracker = New TKS.ChangeTracker(Me)

In the form’s FormClosing event, put the following code (you can see a clue as to the next blog entry in the first line):

'set focus on a textbox control, to make sure that datagrid CellChangeValue event fires if necessary
Me.txtFirstName.Focus()

'check if form is dirty
If Me.changeTracker.IsDirty Then
Dim result = MessageBox.Show("Would you like to save changes before exiting?", "Save Changes", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
Select Case result
Case Windows.Forms.DialogResult.Yes
Me.Save()
Me.changeTracker.SetAsClean()
Case Windows.Forms.DialogResult.No
'no action needed, unless form is hidden instead of closed. Then, you might want to re-set the change tracker
Me.changeTracker.SetAsClean()
Case Windows.Forms.DialogResult.Cancel
e.Cancel = True
End Select
End If

And here is the code for the class itself.  It is written to check TextBoxes, CheckBoxes, ComboBoxes, CheckedListBoxes and DataGridViews, but you can adapt it to check whatever you want. (You can also download the code.):

Namespace TKS
Public Class ChangeTracker

#Region "Data Members"
Private _frmTracked As Form
Private _ctlData As Generic.Dictionary(Of String, TKS.ChangeTracker.ControlInfo)
#End Region

#Region "Constructor"
Public Sub New(ByVal frm As Form)
'initialize data members
_frmTracked = frm
_ctlData = New Generic.Dictionary(Of String, TKS.ChangeTracker.ControlInfo)

'get initial control values, and hook up tracking events
Me.SetUpControlTracking(_frmTracked.Controls, isEventsAssigned:=False)
End Sub
#End Region

#Region "Properties"
Public ReadOnly Property IsDirty As Boolean
Get
'loop through the change-tracker object for each control.  If any is dirty, exit loop and return true
For Each kvPair As KeyValuePair(Of String, ControlInfo) In _ctlData
If kvPair.Value.IsDirty Then Return True
Next
'if we've gotten here, then nothing is dirty - return false
Return False
End Get
End Property
#End Region

#Region "Methods"
Public Sub SetAsClean()
'clear previous data
_ctlData.Clear()
'get new control values - don't need to hook up events as they are already hooked up
Me.SetUpControlTracking(_frmTracked.Controls, isEventsAssigned:=True)
End Sub

Private Sub SetUpControlTracking(ByVal col As Control.ControlCollection, ByVal isEventsAssigned As Boolean)
'loop control collection, add control value to info collection, add event handler to designated controls if it hasn't been done already
For Each ctl As Control In col
If TypeOf ctl Is TextBox Then
Dim txtbox = CType(ctl, TextBox)
_ctlData.Add(txtbox.Name, New ControlInfo(txtbox.Text, False))
If Not isEventsAssigned Then AddHandler txtbox.TextChanged, AddressOf TextBox_TextChanged

ElseIf TypeOf ctl Is CheckBox Then
Dim chkbox = CType(ctl, CheckBox)
_ctlData.Add(chkbox.Name, New ControlInfo(chkbox.Checked.ToString, False))
If Not isEventsAssigned Then AddHandler chkbox.CheckedChanged, AddressOf CheckBox_CheckedChanged

ElseIf TypeOf ctl Is ComboBox Then
Dim cbobox = CType(ctl, ComboBox)
_ctlData.Add(cbobox.Name, New ControlInfo(cbobox.SelectedValue.ToString, False))
If Not isEventsAssigned Then AddHandler cbobox.SelectedIndexChanged, AddressOf ComboBox_SelectedIndexChanged

ElseIf TypeOf ctl Is CheckedListBox Then
Dim lstbox = CType(ctl, CheckedListBox)
_ctlData.Add(lstbox.Name, New ControlInfo(Me.GetAllChecked(lstbox), False))
If Not isEventsAssigned Then AddHandler lstbox.SelectedIndexChanged, AddressOf CheckedListBox_SelectedIndexChanged

ElseIf TypeOf ctl Is DataGridView Then
Dim dg = CType(ctl, DataGridView)
Dim key As String
'will need to loop datagrid and get each cell value.  Concatenate grid name, row index, cell index to create unique key for each cell.  Skip rows with no values.
For Each row As DataGridViewRow In dg.Rows
If Not row.IsNewRow Then
For Each cell As DataGridViewCell In row.Cells
key = dg.Name & row.Index.ToString & cell.ColumnIndex.ToString
_ctlData.Add(key, New ControlInfo(cell.Value.ToString, False))
Next
End If
Next
If Not isEventsAssigned Then AddHandler dg.CellValueChanged, AddressOf DataGridView_CellValueChanged
End If

'recursively get values from, add event handlers to, child controls
If ctl.HasChildren Then
SetUpControlTracking(ctl.Controls, isEventsAssigned)
End If
Next
End Sub
#End Region

#Region "Event Handlers"
'Event handlers will:
'  - get control's change-tracker object from collection
'  - get control's new value and pass to 'CheckIfDirty' method of change-tracker object
'  - if new value is different from saved value, 'CheckIfDirty' will mark control as dirty
'  - if new value restores saved value, 'CheckIfDirty' will change control back to clean
Private Sub TextBox_TextChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim txtbox = CType(sender, TextBox)
If _ctlData.ContainsKey(txtbox.Name) Then
_ctlData(txtbox.Name).CheckIfDirty(txtbox.Text)
End If
End Sub

Private Sub CheckBox_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim chkbox = CType(sender, CheckBox)
If _ctlData.ContainsKey(chkbox.Name) Then
_ctlData(chkbox.Name).CheckIfDirty(chkbox.Checked.ToString)
End If
End Sub

Private Sub ComboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim cbobox = CType(sender, ComboBox)
If _ctlData.ContainsKey(cbobox.Name) Then
_ctlData(cbobox.Name).CheckIfDirty(cbobox.SelectedValue.ToString)
End If
End Sub

Private Sub CheckedListBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim lstbox = CType(sender, CheckedListBox)

If _ctlData.ContainsKey(lstbox.Name) Then
_ctlData(lstbox.Name).CheckIfDirty(Me.GetAllChecked(lstbox))
End If
End Sub

Private Sub DataGridView_CellValueChanged(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs)
Dim dg = CType(sender, DataGridView)
Dim row = dg.Rows(e.RowIndex)
Dim cell = row.Cells(e.ColumnIndex)
Dim key As String = dg.Name & e.RowIndex.ToString & e.ColumnIndex.ToString

'if key exists, check against initial value
If _ctlData.ContainsKey(key) Then
_ctlData(key).CheckIfDirty(cell.Value.ToString)
Else
'if key doesn't exist, this is a new row - add cell, and set as dirty  (set value to something unlikely so control will always evaluate as dirty)
_ctlData.Add(key, New ControlInfo("-TKS", True))
End If
End Sub
#End Region

#Region "Get All Selected Values in List"
Private Function GetAllChecked(ByVal lstBox As CheckedListBox) As String
'loop through 'CheckedIndices' collection and concatenate
Dim sb As New System.Text.StringBuilder
For Each i As Integer In lstBox.CheckedIndices
sb.Append(i.ToString)
Next
Return sb.ToString
End Function
#End Region

#Region "ControlInfo Class"
'change-tracker object - stores control's initial value and evaluates new values
Private Class ControlInfo
Sub New(ByVal v As String, ByVal dirty As Boolean)
Value = v
IsDirty = dirty
End Sub

Public Property Value As String
Public Property IsDirty As Boolean

Public Sub CheckIfDirty(ByVal newValue As String)
If Me.Value.Equals(newValue) Then
Me.IsDirty = False
Else
Me.IsDirty = True
End If
End Sub
End Class
#End Region

End Class
End Namespace

Remove items from Visual Studio Recent Projects list

Here are a couple handy links describing how to remove items from the Recent Projects list on the Visual Studio start page.  Basically, in versions prior to VS2010, it’s a registry hack (I’ve read that VS2010 provides a way to do this within the IDE, but I haven’t played with 2010 yet so I can’t attest to that myself) [Update: it does – right click the item and select ‘Remove’].

http://aspnetcoe.wordpress.com/2007/02/06/how-to-remove-recent-projects-from-visual-studio-start-page/

http://mvantzet.wordpress.com/2009/09/15/remove-recent-projects-from-visual-studio-2008/

When I removed some items from my version of VS 2008, I found that I also needed to rename the remaining registry keys so that there were no gaps in the order (ie, File1, File2, etc with no gaps)

Working with winmm.dll to play audio files in .NET

I’m working on a little utility application that will transfer audio files from a recorder to a computer drive.  Part of the functionality is to display the audio files, and let users listen to a little snippet of the audio file if they so desire.  A quick google search led me to this page containing a good description of the process, with example code.  Using the examples, I came up with the utility class shown below.  And here’s how I’d use the class in a button event handler:

Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
    Using player As New PlayAudioFile(“C:MiscWS400001.WMA”)
         player.PlaySnippet(5)
    End Using
End Sub

Public Class PlayAudioFile
    Implements IDisposable

    ‘Private data member – file path
    Private fileToPlay As String

    ‘Private function to send commands to the Windows OS MultiMedia API
    Private Declare Function mciSendString Lib “winmm.dll” Alias “mciSendStringA” _
    (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, _
    ByVal uReturnLength As Integer, ByVal hwndCallback As Integer) As Integer

    ‘Private wrapper method for API function
    Private Sub SendCommand(ByVal command As String)
        mciSendString(String.Format(“{0} {1}”, command, fileToPlay), Nothing, 0, 0)
    End Sub

    ”’ <summary>
    ”’ Class Constructor – accepts an audio file (must be MP3, WAV or WMA file)
    ”’ </summary>
    ”’ <param name=”soundFile”>Full path of audio file to be played</param>
    Public Sub New(ByVal soundFile As String)
        Dim ext As String = IO.Path.GetExtension(soundFile)
        Select Case ext.ToLower
            Case “.mp3”, “.wav”, “.wma”
                fileToPlay = Chr(34) + soundFile + Chr(34)
            Case Else
                Throw New ArgumentException(“File must be an .MP3, .wav or .WMA file”)
        End Select
    End Sub

    ”’ <summary>
    ”’ Play audio file
    ”’ </summary>
    Public Sub Play()
        Me.SendCommand(“open”)
        Me.SendCommand(“play”)
    End Sub

    ”’ <summary>
    ”’ Stop audio file playback
    ”’ </summary>
    Public Sub StopPlay()
        Me.SendCommand(“stop”)
    End Sub

    ”’ <summary>
    ”’ Pause audio file playback
    ”’ </summary>
    Public Sub PausePlay()
        Me.SendCommand(“pause”)
    End Sub

    ”’ <summary>
    ”’ Resume playback of paused audio file
    ”’ </summary>
    Public Sub ResumePlay()
        Me.SendCommand(“resume”)
    End Sub

    ”’ <summary>
    ”’ Close audio file
    ”’ </summary>
    Public Sub CloseFile()
        Me.SendCommand(“close”)
    End Sub

    ”’ <summary>
    ”’ Play the first part of the sound file (default 15 seconds)
    ”’ </summary>
    Public Sub PlaySnippet()
        PlaySnippet(15)
    End Sub

    ”’ <summary>
    ”’ Play the first part of the sound file
    ”’ </summary>
    ”’ <param name=”snippetLength”>Length of snippet (in seconds)</param>
    Public Sub PlaySnippet(ByVal snippetLength As Integer)
        Me.Play()
        System.Threading.Thread.Sleep(snippetLength * 1000)
        Me.StopPlay()
    End Sub

#Region ” IDisposable Support ”

    Private disposedValue As Boolean = False        ‘ To detect redundant calls

    ‘ IDisposable
    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
                ‘ TODO: free unmanaged resources when explicitly called
                Me.CloseFile()
            End If

            ‘ TODO: free shared unmanaged resources
            Me.CloseFile()
        End If
        Me.disposedValue = True
    End Sub

    ‘ This code added by Visual Basic to correctly implement the disposable pattern.
    Public Sub Dispose() Implements IDisposable.Dispose
        ‘ Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
#End Region

End Class

There should probably be more error handling in the class (for example, to make sure that the file is opened before calling ResumePlay, that sort of thing), but I thought this was a good start.

DataGridViewComboBox Column Properties

I am copying this verbatim from a post I found by Kevin Spencer which is the clearest explanation I have seen of the main properties of a DataGridViewComboBox. It’s here for my reference. Yay if it helps you too!

The DataGridView itself has a DataSource property that determines what columns are in it. The DataGridViewComboBox column also has a DataSource property, but that isn’t the same as the DataSource of the DataGridView. It is the DataSource that is used to populate the ComboBox in each cell. The DataMember and ValueMember properties are the column names of the columns in the ComboBox’s DataSource that define what is displayed in the ComboBox, and the underlying value for that item. It is the DataPropertyName property of the DataGridViewComboBoxColumn that determines the column name in the DataGridView’s DataSource that the ataGridViewComboBoxColumn is associated with. The ValueMember determines the value that will be set for that column in the DataGridView’s DataSource.

Here’s the original link. Thanks, Kevin Spencer.

How to Query SQL Server Role Members

You can use SQL Server Database Roles to control access to various parts of your application. Let’s say I have created a .NET application. I have a menu called Administration and I only want certain users to be able to see the menu. One way to do this is to use Active Directory Groups. Another way is to use SQL Server Database roles.

For this example I create a role called MyAppAdmin. Only members of MyAppAdmin should be able to see the Administration menu. After creating the role and assigning appropriate permissions to the role, I want to check, within my .NET application, to see if the logged on user is a member of the MyAppAdmin role. Here’s how to do this:

Create a stored procedure:

CREATE procedure [dbo].[uspTestDatabaseRole]
— Returns 1 if user is a member of the specified role or if user is dbo
@RoleName varchar(30)
as
declare @Return integer
if USER_NAME() = ‘dbo’
select @Return = 1
else
select @Return = IS_MEMBER(@RoleName)
select @Return

In this procedure the variable @RoleName refers to the Database Role you are checking. You can also use it to check membership in a Windows group. You may notice if the person calling the stored procedure is dbo, I return 1 no matter what. You may not want the procedure to work this way so you should modify for your own purposes.

Now all you need to do is call this procedure from your .NET code and it will return 1 if the person is a member of the database role you are checking or if the person is dbo. Otherwise, it will return 0.

Accessing a digital camera through a dialog box in .NET

A client has asked us to write a little Windows Forms app that will take the pictures on a digital camera and transfer them to a folder on the hard drive.  No sweat, we thought – it’s very easy to transfer files and folders using the System.IO namespace – files on devices will surely function similarly.

But we searched and searched and Googled and Googled, and came up empty.  Finally we found this blog entry, which is apparently the definitive authority about using an old COM component called Windows Image Acquisition (WIA) to work with cameras and scanners:

(Important Note:  if you don’t have a device connected when you try to run the code that opens the dialog box, you will get an error that looks like this:

Exception from HRESULT: 0x80210015
Source: Interop.WIA
at WIA.CommonDialogClass.ShowSelectDevice(...) )

In the course of trying to work with WIA, we also found an MSDN entry (which has a lot of info but code samples are in C++) and a couple more posts with additional information:

Perhaps there is a more modern, .NET managed code way to do this, but until I find it, I thought I’d better have these links handy!!