We Have A Problem

It’s always fun to see an error message you’ve never seen before – even after using a product for almost 10 years.  While trying to check the value of an object while sitting at a breakpoint:

Cannot evaluate expression because we are stopped in a place where garbage collection is impossible, possibly because the code of the current method may be optimized.

Microsoft has very strict guidelines about the verbiage used in their programs.  I can’t believe they let an error message pass through using the word “we” in it.  It’s good to know that the .NET compiler feels that we’re all in this together.  Additionally, the use of the word “impossible” and the vagueness of “possibly because” and “may be” are very out of place.

I’ve never seen an error message so clearly state “That absolutely cannot be done.  I know why, but I don’t know why.”

Finding Solutions In Problems

I’m always looking for novel ways to accomplish something, even it’s totally inefficient… This sounds familiar.

Interestingly, the solution I was experimenting with in the last post is closely related to a problem I took up for resolution today.  In the inefficiency of the code, I found a very clever and unique way of splitting a string on a delimiter like a comma.  Now in this particular case, there was a much more efficient way to accomplish the end result, but I can appreciate the creativity in this query.

This is the code that was focused on:

declare @SortExpression VARCHAR(100) = 'state,zip',@SortOrder VARCHAR(10) = 'ASC'

SELECT STUFF(
(SELECT ', ' + Parsed 
FROM (
    SELECT SUBSTRING(@SortExpression + ',', Number,
        CHARINDEX(',', @SortExpression + ',',Number) - Number) + ' ' + @SortOrder AS Parsed
    FROM Common.dbo.Numbers
    WHERE Number <= LEN(@SortExpression)
    AND SUBSTRING(',' + @SortExpression, Number, 1) = ','
    ) t2
FOR XML PATH(''),TYPE).value('.[1]', 'varchar(MAX)'),1,2,'')

Whenever you see three SELECT keywords and XML together to result in a single value, something seems out of place.  This code takes two strings, “state,zip” and “ASC” and turns it into a single string “state ASC, zip ASC”.  That’s a lot of code for just that.

The interesting part of that query is in the middle, where the query accesses the a database with a table called Numbers which just has a list of numbers from 1 to 10000.  In another post, I created a list of numbers, the exact same thing, in memory using UNPIVOT and a CTE.  I could’ve done the exact same thing to fix this, but the eventual solution I came up with does the same with no recordsets at all to deal with.

Drilling into the inner query,

SELECT SUBSTRING(@SortExpression + ',', Number,
    CHARINDEX(',', @SortExpression + ',',Number) - Number) + ' ' + @SortOrder AS Parsed
FROM Common.dbo.Numbers
WHERE Number <= LEN(@SortExpression)
AND SUBSTRING(',' + @SortExpression, Number, 1) = ','

the thing I find so clever about this query, despite its inefficiency, is the approach it takes.  It uses a sliding window of characters, breaking on the comma, and looking for a trailing comma (that was manually added as a terminator).  When you see the results without the SUBSTRING criteria in the WHERE clause, it looks like:

Parsed

state ASC

state ASC

tate ASC

ate ASC

te ASC

e ASC

ASC

zip ASC

ip ASC

p ASC

And with the SUBSTRING check, the only rows returned are the ones that have a trailing comma.  Code like this makes your head hurt.  In fact, it’s so complex, you almost have to accept it at face value, thinking it’s just so complex, you’d better not touch it.  That is when you isolate and experiment, get the same results, prove it out with different values, and improve it.

So what’s the best replacement I could come up with?

select replace(@SortExpression,',',' ' +@Sortorder + ',') +
case when @SortExpression<>'' then ' ' + @Sortorder else '' end

One complete statement.  Whee!

Finding Solutions Before Problems

I’m always looking for novel ways to accomplish something.  Even if it’s totally inefficient, it still is a good exercise in problem-solving.  Sometimes you can find a good challenge by taking something simple, then making it complex.  For example, there is a simple way to get the first missing value within a non-contiguous range.

