2025-11-16

Visual Studio 2026 Includes Code Coverage in Community and Professional!

On a posting I made on 2014-02-03, I asked that Microsoft include code coverage in the Community and Professional editions of Visual Studio. In my opinion, it was the most glaring missing feature in those editions. They included it in their Enterprise edtion, but the cost was prohibitive.

In the 11+ years since, I have posted multiple times about it being missing. This was not a big work item, since most likely it just took flipping a variable in the Visual Studio build process to include it. There has been on open thread on the Microsoft Visual Studio feature requests site for about that long. At one point, Microsoft said they'd never do it and closed the request, which caused a furious response by the several hundred people follow that thread. I think the response caused a reconsideration.

Well, it finally happened. Visual Studio 2026 includes code coverage in all editions. I would like to commend Microsoft for finally adding this feature. I noticed that on the page of new features, they put it right at the top, above all of the AI features they added to Visual Studio.

Code coverage is the tool that tells you what code is hit while it is being run. It is mainly used in conjunction with unit tests. It tells you what code your unit tests are not hitting. Having unit tests as a feature without code coverage as well makes makes it impossible to measure the comprehensiveness of your unit tests.

Check out the feature in Visual Studio 2026. Microsoft claims that they addressed over 300 feature requests in this version. I am sure some of the other ones are great, but code coverage has been at the top of my list for a very long time.

2025-03-03

Where did the C# Programming Language Name Originate

In the late 1980s at Microsoft, there was an attempt at constructing some extensions to the C++ programming language, which were internally named C#. This project failed, was cancelled, and never used. The database used internally by the language required more resources than the hardware that was available at the time could provide.

However, about a decade later when Microsoft again attempted to form a programming language, they recycled the name. This name is now used for one of the most popular programming languages. The name was meant to represent C++++, if you view the # sign as four plus signs. C++ means "one better than the C programming language". C# means "two better than the C programming language".

2024-07-10

Changing a Picture in Microsoft Visio

Visio doesn't give you a built in way to change the picture that you've added to a diagram to another picture. But with some VBA code, you can perform the task.

First, you will need to add the code below. Press Alt+F11 on the keyboard to open the Visual Basic Editor. Click Insert > Module from the menu. Paste the code below into the module. Save your drawing as a Visio Macro-Enabled Drawing (with a .vsdm extension).

Then to change a picture to another picture, select it. Then press Alt+F8 to open the macros dialog. Select ChangePicture from the dialog and click Run. A dialog will open asking you for a file. Select the file and click OK. The picture will change without losing things such as connections to the picture.

Most of the code is just to open the dialog to ask for the filename. The main  task is to call the shape's ChangePicture method.


Option Explicit

Private Declare PtrSafe Function GetOpenFileName _
    Lib "comdlg32.dll" _
    Alias "GetOpenFileNameA" ( _
    pOpenfilename As OPENFILENAME) As Long

Private Declare PtrSafe Function CommDlgExtendedError _
    Lib "comdlg32.dll" () As Long

Private Type OPENFILENAME
    lStructSize         As Long
    hwndOwner           As LongPtr
    hInstance           As LongPtr
    lpstrFilter         As String
    lpstrCustomFilter   As String
    nMaxCustFilter      As Long
    nFilterIndex        As Long
    lpstrFile           As String
    nMaxFile            As Long
    lpstrFileTitle      As String
    nMaxFileTitle       As Long
    lpstrInitialDir     As String
    lpstrTitle          As String
    flags               As Long
    nFileOffset         As Integer
    nFileExtension      As Integer
    lpstrDefExt         As String
    lCustData           As LongPtr
    lpfnHook            As LongPtr
    lpTemplateName      As String
    '#if (_WIN32_WINNT >= 0x0500)
    pvReserved          As LongPtr
    dwReserved          As Long
    FlagsEx             As Long
    '#endif // (_WIN32_WINNT >= 0x0500)
End Type

Private Const OFN_READONLY = &H1
Private Const OFN_OVERWRITEPROMPT = &H2
Private Const OFN_HIDEREADONLY = &H4
Private Const OFN_NOCHANGEDIR = &H8
Private Const OFN_SHOWHELP = &H10
Private Const OFN_ENABLEHOOK = &H20
Private Const OFN_ENABLETEMPLATE = &H40
Private Const OFN_ENABLETEMPLATEHANDLE = &H80
Private Const OFN_NOVALIDATE = &H100
Private Const OFN_ALLOWMULTISELECT = &H200
Private Const OFN_EXTENSIONDIFFERENT = &H400
Private Const OFN_PATHMUSTEXIST = &H800
Private Const OFN_FILEMUSTEXIST = &H1000
Private Const OFN_CREATEPROMPT = &H2000
Private Const OFN_SHAREAWARE = &H4000
Private Const OFN_NOREADONLYRETURN = &H8000&
Private Const OFN_NOTESTFILECREATE = &H10000
Private Const OFN_NONETWORKBUTTON = &H20000
Private Const OFN_NOLONGNAMES = &H40000          '  force no long names for 4.x modules
Private Const OFN_EXPLORER = &H80000             '  new look commdlg
Private Const OFN_NODEREFERENCELINKS = &H100000
Private Const OFN_LONGNAMES = &H200000           '  force long names for 3.x modules

