Add maxlength to textarea with jQuery

An html input field has a maxlength attribute to limit the number of characters that can be entered in the field, but an html textarea does not.  However, maxlength functionality can be easily added to textarea controls with a little bit of jQuery.

This snippet looks for textareas that have a maxlength attribute, and limits the number of characters to the number in the attribute.  This could use a bit of validation code, perhaps – making sure that the maxlength value is numeric, for example.  But you get the idea…


    $(‘textarea[maxlength]’).keyup(function() {

        //get textarea text and maxlength attribute value
        var t = $(this);
        var text = t.val();
        var limit = t.attr(‘maxlength’);

        //if textarea text is greater than maxlength limit, truncate and re-set text
        if (text.length > limit) {
            text = text.substring(0, limit);


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’].

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”)
    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()
    End Sub

    ”’ <summary>
    ”’ Stop audio file playback
    ”’ </summary>
    Public Sub StopPlay()
    End Sub

    ”’ <summary>
    ”’ Pause audio file playback
    ”’ </summary>
    Public Sub PausePlay()
    End Sub

    ”’ <summary>
    ”’ Resume playback of paused audio file
    ”’ </summary>
    Public Sub ResumePlay()
    End Sub

    ”’ <summary>
    ”’ Close audio file
    ”’ </summary>
    Public Sub CloseFile()
    End Sub

    ”’ <summary>
    ”’ Play the first part of the sound file (default 15 seconds)
    ”’ </summary>
    Public Sub PlaySnippet()
    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)
        System.Threading.Thread.Sleep(snippetLength * 1000)
    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
            End If

            ‘ TODO: free shared unmanaged resources
        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.
    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.

System.Data.OleDb.OleDbException: Unspecified error

I ran across this error in an ASP.NET project that was using ADO.NET to access the data in a .csv file (more info here). After much gnashing of teeth, I finally ran across this blog post, that explained the problem and provided a link to this MSDN article.

Basically, you need to make sure that the user has permissions on both the file in which the .csv file resides, and also the file in which the Jet Engine will create temporary files. It is this last piece that I didn’t know, and lead to days of heartache.

So I thought I’d post, in the hopes of minimizing the heartache for others…

Use HttpModule to turn tracing on via the querystring

Sometimes I want to turn tracing on in a production application to troubleshoot issues that I can’t replicate on my development machine.  It’s easy enough to do this by turning on application-level tracing in the web.config file, like so:

  <trace enabled=”true” pageOutput=”true” />

The problem with this is that changes to the web.config file cause the app domain to recycle, which can cause users currently in the application to lose data.  So I have to schedule a time when all users have to get out, or I have to work after hours, which is a drag.

It’s easy enough to turn on tracing programmatically – Page.Trace.IsEnabled = true.  Then you could write code in the page’s Load event, turning tracing on if the page detects a particular querystring.  The problem here is that you’d have to add the code to every page that you might someday want to trace.

So I decided to create an HttpModule that would turn on tracing via the querystring.  HttpModules allow you to tap in to the HttpRequest pipeline, so your code will run at a designated point in every ASP.NET request.  You can hook up your module to run at various points in the page life cycle, such as BeginRequest, AuthenticateRequest, Error, etc.  (HttpModules are also excellent for application-level error handling). 

In order to create an HttpModule, you have to create a class that implements the IHttpModule interface.  Do this by creating your class, and then typing “Implements IHttpModule” directly under the “Public Class Whatever” line.  Once you hit enter, the two methods that your class must invoke, Init and Dispose, are automatically created for you.

Here’s what my HttpModule class looks like (be sure to import the System.Web namespace):

Option Strict On

Imports Microsoft.VisualBasic
Imports System.Web

Public Class TraceModule
    Implements IHttpModule

    Dim WithEvents app As HttpApplication = Nothing

    Public Sub Init(ByVal context As HttpApplication) Implements IHttpModule.Init
        app = context
    End Sub

    Public Sub context_BeginRequest(ByVal sender As Object, ByVal e As EventArgs) _
    Handles app.BeginRequest

        Dim c As HttpContext = HttpContext.Current
        Dim strTrace As String = c.Request.QueryString(“trace”)

        If strTrace = “on” Then
            c.Trace.IsEnabled = True
        End If

    End Sub

    Public Sub Dispose() Implements IHttpModule.Dispose
        app = Nothing
    End Sub

End Class