declare @i int=1
create table #t(value int)

-- Add numbers in multiples of 4
while @i<100
begin
    if (@i % 4)=0 
    insert #t(value)values(@i)
    set @i=@i+1
end

-- Get first available value
select top 1 t1.value+1
from #t t1
where not exists (
    select 1 
    from #t t2 
    where t2.value=t1.value+1
    )
order by 1

drop table #t

You can get all the next available numbers by removing the “top 1”, but what if the gap was more than 1 value wide?  You’d have to get the first missing values, then fill them or track them in a temp table/variable, then call the statement again.  In this example,  we do have gaps larger than one value.  We want to return 1,2,3,5,6,7,9,10,11, etc. This means we need to check for every value that is not in the #t table.  How would you be able to do that in a single statement?  In pseudo-code, you want to do something like:

select x where not exists (select 1 from #t)

but you have to have a FROM clause.  And that means you have to have the potential values somewhere to pull from.  You could make a temp table/variable and populate it with a range of values you want to compare against, but again, we want this to be done in one statement.

To solve this, you can make a small lookup table using UNPIVOT

select v
from (
    select 0 v0,1 v1,2 v2,3 v3,4 v4,5 v5,6 v6,7 v7, 8 v8, 9 v9
    ) n
unpivot(v for value in (v0,v1,v2,v3,v4,v5,v6,v7,v8,v9)) n

This gets you a resultset of 0 through 9.  Not a lot of values to compare against.  But structuring it as a CTE, you can make this 0-99.  You can join it again to get 0-999, and keep joining until you get the maximum values you need.

with Numbers(num) as
    (
    select v
    from (
        select 0 v0,1 v1,2 v2,3 v3,4 v4,5 v5,6 v6,7 v7, 8 v8, 9 v9
        ) n
    unpivot(v for value in (v0,v1,v2,v3,v4,v5,v6,v7,v8,v9)) n
    ) 
select (N1.num*10)+N2.num 
from Numbers N1
full join Numbers N2 on 1=1

Now that we have a table of lookup values, it’s trivial to find the missing values from our original table.

with Numbers(num) as
    (
    select v
    from (
        select 0 v0,1 v1,2 v2,3 v3,4 v4,5 v5,6 v6,7 v7, 8 v8, 9 v9
        ) n
    unpivot(v for value in (v0,v1,v2,v3,v4,v5,v6,v7,v8,v9)) n
    ) 
select lookupNum
from (
    select (N1.num*10)+N2.num lookupNum
    from Numbers N1
    full join Numbers N2 on 1=1
    ) n
where not exists(    
    select 1
    from #t t
    where t.value=n.lookupnum
    )
order by 1

One complete statement.  Whee!

A Toolbar of Your Favorite Menu Items? Interesting…

Originally posted at SOAPitStop.com – Sept 2, 2009

Remember that little idea that Office had a while ago that would hide infrequently-used menu items?  Wasn’t that a great idea?  For me, it was the very first thing I turned off after installing Office.  But I do understand what they were going after.  When applications do so much, every user is probably just using a subset of the whole application’s features.

The application that I’m writing is kind of getting like that.  A few versions ago, I created a toolbar on the side that was planned to be context-sensitive, so it would show actions based on what data was shown and available – kind of how Microsoft is now doing with the task pane.  Eventually, I may create or convert the toolbar to a task pane.  But as the application was growing, I had the same thought the Office designers had: each user probably only cares about 5 or 6 menu items at a time and those items should be as readily available as possible.  So instead of making personalized menus, I decided to create a Favorites toolbar.  This is similar to Microsoft programs where you can add toolbars and put menu items on them.

Because the application is in flux and because I am lazy, I didn’t want to go through the effort of creating a “Customize Toolbar” dialog.  I also didn’t want to have an extra dialog for “Add To Favorites”.  So what I did was allow menu items to be dragged onto the toolbar.  The proof-of-concept started as most do, just to see how it would work.  I got it going in under 150 lines of code, even less considering whitespace and definitions and all.

To quickly summarize the technique, I started by putting a toolbar container on the form, adding a toolstrip to hold the favorites, and adding a menu to hold the draggable items.

Then I added the code to allow the dragging of the menu items:

    Private Sub Menu_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs) _
        Handles mnuFirst.MouseMove, mnuSecond.MouseMove, mnuThird.MouseMove, mnuFourth.MouseMove, _
        mnu2ndLevel1.MouseMove, mnu2ndLevel2.MouseMove, mnu2ndLevel3.MouseMove

        Dim item As ToolStripMenuItem

        If e.Button = Windows.Forms.MouseButtons.Left Then
            item = CType(sender, ToolStripMenuItem)
            item.DoDragDrop(item, DragDropEffects.Copy)
        End If

    End Sub