Private Const OFN_SHAREFALLTHROUGH = 2
Private Const OFN_SHARENOWARN = 1
Private Const OFN_SHAREWARN = 0

Private Const CDERR_DIALOGFAILURE = &HFFFF&

Private Const CDERR_GENERALCODES = &H0
Private Const CDERR_STRUCTSIZE = &H1
Private Const CDERR_INITIALIZATION = &H2
Private Const CDERR_NOTEMPLATE = &H3
Private Const CDERR_NOHINSTANCE = &H4
Private Const CDERR_LOADSTRFAILURE = &H5
Private Const CDERR_FINDRESFAILURE = &H6
Private Const CDERR_LOADRESFAILURE = &H7
Private Const CDERR_LOCKRESFAILURE = &H8
Private Const CDERR_MEMALLOCFAILURE = &H9
Private Const CDERR_MEMLOCKFAILURE = &HA
Private Const CDERR_NOHOOK = &HB
Private Const CDERR_REGISTERMSGFAIL = &HC

Private Function GetFileName() As String
    Dim lngResult As Long
    Const MAX_BUFFER As Long = 250

    Dim OFN As OPENFILENAME

    With OFN
        .lpstrFilter = "All Files (*.*)" & vbNullChar & "*.*" & vbNullChar
        .nFilterIndex = 1
        .lpstrFile = Space$(MAX_BUFFER - 1) & vbNullChar
        .nMaxFile = Len(.lpstrFile)
        .lpstrFileTitle = Space$(MAX_BUFFER - 1) & vbNullChar
        .nMaxFileTitle = Len(.lpstrFileTitle)
        .lpstrInitialDir = "C:\"
        .flags = OFN_FILEMUSTEXIST Or OFN_PATHMUSTEXIST
        .lStructSize = LenB(OFN)
    End With

    lngResult = GetOpenFileName(OFN)

    If lngResult <> 0 Then
        GetFileName = Left$(OFN.lpstrFile, InStr(1, OFN.lpstrFile, vbNullChar) - 1)
    Else
        GetFileName = vbNullString
    End If
End Function

Public Sub ChangePicture()
    Dim strFileName As String
    Dim shp As Shape
    
    ' Ensure a shape is selected
    If Application.ActiveWindow.Selection.Count = 0 Then
        MsgBox "Please select a shape first."
        Exit Sub
    End If
    
    strFileName = GetFileName()
    If Len(strFileName) > 0 Then
        Set shp = Application.ActiveWindow.Selection.PrimaryItem
        Call shp.ChangePicture(strFileName)
    End If
End Sub

2024-06-19

Getting a Microsoft Publisher Style Color to Stick

In Microsoft Publisher, If you try to set a font color in a style, it won't seem to save. If you change the color, it will look like it saved, but if you close the file, open it again, the color will have reset to black. The trick to getting it to actually save is to change both the fill color and the outline color. Follow these steps:

  1. Click Home > Styles > Styles
  2. Right click on the style you want to change
  3. Click the "Text effects..." button
  4. Click the Text Fill & Outline button at the top
  5. Set the Text Fill to the Solid fill option
  6. Pick your color
  7. Set the Text Outline to the Solid line option
  8. Pick the same color
  9. Click OK

Now your color will save to the style.



2024-04-22

How to Move a Window When You Can't Click on the Title Bar

This is a little tip for how to move a window when, for some reason, the title bar is off the top of the screen. This can happen when  you change screen resolutions or have a window on a second monitor that is no longer available and the window gets moved to the main monitor. The trick is to click Alt+<Space>, M, then use the arrow keys to move the window.

If you went back many years ago, the application menu icon in the upper left of the window used to look like a minus sign. It now shows the application icon. Except that wasn't a minus sign, it was a picture of the space bar on the keyboard. Nobody, not even the programmers at Microsoft, got the reference that Alt+<Space> activates the application menu. M is the access key for Move. Once Move is activated, the arrow keys become active to move the window.

2024-02-09

Where Does Office Store the Most Recently Used List?

Where does Microsoft Office save the Most Recently Used list for Word, Excel, etc.? The answer is in a file under this directory:

C:\Users\UserName\AppData\Local\Microsoft\Office\VersionNumber\MruServiceCache

There will be a directory under that that is randomly generated, then under that is the product name. Then under that is a file with the name Documents_en-US (or whatever the language). That file is a JSON file that has the list in it.

2022-11-07

The Correct Way to Handle Multiple Exceptions in C#

This is just a quick article on the correct way to handle multiple exceptions with the same code in C#. In older versions of C#, one way to handle multiple exceptions was code like this:


    try
    {
        // Code that can fail
    }
    catch (IOException)
    {
       // Failure code A
    }
    catch (ArgumentException)
    {
       // Failure code A
    }