After you’ve created your module, you just need to add a setting in the web.config file telling ASP.NET to use your module, as shown below.  If the class is in an assembly in the bin folder, you just need to provide the class name.  If it’s in the App_Code folder, then you need to add that to the setting.

   <!– Module class in assembly called TKS.dll in bin folder –>
   <add name=”WebTraceModule” type=”TKS.TraceModule”/>
   <!– Module class in App_Code folder –>
   <add name=”WebTraceModule” type=”TraceModule, App_Code” />

Now if you want to see the trace for any page in your application, just add the querystring “?trace=on” at the end of the URL, and the trace will display in the page without making any other changes.  If you want to add some security to this, so that not just anybody can run the trace, you can require additional querystrings, or only turn tracing on for certain users or groups, or just about anything else that you can do in code.

Ordinal Numbers in T-SQL

I wanted to write a query that took numbers and turned them into ordinal numbers – re: 1 = 1st, 2 = 2nd, 3 = 3rd, etc.

I took this code from Chip Pearson’s web site. His posting was about ordinal numbers in Excel. I converted the code to a T-SQL function, and I can now use it in any other T-SQL queries I write. Here it is:

create Function dbo.OrdinalNumber
/* used to return an ordinal number */
(@Number integer)
returns varchar(6)
as begin

declare @N int
declare @Suffix char(18)
declare @Result varchar(6)

select @N = @Number%100
select @Suffix = ‘stndrdthththththth’

If ((Abs(@N) >= 10) And (Abs(@N) <= 19))
Or ((Abs(@N) % 10) = 0)
select @Result= cast(@Number as varchar) + ‘th’
select @Result = cast(@Number as varchar) + substring(@Suffix,
((Abs(@N) % 10) * 2) – 1, 2)
return @Result

To use it just feed it the number you want to convert.

select dbo.ordinalnumber(1)
will return “1st”

Using “Execute As” to Test a Stored Procedure as a Different User

In an earlier blog post, I wrote about how to use “Execute As” in a stored procedure to access a separate database. When you include “Execute As” in a stored procedure, you can pull data from a separate database without giving your users direct permissions on that database.

Another way I really like to use “Execute As” is to test the permissions on my stored procedures. You may have had a time or two where a stored procedure ran great when you ran it, but when your user tried it… not so great.

Here’s how to test as that user from either Query Analyzer or SQL Server Management Studio. First, run this line of code, substituting SOMEDOMAIN and Someuser with the appropriate information.

execute as login = ‘SOMEDOMAINSomeuser’

Now run this line of code. It should return the login you just entered.


Now run your stored procedure.

When you are done testing, make sure you run this line (word, actually) of code:


This will set the login back to your login.

Find First Day of Month, Last Day of Month, etc

Today I was writing some code where I needed to calculate the end of the month for a certain date.  As per usual, I Googled, and found various examples, some using old VB functions, some using methods of the Date object,  some very involved and using lots of string manipulation and converting of things from dates to strings and back again, etc.  I used these various examples to develop a little utility class, which is as follows:

Public Class UtilityDates

Public Shared Function GetFirstOfMonth() As Date
Return GetFirstOfMonth(DateTime.Today)
End Function

Public Shared Function GetFirstOfNextMonth() As Date
Return GetFirstOfNextMonth(DateTime.Today)
End Function

Public Shared Function GetEndOfMonth() As Date
Return GetEndOfMonth(DateTime.Today)
End Function

Public Shared Function GetEndOfLastMonth() As Date
Return GetEndOfLastMonth(DateTime.Today)
End Function

Public Shared Function GetFirstOfMonth(ByVal startDate As Date) As Date
‘remove all but one day from date to get first of month
Return startDate.AddDays(-(startDate.Day – 1))
End Function

Public Shared Function GetFirstOfNextMonth(ByVal startDate As Date) As Date
‘get first of month and then add one month
Return GetFirstOfMonth(startDate).AddMonths(1)
End Function

Public Shared Function GetEndOfMonth(ByVal startDate As Date) As Date
‘subtract one day from first of last month
Return GetFirstOfNextMonth(startDate).AddDays(-1)
End Function

Public Shared Function GetEndOfLastMonth(ByVal startDate As Date) As Date
‘subtract one day from first of the month
Return GetFirstOfMonth(startDate).AddDays(-1)
End Function

End Class

Note that each method is overloaded, so you can calculate from the default of today’s date, or send in a specific date.  Of course, you could add a few more functions from here, but I thought that this was plenty for today:)