Then the code to drop the items (the toolstrip needs to have AllowDrop set to True):

    Private Sub toolFavorites_DragEnter(ByVal sender As Object, ByVal e As DragEventArgs) _
        Handles toolFavorites.DragEnter

        If e.AllowedEffect = DragDropEffects.Copy AndAlso e.Data.GetDataPresent(GetType(ToolStripItem)) Then
            e.Effect = DragDropEffects.Copy
        End If

    End Sub

    Private Sub toolFavorites_DragDrop(ByVal sender As Object, ByVal e As DragEventArgs) _
        Handles toolFavorites.DragDrop

        Dim droppedItem As ToolStripItem

        droppedItem = CType(e.Data.GetData(GetType(ToolStripItem)), ToolStripItem)
        AddToFavorites(droppedItem)

    End Sub

    Private Sub AddToFavorites(ByVal item As ToolStripItem)
        Dim newItem As ToolStripButton

        newItem = New ToolStripButton(item.Text, item.Image)
        newItem.Tag = item
        AddHandler newItem.MouseDown, AddressOf FavoritesContext
        AddHandler newItem.Click, AddressOf FavoritesClick
        AddHandler item.EnabledChanged, AddressOf OnMenuEnabledChanged

        toolFavorites.Items.Add(newItem)

    End Sub

Then the code to route the click of the favorites to the real menu item

    Private Sub FavoritesClick(ByVal s As Object, ByVal e As EventArgs)
        Dim item As ToolStripItem

        item = CType(CType(s, ToolStripItem).Tag, ToolStripMenuItem)
        item.PerformClick()

    End Sub

That was really it.  Of course, then I had to persist the favorites in My.Settings and provide a way of removing the favorite menu item, resulting in the above-referenced AddHandler statement for FavoritesContext and a couple other methods for running through the menu items on the form load and close.  Then we need to disable the favorite button when the linked menu item is disabled, leading to the AddHandler for OnMenuEnabledChanged.  It just keeps growing.

Dating Advice

No, I certainly can’t help you get dates or have successful dates.  But I can offer a couple of functions that might help you work with dates in your code.  I suck at dates (all types).  Every time I want to calculate dates, I need to print a calendar from Outlook and count the days.  It’s pretty ironic that one of my previous projects was all about schedules.  And one of my current projects deals with delivery schedules as well.  So I can’t escape it.

I always would get frustrated because every month was different.  Every month started on a different day and had a different number of days.  It felt impossible to get all the different combinations.  But recently, I had a moment of clarity and realized some basic facts about a month.  Things like:

  • No month has less than 28 days
  • This guarantees every month will have 4 weeks
  • This guarantees there are no less than 4 and no more than 5 of every weekday in a month
  • The only weekdays that will have 5 occurrences will be the days in excess of 28.  These days can be accounted for at the beginning or end of the month – it doesn’t matter.
  • By extension, there are a minimum of 20 workdays in a month (Mon-Fri)
  • And, any additional workdays will be those in excess of 28 that are between Monday and Friday