This violates this violates the DRY (Don't Repeat Yourself), concept with Failure code A being repeated. Yes, you can call a method (or even a lamda function) from the failure code, but that creates code that is elsewhere for something that should be handled here. Another attempt would be something like this:


    try
    {
        // Code that can fail
    }
    catch (Exception ex)
    {
        if (ex is IOException || ex is ArgumentException)
        {
            // Failure code A
        }
        else
        {
            throw;
        }
    }

This is better (and the right way in C# before version 6), but it is clumsy. Incidentally, in this code, it would be important to use just throw, not throw ex as C# does not treat them the same. Using just throw preserves the stack trace so that the call stack shows the origination of the exception, whereas throw ex shows the exception originating in this code.

Here is the right way to handle it with current versions of C#:


    try
    {
        // Code that can fail
    }
    catch (Exception ex) when (ex is IOException or ArgumentException)
    {
        // Failure code A
    }

Incidentally, the convention in C# is to use "ex" as the variable for exceptions, as "e" is used for the second argument in event handlers, and if you have exception handling code in an event handler, you don't want them to conflict.

2021-11-10

Excel Bug Changes Color on Cell Not in Range

I'm in the process of writing an Excel add-in, using the relatively new mechanism of writing a TypeScript library. I had previously written this Excel add-in in C# on .NET Framework 4.8, but this mechanism doesn't work in .NET 5 or 6 for architectural reasons. (With a bunch of tricks, I got Excel calling .NET 5 code configured as a COM DLL, but it won't work if the user's machine is configured in some ways and I couldn't get the add-in recognized correctly.) The TypeScript actually calls a web API that then calls the C# on the server side, so this wasn't a rewrite from the ground up but a layer thrown on top of my previous code, but Excel never sees that. From Microsoft's perspective using JavaScript has the advantage that it is portable, meaning that these add-ins can work on Windows, iOS, the web, phones, or anywhere else that Microsoft can place Excel.

TypeScript is a language that adds strongly typed features to JavaScript. It compiles into JavaScript, so it works anywhere that JavaScript does. I dislike weakly typed languages like JavaScript, so TypeScript makes JavaScript acceptable.

So in the process of writing my add-in, I ran into a bug in the Excel Javascript/Typescripts APIs. I formatted cells A6:A11 to have a blue background, and oddly enough, cell A13 turned blue as well. I don't know what the internals of the Javascript API or Excel look like, but this bug is really strange, as it seems to be dependent on the data that is in a formatted cell. In any case, I reduced the code to a small easily reproducible case, wrote it up, and submitted it to Microsoft. They confirmed the bug the same day I submitted it and have assigned it to a developer.

More info: It turns out that this is not a Javscript API bug. It is a design flaw in Excel. If you format the backcolor of three or more cells (doesn't happen with two), say A6:A8, then change a cell within three cells, say A11, it will also change color. This came back as BY DESIGN. What a stupid design. It is unfathomable to me that this is what a user would want or expect.

Here is some equivalent VBA code (press Alt+F11, double-click on Sheet1, insert the code, press F5 to run it):

  Public Sub ExcelBug()
    Sheet1.Range("A1:A3").Interior.Color = vbBlue
    Sheet1.Range("A1").Value = "a"
    Sheet1.Range("A2").Value = "b"
    Sheet1.Range("A3").Value = "c"
  End Sub
  
Run the code. Now type anything into cell A5 and press enter. What do you think...should the backcolor change to be blue? Well, it does. Now delete the value and change the backcolor to be no fill. Add the following line just before the End Sub:
      Sheet1.Range("A5").Value = "d"
  
Now run the code. A5 doesn't change to be blue. Now delete the value and type it again. No blue. What are the rules on when it will change to be blue? Now put the same data into Excel on the web. Will it be blue or not? Answer: not. Regardless of whether they claim it is by design, this is a bug.

2021-11-01

Microsoft Access Combo Box Search While Typing

If you start typing in a Microsoft Access combo box, it might not search as you type. I eventually figured out the trick to making the search work. The problem occurs when the combo box is based on a query. For the query to work, it must be a DISTINCT query. In other words, if you go to SQL View (select View SQL from the ribbon), and the query is:

SELECT tblCategory.pcCategoryId, tblCategory.strCategory
FROM tblCategory
ORDER BY tblCategory.strCategory;

Change it to:

SELECT DISTINCT tblCategory.pcCategoryId, tblCategory.strCategory
FROM tblCategory
ORDER BY tblCategory.strCategory;
After that the search while typing should work.

2021-05-13

Displaying an Image in a Microsoft Access Image Control

If you have a column in a Microsoft Access table that has the name of an image that refers to a file on the disk, you can update an image control in either a form or report with the code below. Put this code into a standard VBA module that you create with Insert Module from the menu. This code assumes that all the images are in a subdirectory of the location of the database called "images" if there are relative paths to the image file.

Public Const strImageFolder = "images"

Public Sub DisplayImage(ctlImageControl As Control, strImagePath As Variant)
    On Error GoTo ErrorHandler
    
    If IsNull(strImagePath) Then
        ctlImageControl.Visible = False
    Else
        If InStr(1, strImagePath, "\") = 0 Then
            strImagePath = Application.CurrentProject.Path & "\" & strImageFolder & "\" & strImagePath
        End If
        ctlImageControl.Visible = True
        ctlImageControl.Picture = strImagePath
    End If
    Exit Sub
ErrorHandler:
    Select Case Err.Number
        Case 2114 'Doesn't support the format of the file
            ctlImageControl.Visible = False
        Case 2220 ' Can't find the picture.
            ctlImageControl.Visible = False
        Case Else  ' Some other error.
            MsgBox "Unexpected Error #" & Err.Number & " " & Err.Description, vbExclamation, "Unexpected Error"
    End Select
End Sub

To use this code in a form, if the control that contains the image name txtPicture and the image control is named imgPicture then add this code to the module for the form:

Private Sub Form_AfterUpdate()
    Call DisplayImage(Me!imgPicture, Me!txtPicture)
End Sub

Private Sub Form_Current()
    Call DisplayImage(Me!imgPicture, Me!txtPicture)
End Sub

Private Sub txtPicture_AfterUpdate()
    Call DisplayImage(Me!imgPicture, Me!txtPicture)
End Sub

To use it in a report, assuming there is a column in the table or query the report is based on called strPicture and an image control named imgPicture, add this code to the report:

Private Sub Detail_Print(Cancel As Integer, PrintCount As Integer)
    Call DisplayImage(Me!imgPicture, Me!strPicture)
End Sub

Open a URL using VBA

This is just a quick tip on opening a hyperlink using the default browser in VBA. It uses the ShellExecute Windows API call. Call the OpenHyperlink function shown below with the URL that you want to open.

Private Declare PtrSafe Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" ( _
  ByVal hWnd As Long, _
  ByVal lpOperation As String, _
  ByVal lpFile As String, _
  ByVal lpParameters As String, _
  ByVal lpDirectory As String, _
  ByVal nShowCmd As Long _
  ) As Long

Public Function OpenHyperlink(ByRef strHyperlink As String) As Long
    OpenHyperlink = ShellExecute(0, "Open", strHyperlink, vbNullString, vbNullString, vbNormalFocus)
End Function

An example of calling it is:

Call OpenHyperlink("http://blog.xoc.net")

2021-05-09

Extracting Microsoft Access OLE Object Field Items

I created a Microsoft Access database for a small set of data (<1000 rows). Access was a perfect database for this particular problem, allowing easy input and good reporting, and the Access accdb database format allows easy installation on different computer that have Access. However, I made a mistake in storing bitmaps in an OLE object column. Access still has a limit of two gigabytes for its native database format. Bitmaps don't compress and quickly consume all of that limit. I had entered several hundred items before running into that limit. The two gigabyte limit was reasonable in the 1990s when a 1 gigabyte drive cost over $1000 (I have a receipt!), but is ridiculously small by today's standard.

The VBA code below works on the table tblExample. It extracts the bitmap from an OLE Object column (olePicture) and writes it to a file on the disk. It then updates another column (strPicture) with the name of the file it wrote. The filename is constructed by the name of the primary key field (ID) followed by .bmp, thus ID of 1 becomes 1.bmp in the same directory as the database.

An OLE Object field has a Package Header, an OLE header, the actual data of the bitmap, some optional other stuff, and an OLE footer. The problem is that the headers are variable length with sizes embedded into them, so the actual bitmap has to be located within the data before it can be extracted. So this code extracts the sizes and skips to the appropriate place and extracts the data. It uses a helper function that constructs a long from the first four bytes of an array of bytes (although it will break if a size is over 2^31 as it would try to convert an unsigned count to a signed count, which should never happen here).

After running this code successfully (use the Windows File Explorer to view the bitmaps), the OLE Object column can be deleted. Other VBA code will be necessary to display the picture in the external file, which is beyond the scope of what I want to show here. The code is not very fast as it writes the file one byte at a time, but it should be a one-time thing, at least for my purpose. It also probably has some boundary conditions related to some kinds of OLE objects that break it under some conditions, but it worked for what I needed.

Option Compare Database
Option Explicit

Public Sub ExtractImages()
    ' Need a reference to the Microsoft ActiveX Data Objects 6.1 Library
    Dim rst As ADODB.Recordset
    Dim varByte As Variant
    Dim i As Long
    Dim lngLength As Long
    Dim byteVal As Byte
    Dim strFileName As String
    Dim strFilePath As String
    
    Set rst = New ADODB.Recordset
    rst.Open "tblExample", CurrentProject.Connection, adOpenDynamic, adLockOptimistic
    Do While Not rst.EOF
        If Not IsNull(rst.Fields.Item("olePicture").Value) Then
            ' Create the filename from the primary key ID field.
            strFileName = rst.Fields.Item("ID").Value & ".bmp"
            
            ' Fill strPicture with the filename
            rst.Fields.Item("strPicture").Value = strFileName
            rst.Update
            
            strFilePath = Application.CurrentProject.Path & "\" & strFileName
            If Dir(strFilePath) = "" Then
                ' Read the package header the package header, the second byte is the size
                varByte = rst.Fields.Item("olePicture").GetChunk(3)
                
                'Extract the offset to the start of the OLE header
                varByte = rst.Fields.Item("olePicture").GetChunk(varByte(2) + 5)
                
                'Get the first four bytes which holds the OLE size
                varByte = rst.Fields.Item("olePicture").GetChunk(4)
                
                ' Use to size to of the header to move to the end of the header
                varByte = rst.Fields.Item("olePicture").GetChunk(GetLong(varByte))
                
                ' Skip the next eight bytes
                varByte = rst.Fields.Item("olePicture").GetChunk(8)
                
                ' The next four bytes retrieves the size of the Bitmap
                varByte = rst.Fields.Item("olePicture").GetChunk(4)
                
                ' Turn those bytes into a length
                lngLength = GetLong(varByte)
                
                ' Get the bitmap
                varByte = rst.Fields.Item("olePicture").GetChunk(lngLength)
                
                ' Write the bitmap to the file
                Open strFilePath For Binary As #1
                For i = 0 To lngLength - 1
                    byteVal = varByte(i)
                    Put #1, , byteVal
                Next i
                Close #1
            End If
        End If
        rst.MoveNext
    Loop
    rst.Close
    Set rst = Nothing
    MsgBox "Done"
End Sub

Public Function GetLong(ByRef varByte As Variant) As Long
    ' Convert the first four bytes of varByte into a long
    Dim i As Long
    Dim lngResult As Long
    
    For i = 3 To 0 Step -1
        lngResult = lngResult * 256 + varByte(i)
    Next i
    GetLong = lngResult
End Function

2021-03-22

What Does the "Home" Key Do in Microsoft Editors?

I want to give a little anecdote on how I changed how people program. It was some time around 1990, maybe plus or minus a year. I was working on the Microsoft Access programming team at Microsoft. Actually they still hadn't settled on a name yet and eventually stole the name of a communications product Microsoft had shipped earlier and re-used it for their database, but I digress. I spent the majority of my hours in the buildings at Microsoft. My friends also worked at Microsoft, so when I wasn't working, I'd frequently head over to their office and just hang out. We all worked long hours.

One of my friends there was a programmer named Richard. Richard ostensibly worked on the database engine side of Microsoft Access, whereas I was on the user-interface side, but Richard had kind of "god-level" access to all of the code across Microsoft's Application Division. Anything that wasn't part of the operating system at Microsoft, he was authorized and trusted to go in and change.

I was sitting in Richard's office one night, and he said there had been a debate on what the "Home" key should do in Microsoft's editors. One camp said it should go to the beginning of the line. The other camp said it should go to the first non-whitespace character on the line, after any spaces or tabs. He asked, "what do you think it should do?" I said, "what if the first time you pressed it, it went to the first non-whitespace character, but if you were already there, it went to the start of the line?" He said, "that's a good idea!" And as I sat there, he went in and changed the code in Visual Studio and the Visual Basic editors. Try it, because it still does that today.

Now this was kind-of the dark ages in software development. Microsoft was just putting its first usability testing groups together, so today you'd probably do some usability tests to see if that really worked for people. Or at least have a meeting about it. But I just happened to be in the right place at the right time, with the right programmer with the right access and skills. I got asked the question on what I thought it should do and everyone else gets to live with it for all time.

2021-02-12

Calling a .NET 5 (.NET Core) COM DLL from Microsoft Office (Excel, Word, Outlook, etc.)

I have finally got a .NET 5 DLL written in C# able to be called from Microsoft Office! This process actually works for any application to call the DLL through COM.This has been a bear to figure out. It is not easy, but it can be done. There are some mentions of the process on the web, but I have seen no examples. I am going to post the code on GitHub with a sample project, and the full description over there.

So before launching into the process, here is my most basic recommendation. If possible, for the time being don't use .NET 5 or .NET Core at all. Use the .NET Framework 4.x, because it does much of the work for you. For my current project, that wasn't possible, because a library it needed to call was only going to be maintained on .NET 5, as it was also being called from at .NET 5 front end. This recommendation will likely change as the .NET core does the work of providing a type library in the comhost file they create in some future release.

But here is the basic process: 1) Create a project with a class and interface. 2) Decorate them with appropriate attributes. 3) Add the appropriate method and the commands to create the correct registry entries to the project. 4) Add the appropriate settings to project file. 5) Build the DLL. 6) Create a parallel IDL file that describes the interface. 7) Compile it with the MIDL compiler. 8) Register the DLL. 9) In office, add a reference to the DLL.

