I really liked the XML expressiveness of Visual Basic, let’s build a very simple MSN History Search Engine using LINQ and XML Literals in Visual Basic.
The best thing is those literals could be used in LINQ expressions. Remember the simple XML file that MSN stores as a history.
.@AttributeName : Accesses the attribute element in XML
: Accesses the element in XML
: Accesses the descendant name in XML
Modifying the XML content is very neat as well either using the LINQ expressions or even in loops.
In .NET Framework 2.0 VB has one more feature called MY namespaces. It is very nice to access some dynamic data available like application or forms information. It also contains some helper functions to do some common tasks. Now I also found it very handy in a Windows Forms application.
Get the history files from the location and operate the XLINQ query:
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) For Each file In My.Computer.FileSystem.GetFiles(dirLocation) ProcessFile(file) Next txtOutput.Text = sBuild.ToString() End Sub
The XLINQ query that does search magic for the messages is as follows :
Function ProcessFile(ByVal s As String) As Boolean If s.EndsWith("xml") Then Dim msn = XElement.Load(s) Dim q = From message In msn.<message> _ Where message.<text>.Value.Contains(txtSearch.Text) _ Select From = (message.<from>.@FriendlyName), Too = (message.<to>.@FriendlyNam), _ Message = message.<text>.Value For Each msgFound In q sBuild.AppendLine(msgFound.From + " says to " + msgFound.Too + _ " : " + msgFound.Message) Next End If End Function
What makes this different is the usage of literals. In C# that query would be longer than that.
In the sample message.
means that it will get the From element and get the friendlyname attribute from it.
It is basically like having the XML data in your hands but there is no need to parse it or access the elements using the classes provided rather this work is done by the compiler at the compile time.
In a couple lines of code we have a fully featured MSN history searching. Let me know if you still want the source code (although that is all about it) or even the executable in case you are not into programming.