Earlier attempts to figure out the number of workdays in a month resulted in a brute force loop that would run through every day from 1 to 31 and if the DayOfWeek was Mon-Fri, increment a counter.  Now, with these new guidelines, I can start at 20 and only deal with 0-3 excess days.  Like with this function:

Shared Function WorkdaysInMonth(ByVal d As Date) As Integer
    Dim daysInMonth As Integer
    Dim extraWeekDays As Integer

    daysInMonth = New Date(d.Year, d.Month, 1).AddMonths(1).AddDays(-1).Day

    For i As Integer = 1 To daysInMonth - 28
        Select Case New Date(d.Year, d.Month, i).DayOfWeek
            Case DayOfWeek.Monday, DayOfWeek.Tuesday, _
                DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday

                extraWeekDays += 1

        End Select

    Next

    Return 20 + extraWeekDays

End Function

Using the other rules for weekdays, we know we only need to deal with the exceptions, to find out whether there are 5 weekdays in a month:

Private Shared Function NumberOfWeekdaysInMonth(ByVal weekday As DayOfWeek, ByVal referenceDate As Date) As Integer
    Dim firstDay As DayOfWeek
    Dim lastDay As DayOfWeek

    firstDay = New Date(referenceDate.Year, referenceDate.Month, 1).DayOfWeek
    lastDay = New Date(referenceDate.Year, referenceDate.Month, 1).AddMonths(1).AddDays(-1).DayOfWeek

    If New Date(referenceDate.Year, referenceDate.Month, 1).AddMonths(1).AddDays(-1).Day = 28 Then
        Return 4

    ElseIf lastDay >= firstDay AndAlso weekday >= firstDay AndAlso weekday <= lastDay Then
        Return 5

    ElseIf lastDay < firstDay AndAlso weekday >= firstDay - 7 AndAlso weekday <= lastDay Then
        Return 5

    ElseIf lastDay < firstDay AndAlso weekday >= firstDay AndAlso weekday <= lastDay + 7 Then
        Return 5

    Else
        Return 4

    End If

End Function

That one got a bit hairy because is the extra days started at the end of the week with a high DayOfWeek value, and ended early in the week with a low DayOfWeek value, we had to compensate at each end.  That’s the reasons for all the different IF conditions.  There’s also a specific condition for February’s 28 days.

Finally, a function to determine the first, second, third, fourth, or fifth weekday in a month.  Useful when calculating holidays like Labor Day and Thanksgiving.

Private Shared Function NthDayOfMonth(ByVal index As Integer, ByVal weekDay As DayOfWeek, _
    ByVal referenceDate As Date) As Date

    Dim firstDay As DayOfWeek
    Dim dayOfMonth As Integer

    firstDay = New Date(referenceDate.Year, referenceDate.Month, 1).DayOfWeek
    dayOfMonth = (7 * (index - 1)) + _
        CInt(IIf(firstDay > weekDay, 7 + weekDay - firstDay, weekDay - firstDay))

    Return New Date(referenceDate.Year, referenceDate.Month, dayOfMonth + 1)

End Function

Autosize. No, not the control, the text.

Originally posted to SOAPitStop, Nov 16, 2008.

It’s nice that .NET controls have an auto-size property so you don’t have to worry about overflow and all.  But what about cases where you have a fixed layout?  Well, that’s simple, you turn autosize off and fix the control to the size you need.

That’s half the story.  What about the text that’s inside it?  Now you know I’m talking to marketing people when I say that there are times you want the text to be as big as possible within that control.  But you can’t just set the font to a huge size, because sometimes you’ll have more text to display and the font size must regrettably be reduced.