There are various gotchas in this process. One of the things that is tricky is making sure that your DLL, the comhost wrapper, and the version of Microsoft Office you are calling it from all have the same bitness (32 bits or 64 bits).

So given all that, you can find the test project with more detailed documentation here: https://github.com/GregReddick/ComTestLibrary/tree/master/ComTestLibrary1

2021-01-24

Solving Mastermind

A question was posted online recently about the best strategy for winning the game of Mastermind. Mastermind is a game played between two players, a Code Maker and a Code Breaker. The Maker makes a code of colored pegs, and the Breaker has to guess the code. After each guess, the Maker gives feedback of how many of the pegs were the right color in the right place and how many are the right color in the wrong place, indicated by black and white pegs in the board. The Breaker then makes another guess.

The parameters of the game are how many possible colors there are, how many pegs are in the code, and whether the same color is allowed to be repeated in the code, as in (4 of 6, repeats).

Donald Knuth wrote a paper on optimal play for the Breaker and showed that in four pegs in the code of six possible colors with repeats, it can be solved in no more than five tries. Donald Knuth is a deity of Computer Science, having written The Art of Computer Programming. I wrote a program to implement Knuth's algorithm in C#. It also creates a table at the end of how to make perfect play.

In my program, I replace colors with numerals since the colors are arbitrary. I have placed the code on GitHub. You can try the suggested algorithm on this site.

