Wednesday, June 22, 2011

Predicates and VB.NET

When I talk to people about .NET and that I like to code with VB.NET I always have to endure the hazing that comes along with it. One of the points that C# developers always seem to bring up is that VB.NET sucks when it comes to predicates.

I suppose it's hard to show or explain out of context, but I'll give it a shot anyway.

Let's say you have a dictionary of string,string files as a manifest. The key is the full path of the file and the value is the name of the file or some meta data about it. The dictionary is populated by an initial scan of the file system and then updated as events fire from a filesystemwatcher.

Now, you rename a directory - and your file manifest needs to be updated. Here's how you could do that with a predicate using the filesystemwatcher.renamed event:




Sub fileRenamed(ByVal source As Object, ByVal e As RenamedEventArgs)
Try
If e.FullPath.Contains("$RECYCLE") Or e.FullPath.Contains("System Volume") Or e.FullPath.Contains("DfsrPrivate") Then
Exit Sub
End If
'A directory was renamed, we need to modify all keys and values with the old path to the new one - since they don't exist under the old path anymore.

If Directory.Exists(e.FullPath) Then
Dim oldKeys As IEnumerable(Of KeyValuePair(Of String, String)) = fileDict.Where(Function(grepDict) Regex.Match(grepDict.Key, e.OldFullPath).Success).ToList

For Each s As KeyValuePair(Of String, String) In oldKeys
'Remove the old key.
fileDict.Remove(s.Key)

'Add the new key with the updated path.
fileDict.Add(Regex.Replace(s.Key, e.OldFullPath, e.FullPath), Regex.Replace(s.Value, oldMetaData, newMetaData))
Next
Else
fileDict.Remove(e.OldFullPath)
fileDict.Add(e.FullPath, fileNameOrMetaData)
End If

Catch ex As Exception
EventLog.WriteEntry(My.Application.Info.ToString, ex.Message)
End Try

End Sub

No comments:

Post a Comment