To accommodate this, I made a quick method that brute-forces the correct font size in the control.  basically, stepping down the size of the font until it fits.  I know loops like this are cheap, poor programming, and I did give consideration to doing some hard math to calculate the proper font size based on the initial size, but sometimes not getting hung up on performance can be liberating.

    Private Sub ResizeText(ByVal c As Control)
        Dim currentSize As Size
        Dim currentFont As Font

        currentFont = c.Font

        Do
            currentSize = TextRenderer.MeasureText(c.Text, currentFont, _
                c.Size, TextFormatFlags.WordBreak)

            If currentSize.Width > (c.Width - c.Margin.Horizontal) _
                OrElse currentSize.Height > (c.Height - c.Margin.Vertical) Then

                currentFont = New Font(currentFont.FontFamily, _
                    CSng(currentFont.Size - 0.5), currentFont.Style, currentFont.Unit)
            Else
                Exit Do

            End If

        Loop While currentFont.Size >= 1

        c.Font = currentFont

    End Sub

/span

Casting Upwards

When binding business objects to a datagrid, often you have a need to display some information that is not directly exposed by the object itself.  Maybe it’s a calculated value, maybe it’s something nested deeper in the object.  When faced with this issue, there are a few different action paths you can take.  You can add extra read-only properties to your business object to support the extra view information.  You can create a new class that inherits from the class you are displaying and put the extra properties in there.  Or you can handle the CellFormatting event in the datagrid and change the displayed values manually.  One of the downsides of using a new derived class with extra properties is that you can’t cast a base class to it.  You could cast down to the base class, but no casting up.

Here is a technique that is closest to the second option listed above and side-steps the upcasting problem.  I dislike the first option because it clutters the business object with UI-specific code.  Going with option 2 is only slightly better, while you can populate the correct display-specific object and return it from your business logic layer, either you have to have a method that return the derived type, or you will have to cast it to its correct type in the UI.  Even then, your business layer still contains UI logic.

So, keeping things separated, the derived display-specific class should be defined in the UI layer.  This means it will have extra read-only properties for use with databinding.  The business layer will return the basic object(s), so it will be up to us to convert these to UI-friendly versions.  There are two problems with converting the object: not all the object state may be exposed via public properties, and those properties may contain logic.  It would be best to copy the object by its internal state – private variables.

On first thought, working with the private variables means the code must be inside the source object and the destination object.  This would be tedious to do, passing in the destination object, then sending the source object’s private variables to the destination so the destination object can manipulate its own private variables.  Yuck.  However, using Reflection, the job gets a whole lot easier.

Here’s a small class with a method to convert one class to another by copying its private and public fields.  The properties are intentionally excluded since they may contain logic that modifies the internal state.  You should use this technique with care and know exactly what it does and does not do.  Basically, it copies values from one instance of a class to another.  This is fine for simple classes, but it’s not going to resolve references for you.

Consider ClassA with a private field of type ClassB.  ClassB maintains a private variable with a reference to ClassA, so that it can manipulate all of its "parent’s" state and logic.  If you use this technique to cast ClassA to ClassAA, because you want an extra property to display some info from ClassB, you’re in for some fun results if you change some data in ClassAA.  This is because ClassB still has a reference to ClassA, not ClassAA.

Public Class UpCaster
    Shared Sub CastUp(ByVal sourceObj As Object, ByVal destinationObj As Object)
        Dim values As New Dictionary(Of String, Object)
        Dim props() As Reflection.FieldInfo 

        props = sourceObj.GetType.GetFields(Reflection.BindingFlags.NonPublic _
            Or Reflection.BindingFlags.Static _
            Or Reflection.BindingFlags.Instance _
            Or Reflection.BindingFlags.Public) 

        For Each p As Reflection.FieldInfo In props
            values.Add(p.Name, p.GetValue(sourceObj))
        Next 

        props = destinationObj.GetType.GetFields(Reflection.BindingFlags.NonPublic _
            Or Reflection.BindingFlags.Static _
            Or Reflection.BindingFlags.Instance _
            Or Reflection.BindingFlags.Public) 

        For Each p As Reflection.FieldInfo In props
            If values.ContainsKey(p.Name) Then p.SetValue(destinationObj, values(p.Name))
        Next 

    End Sub 