The program uses a MinMax algorithm, which finds the code that will reduce the number of possible remaining codes on each play. Because of the way it works, sometimes it will make a code that might not actually solve it on the next play, but instead guarantee that it solves it in the least number of tries. There are some other algorithms that will solve it in a smaller average number of tries, but possibly having a larger maximum.

2020-06-17

Creating a Break Timer in PowerPoint using VBA

When I teach live classes, I use the SysInternals Zoomit application, which has a break timer built in. However, I was teaching a online class, and Zoomit did not seem to get along with WebEx. I decided to write a break timer directly into the PowerPoint slides I was using.

The first step is to create a slide at the end of the presentation that looks like this:


In other words, it is a standard slide with a title at the top and bullet points section below. I centered both and removed the bullet, so it just had text on the time. The code below counts on this slide as being the last in the presentation.

Next I brought up the PowerPoint Visual Basic Editor. You can do this with Alt+F11. Insert a module with Insert > Module from the menu. In the module, add this VBA code:

Option Explicit

Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal Milliseconds As Long)
Private lngPreviousSlide As Long
Private boolEndBreak As Boolean

Public Sub BreakTimer()
    Dim dtmStart As Date
    Dim dtmEnd As Date
    Dim slidesCollection As slides
    Dim slideBreak As slide
    Dim lngCurrentSlide As Long
   
    dtmStart = Now
    dtmEnd = DateAdd("n", 10, dtmStart)
   
    Set slidesCollection = Application.ActivePresentation.slides
    Set slideBreak = slidesCollection(slidesCollection.Count)
   
    lngCurrentSlide = SlideShowWindows(1).View.slide.SlideIndex
    If lngCurrentSlide = slidesCollection.Count Then
        'On the break slide, end the break early
        boolEndBreak = True
    Else
        ' Go on break
        lngPreviousSlide = lngCurrentSlide
        boolEndBreak = False
        SlideShowWindows(1).View.GotoSlide slidesCollection.Count, msoTrue
        DoEvents
        Do Until (Now > dtmEnd) Or boolEndBreak
            slideBreak.Shapes(2).TextFrame.TextRange.Text = Format(dtmEnd - Now, "n:ss")
            Sleep 900
            DoEvents
        Loop
        SlideShowWindows(1).View.GotoSlide lngPreviousSlide, msoFalse
    End If
End Sub

When this code run, it remembers the current slide, changes the code to the last slide, and starts a 10 minute countdown (Change the 10 in the DateAdd function to another number to do a different number of minutes in your break).

I then went to the master slide (View > Slide Master) and added a small button in the lower right hand corner. To add a button, you need to have the Developer ribbon turned on. Use File > Options > Customize Ribbon and check the checkbox next to Developer in the dialog and press OK. Then switch to your Developer ribbon.

On the Developer ribbon, Click the Command Button icon, then draw the button on the master slide. Then click the Properties button on the ribbon. Set the name of the button to cmdBreak, and select a clock type image file in the Picture property by hitting the ... button on the right. Then double-click on the button you just created. This creates an Event Handler for the button. In the Event Handler, add this code:

Option Explicit

Private Sub cmdBreak_Click()
    Call BreakTimer
End Sub

Close the Master slide. Run your presentation. Whenever you want to call a break, click the button in the lower right of the current slide. It will jump to your break slide and start counting down. At the end of the break, it will jump back to the slide it was on. If you want to end the break early, on the break slide, click the break button and it will end it (the code is re-entrant, so it can be processing and the button is hit again, which executes it a second time while the first instance is still running).

2019-05-01

Visual Studio 2019 Community has CodeLens

I have been asking for many years in this blog that Visual Studio get CodeLens on the cheaper versions.of Visual Studio. CodeLens shows the number of references to piece of code immediately below the method first line, and quickly allows getting to those references. It is actually configurable, so it can show other information as well, but the reference count is the default.

When Microsoft first made CodeLens available, it was only available on the $12000 version of Visual Studio. It has finally made its way into the Community Edition as of the recent release of Visual Studio 2019. The Community Edition is the version available for free for very small companies, educational, and personal use.

Now if they would make Code Coverage available on the Community Edition, it would make me happy. Code Coverage allows seeing what code has been hit by test suites and where additional tests need to be written. There is the free AxoCover that does pretty well, but having the Microsoft version available would be better. This is my biggest missing feature in the Visual Studio that I use.

2019-01-30

How to Delete an Excessively Long Directory on NTFS