End Class

Too Many Items In Combo Box: When One Is Just One Too Many

I got to troubleshoot a dumb error message today.  The error was "Too many items in combo box."  The situation was anything but.  I was only adding one item.

So I got it working and I wanted to find out why it happened in the first place.  The error it should have returned was "Value cannot be NULL" because that was the root of the problem.  So here’s a distilled piece of code to illustrate the problem.  Create a form and put a combo box on it.  The code for the form should look like:

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _ 
        Handles MyBase.Load

        Dim d As New DisplayItem
        ComboBox1.Items.Add(d)

    End Sub

End Class

Public Class DisplayItem
    Public Name As String

    Public Overrides Function ToString() As String
        Return Name
    End Function

End Class

The problem is the combo box is trying to display DisplayItem.Name, because that is what the ToString says to do, but the value of Name is Nothing.  You can fix this by setting the value of Name to String.Empty or something else.  The odd thing is that you can also fix the problem by commenting out the ToString override.  To figure this out, I fired up Reflector and went to see what was going on behind the scenes.

This particular situation is basically bypassing all the safe value checks done when adding an item to a list control.  I suppose Microsoft should add a test case for this scenario, but really, if the programmer is attentive, this shouldn’t happen.  I, naturally, happen to be inattentive.

Behind the scenes of the Add method of the Items collection, the first check is in the AddInternal method.  Since we’re passing in an instance of DisplayItem, it passes that check.  The next step is in the NativeAdd method.  At this point, we’ve done our NULL checks and it is assumed we can convert the object to a string.  This method now calls GetItemText.

GetItemText parses the properties of the object passed in and gets the string value.  If the DisplayMember property is not set, the control uses the ToString value of the object itself.  Because we overrode ToString, the control trusts us and returns the value from ToString, the Name value.  This turns out to be Nothing – Oops!  We’ve already passed the check for Nothing, so this sends bad data to the Win32 API, bubbling a failure error code back to NativeAdd.  If NativeAdd gets anything but a success, it always returns the message “Too Many Items In Combo Box”.  But the real reason is that you snuck a Nothing past the initial validation.

Interestingly, if the DisplayMember is set, and the value of the property is Nothing, it is handled properly in GetItemText.  If we converted Name to a private field and made a public property, then set the DisplayMember of  ComboBox1, it would work.  If your display member is another object that overrides the ToString function, you can get around that check as well and return Nothing, causing a failure.

The simple solution for this error message is to avoid NULL values.  The bottom line is to have .ToString always return a string, never Nothing.

IsInRole While Disconnected; No Longer IsInHole

In an application I am continuing to write, during startup, the user’s security is determined by the user’s security groups and permissions are granted within the program based on the group membership.  This has worked fine.  Then one day in an airport I wanted to work on some documentation and I quickly discovered that I could not run the program.  I could not run the program because I was not on the VPN and the Active Directory (AD) groups could not be enumerated to check my permissions.  At the time, I was kind of grateful I couldn’t do any work and didn’t give it much more thought. Our application is not designed to be run in a disconnected fashion.  You have to be on the VPN to get to the database server and use it.  Lately, I revisited the problem and decided to resolve it.

In my particular instance, I had a database running locally, but I was missing an Active Directory server to read from.  I had my cached credentials, shouldn’t that be enough?  Well, it is, if you do it the hard way.

Everyone should know that a user or a group is just a name.  There is an ID behind that group or user, which allows you to rename the group/user without breaking anything.  Behind the scenes, Windows always uses the ID.  The name is just for your benefit.

Using the excellent tool WhoAmI, I saw the following (don’t chide me for running as Administrator):

C:\>whoami /groups /sid

[Group  1] = "700CB\Domain Users"  S-1-5-21-2454202000-1896829455-2950045386-513
[Group  2] = "Everyone"  S-1-1-0
[Group  3] = "DA3\Debugger Users"  S-1-5-21-854245398-1547161642-725345543-1007
[Group  4] = "DA3\Offer Remote Assistance Helpers"  S-1-5-21-854245398-1547161642-725345543-1004
[Group  5] = "BUILTIN\Users"  S-1-5-32-545
[Group  6] = "BUILTIN\Administrators"  S-1-5-32-544
[Group  7] = "NT AUTHORITY\INTERACTIVE"  S-1-5-4
[Group  8] = "NT AUTHORITY\Authenticated Users"  S-1-5-11
[Group  9] = "LOCAL"  S-1-2-0
[Group 10] = "700CB\Domain Admins"  S-1-5-21-2454202000-1896829455-2950045386-512

When disconnected form the LAN (you might need to reboot while disconnected to clear the cache), it looks like:

C:\>whoami /groups /sid

[Group  1] = ""  S-1-5-21-2454202000-1896829455-2950045386-513
[Group  2] = "Everyone"  S-1-1-0
[Group  3] = "DA3\Debugger Users"  S-1-5-21-854245398-1547161642-725345543-1007
[Group  4] = "DA3\Offer Remote Assistance Helpers"  S-1-5-21-854245398-1547161642-725345543-1004
[Group  5] = "BUILTIN\Users"  S-1-5-32-545
[Group  6] = "BUILTIN\Administrators"  S-1-5-32-544
[Group  7] = "NT AUTHORITY\INTERACTIVE"  S-1-5-4
[Group  8] = "NT AUTHORITY\Authenticated Users"  S-1-5-11
[Group  9] = "LOCAL"  S-1-2-0
[Group 10] = ""  S-1-5-21-2454202000-1896829455-2950045386-512

My local group names were resolved to their names, but my domain group names couldn’t resolve because AD was unreachable.  My cached profile still had the SIDs though.

So, if I could do an IsInRole check using the SID instead of the domain group name, I’d be golden.  And this is just what I did.

Imports System.Security.Principal
Imports System.Threading

Dim sid As New SecurityIdentifier("S-1-5-21-1859785585-1835888107-1082013118-1025")
Dim p As WindowsPrincipal = CType(Thread.CurrentPrincipal, WindowsPrincipal)

MsgBox(p.IsInRole(sid))

So I took the SID for the groups I was testing for and tested for them instead.  Obviously, if an admin deleted and recreated the group thinking nobody would notice, it would be hell to troubleshoot, so if you’re not fully in control of your environment, you might want to steer clear.  Maybe do the SID after checking IsNetworkAvailable to reduce the exposure to failure?

But for me, it works like a champ, and now I can work in airports.  Hmmm.  Why did I figure this out again?

Columns Autosize: Listview in List View

Here’s another little snip of code I couldn’t find online when I needed it.  Geez, when I became a programmer, I wasn’t thinking I’d have to actually figure things out on my own.  That’s a lot of work.

Anyway, the problem I faced was when I had a Listview control on a form and I changed views from anything to List view, the columns of the items were really small, so I’d get ellipses’ after all the entries.  Sure, I could just set the column with to some obnoxious amount like 500, but that’s a waste of space.  So after searching and seeing a bunch of postings about using a Win32 API call to autoresize the column, then getting disappointed because it was for VB 4/5/6, I just hacked through it.

The Details view has an autosize feature, but apparently they didn’t extend it to the List view.  But we can still make use of it.  Why not switch to detail, set the autosize of column 0 to true, then measure how wide it makes the column, then use that as the column width in List view?  That’s a dumb idea.  Who would do something like that.  Oh, what do you know, it works.

Dim maxSize As Integer

lstItems.View = View.Details
lstItems.Columns(0).AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)
maxSize = lstItems.Columns(0).Width

lstItems.View = View.List
lstItems.Columns(0).Width = maxSize
lstItems.Refresh()

Yay.