The current version of Windows has some throwbacks to the days of the DOS operating system. Back in the day, DOS had a limit on filenames that they could not be more than 260 or so characters long (there was a little fudging between the limit on directories and filenames, but let's just call it 260).

The current NTFS file system doesn't have that 260 character limit. However, many of the tools that talk to NTFS, like the Windows Explorer and the command line still do have the limit. So if you have a tool that doesn't have the limit, it can create a directory that you cannot delete from the Windows Explorer or the command line. Arg!

The solution is to make the entire directory path shorter than 260 characters, then you can delete the directory. Go to Windows explorer, and drill down into your excessively long directory path until you cannot go any deeper. Then drag that deepest directory you can reach and move it to be a subdirectory of the root (or somewhere much further up the directory tree if the name conflicts). Delete the directory path that you dragged from, which should now be short enough to delete. Then drill down in your new path from the root...you should be able to reach further down than you could before because the limit only applies from the root. Repeat again and again until you can get to the bottom of the tree.

As an additional note: The most common reason for the long directory name problem is that Windows has a bug where it creates a recursive reparsepoint for a directory called "Application Data". This puts the directory as a subdirectory of itself. This means that you can into this subdirectory forever. So if you use a tool like robocopy to copy the directory tree, it will drill down until it hits the NTFS limit on the directory name (much longer than 260) and keep copying the directory. Then you can't delete the directory it copied. To remove a reparsepoint, you can do the following commands from a command prompt:

cd "\users\myacct\appdata\local\application data"
fsutil reparsepoint delete "application data"

2018-08-30

Using the New Features in the Latest Versions of C#

The current version of Visual Studio 2017 (15.8.2 the day this is posted) actually supports C# version 7.3. You can see the new features by looking at the C# feature list. However, by default, Visual Studio will use C# version 7.0. To use versions after 7.0, you will need to go to the project properties, select Build, then click the Advanced button. In the dialog is a setting for Language Version. Changing this to 7.3, for example, will enable the latest features.

You can use this same setting for turning off features. If you don't like the stuff they added to C# version 7, you can go back to 6, or even back to 3. They have been pretty good, however, at not screwing up the language with features added in later versions. I can't think of a feature where I went, "I wish they didn't put that in the language." I think lambda expressions are overused by a lot of people, but there are places where they are appropriate. I also use "var" as little as possible, but there are places where var is necessary and useful. The usage of these features is a coding style issue, not a problem with the language itself.

You can see the features that might be coming in future versions of C# at this page. The biggest feature that is being discussed is non-nullable reference types. With these, you can specify that a specific reference type cannot ever be null. This will likely change how a lot of C# code gets written.

2018-06-10

Using UserControls with Caliburn.Micro

It is common to want to create a reusable UserControl, to be placed into a WPF (Windows Presentation Foundation) screen. This can be done one of two ways:
  • ViewModel First
  • View First
The techniques below will show how to do both of these schemes using Caliburn.Micro to perform the plumbing to connect them up. It took me quite a bit of research to figure out how to make these happen, particularly the View first, scheme. Both of these techniques can be used to create a UserControl in a Window that was itself generated using the other technique. For example, a window that was created using the ViewModel First scheme can include a UserControl that is created using the View First scheme.

In the example code below, the main window View is called  MainWindowView and has a ViewModel called MainWindowViewModel. The ViewModel First control has a ViewModel called ViewModelFirstTestControlViewModel, which is displayed with the View called ViewModelFirstTestControlView. The View First control has a View called ViewFirstTestControlView and has a ViewModel called ViewFirstTestControlViewModel.

The ViewModel first scheme places a ContentControl into the MainWindowView, with a x:Name attribute. For example:

<ContentControl
 x:Name="ViewModelFirstTestControlViewModel" />

The MainWindowViewModel then has this code:

namespace TestSystem.ViewModels
{
 using Caliburn.Micro;
 
 /// <summary>A ViewModel for the main window.</summary>
 /// <seealso cref="T:Caliburn.Micro.PropertyChangedBase"/>
 public class MainWindowViewModel : PropertyChangedBase
 {
  /// <summary>Initializes a new instance of the <see cref="MainWindowViewModel"/> class.</summary>
  public MainWindowViewModel()
  {
   this.ViewModelFirstTestControlViewModel = new ViewModelFirstTestControlViewModel("ViewModel First Set Content");
  }
 
  /// <summary>Gets the ViewModelFirst test control view model.</summary>
  /// <value>The ViewModelFirst test control view model.</value>
  public ViewModelFirstTestControlViewModel ViewModelFirstTestControlViewModel
  {
   get;
   private set;
  }
 }
}

So the constructor of the MainWindowViewModel instantiates the ViewModel of the UserControl, passing any arguments to initialize the values in the control. A property with the same name as the x:Name of the ContentControl exposes that ViewModel to the ContentControl. When the ContentControl needs to display the ViewModel, Caliburn.Micro finds the appropriate View and displays that as the content of the ContentControl.

The content of the actual UserControl View in this example looks like this, but could be virtually anything you want:


<UserControl
 x:Class="TestSystem.Views.ViewModelFirstTestControlView"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
 <StackPanel
  <TextBlock
   Text="{Binding Path=Caption}" />
 </StackPanel>
</UserControl>

The ViewModel for the control in this example look like this:

namespace TestSystem.ViewModels
{
 using Caliburn.Micro;
 
 /// <summary>A ViewModel for the ViewModelFirst test control. This class cannot be inherited.</summary>
 /// <seealso cref="T:Caliburn.Micro.PropertyChangedBase"/>
 public sealed class ViewModelFirstTestControlViewModel : PropertyChangedBase
 {
  /// <summary>The caption.</summary>
  private string caption = "Default ViewModel first caption";
 
  /// <summary>
  /// Initializes a new instance of the <see cref="ViewModelFirstTestControlViewModel"/> class.</summary>
  public ViewModelFirstTestControlViewModel()
  {
  }
 
  /// <summary>
  /// Initializes a new instance of the <see cref="ViewModelFirstTestControlViewModel"/> class.</summary>
  /// <param name="caption">The caption.</param>
  public ViewModelFirstTestControlViewModel(string caption)
  {
   this.caption = caption;
  }
 
  /// <summary>Gets or sets the caption.</summary>
  /// <value>The caption.</value>
  public string Caption
  {
   get
   {
    return this.caption;
   }
 
   set
   {
    if (value != this.caption)
    {
     this.caption = value;
     this.NotifyOfPropertyChange(() => this.Caption);
    }
   }
  }
 }
}

The main point about the code is that there is a constructor that takes any initial values to be set for the control. You may not actually need the default constructor.

Now, let's examine how to do virtually the same thing, but do it View First. In the MainWindowView, there is this code to place the control into the View:

<ctl:ViewFirstTestControlView
 cm:Bind.Model="TestSystem.ViewModels.ViewFirstTestControlViewModel"
 Caption="View First Set Content" />

For this Xaml to work, two namespace must be defined:

 xmlns:cm="http://www.caliburnproject.org"
 xmlns:ctl="clr-namespace:TestSystem.Views" 

The cm namespace comes from the Caliburn.Micro project. Many people use "cal" instead of "cm", but I've got a namespace for "calendrics" in some of  my projects, so use cm instead. The "ctl" namespace is where your views reside.

The cm:Bind.Model specifies the ViewModel for the control. The Caption passes in the initial value of the control.

This retrieves the View for the control. The View looks very similar the the ViewModel First View, with some additions:

<UserControl
 x:Class="TestSystem.Views.ViewFirstTestControlView"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:vm="clr-namespace:TestSystem.ViewModels"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
 <UserControl.Resources>
  <vm:ViewFirstTestControlViewModel
   x:Key="ViewFirstTestControlViewModel" />
 </UserControl.Resources>
 <StackPanel
  x:Name="root"
  DataContext="{StaticResource ViewFirstTestControlViewModel}">
  <TextBlock
   Text="{Binding Path=Caption}" />
 </StackPanel>
</UserControl>


The additions specify the ViewModel for the control as a resource and binds the DataContext of the first child control to that ViewModel. However, with View First, the thing you can't avoid is having code behind. The code behind for the UserControl looks like this:

namespace TestSystem.Views
{
 using System.Windows.Controls;
 
 using TestSystem.ViewModels;
 
 /// <summary>A view first test control view.</summary>
 /// <seealso cref="T:System.Windows.Controls.UserControl"/>
 /// <seealso cref="T:System.Windows.Markup.IComponentConnector"/>
 public partial class ViewFirstTestControlView : UserControl
 {
  /// <summary>The view model.</summary>
  private ViewFirstTestControlViewModel vm;
 
  /// <summary>Initializes a new instance of the <see cref="ViewFirstTestControlView"/> class.</summary>
  public ViewFirstTestControlView()
  {
   this.InitializeComponent();
   this.vm = (ViewFirstTestControlViewModel)this.root.DataContext;
  }
 
  /// <summary>Gets or sets the caption.</summary>
  /// <value>The caption.</value>
  public string Caption
  {
   get
   {
    return this.vm.Caption;
   }
 
   set
   {
    this.vm.Caption = value;
   }
  }
 }
}

The code behind does the InitializeComponent(), then sets the ViewModel to the DataContext that was set in the view. This, in turn, is used to have the property of the control talk to the ViewModel. The ViewModel of the control looks like this:

namespace TestSystem.ViewModels
{
 using Caliburn.Micro;
 
 /// <summary>A ViewModel for the ViewFirst test control. This class cannot be inherited.</summary>
 /// <seealso cref="T:Caliburn.Micro.PropertyChangedBase"/>
 public sealed class ViewFirstTestControlViewModel : PropertyChangedBase
 {
  /// <summary>The text.</summary>
  private string caption = "Default View first caption";
 
  /// <summary>Gets or sets the text.</summary>
  /// <value>The text.</value>
  public string Caption
  {
   get
   {
    return this.caption;
   }
 
   set
   {
    if (value != this.caption)
    {
     this.caption = value;
     this.NotifyOfPropertyChange(() => this.Caption);
    }
   }
  }
 }
}

This is almost the same as the ViewModel of the ViewModel First control, except it does not need the constructors, since the property is changed from the MainWindowView. (It has a default constructor that does nothing.)

A zip file for the entire project is found here. Included are all the files, including the Caliburn.Micro bootstrapper that sets up the files.

If you know of more efficient ways of doing any of the things I've described, please let me know in the comments.