If you are interested in using LINQ to read Xml instead of the older way of the XmlDocument and SelectNodes, the code below is a pretty good example. The code takes in the ISO standard file for country names and codes (see sample below) and turn it into a list of Country objects for use in an application including ComboBoxes.

<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>

<ISO_3166-1_List_en xml:lang="en">

   <ISO_3166-1_Entry>

      <ISO_3166-1_Country_name>AFGHANISTAN</ISO_3166-1_Country_name>

      <ISO_3166-1_Alpha-2_Code_element>AF</ISO_3166-1_Alpha-2_Code_element>

   </ISO_3166-1_Entry>

   <ISO_3166-1_Entry>

      <ISO_3166-1_Country_name>ÅLAND ISLANDS</ISO_3166-1_Country_name>

      <ISO_3166-1_Alpha-2_Code_element>AX</ISO_3166-1_Alpha-2_Code_element>

   </ISO_3166-1_Entry>

</ISO_3166-1_List_en>

Before

Here is the original code that has been in use for a few years. It uses the "easy" way of loading and selecting nodes using the XmlDocument object.

Dim countriesXml As New System.Xml.XmlDocument

countriesXml.LoadXml(My.Resources.CountriesXML)

 

Dim list As New System.Collections.Generic.List(Of Country)

 

For Each country As System.Xml.XmlNode In countriesXml.SelectNodes("//ISO_3166-1_Entry")

 

   Dim tempCountry As New Country

 

   tempCountry.Name = country.SelectSingleNode("ISO_3166-1_Country_name").InnerText

   tempCountry.Code = country.SelectSingleNode("ISO_3166-1_Alpha-2_Code_element").InnerText

 

   list.Add(tempCountry)

 

Next

 

After

This code uses LINQ and the new XElement to make it easy to load the xml from the assemblies resources.

Dim reader = XElement.Parse(My.Resources.Countries)

 

Dim list As New System.Collections.Generic.List(Of Country)

 

Dim data = From c In reader.Elements(XName.Get("ISO_3166-1_Entry")) _

           Order By c.Element(XName.Get("ISO_3166-1_Country_name")).Value _

           Select New Country With {.Name = c.Element(XName.Get("ISO_3166-1_Country_name")).Value, _

                            .Code = c.Element(XName.Get("ISO_3166-1_Alpha-2_Code_element")).Value.ToUpper}

 

As you can see this is much cleaner, fewer lines of code and actually faster (1 millisecond). Also you can see in the Select line that I am actually filling the Country object during the query... pretty cool!

Tip Submitted By: David McCarter

This code can be found in the open source dotNetTips.Utility assembly


 
Categories: LINQ | VB.NET | XML

If you are coming to the San Diego .NET Developers Group meeting tonight I hope you will be their early for my talk titled "What’s New In VS 2008 SP1". Lots of new additions to this SP, not just bug fixes. Below is a link to the presentation.

VS2008Sp1.pdf (715.88 KB)
 
Categories: .NET | ADO.NET | AJAX | ASP.NET | Csharp | dotNetDave | Entity Framework | LINQ | MVC | Silverlight | VB.NET | VS.NET | WCF | WinForms | WPF

September 2, 2008
@ 11:36 AM
If you live in the San Diego area, dotNetDave (a.k.a. David McCarter) will be teaching a 6 week Fundamentals of the .NET Framework course at the University of California, San Diego Extension beginning on Thursday 9/24/2008 from 5:30pm to 9:15pm. For more information and to enroll, please click here.
 
Categories: .NET | C# | dotNetDave | VB.NET

September 1, 2008
@ 11:47 AM

I hope everyone in California is planning to attend this years Central Coast Code Camp up in San Luis Obispo on 9/27 - 6/28. It's always a great time and lots of free training! I will also be selling a limited number of my latest book "David McCarter's .NET Coding Standards" at my sessions for $11, cheaper than the web site (no tax and shipping), please bring exact change.

I will be presenting the following sessions and I hope you will attend.

dotNetDave's .NET Utility Assembly (My First CodePlex Project)

 dotNetDaves .NET Utility Assembly.pdf (704.86 KB)

CodePlex site: http://www.codeplex.com/dotNetTips

Building Rich & Interactive Web Applications with ASP.NET AJAX Part 1

zip_icon.gif Building Rich & Interactive Web Applications with ASP.NET AJAX Part 1 - 20081.zip (1.05 MB)

Building Rich & Interactive Web Applications with ASP.NET AJAX Part 2 

zip_icon.gif Building Rich & Interactive Web Applications with ASP.NET AJAX Part 2 - 200812.zip (1.49 MB)

Why You Need .NET Coding Standards (2008)

Why You Need .NET Coding Standards-2008.pdf (941.06 KB)

Photos

Pictures: http://www.flickr.com/photos/davidmccarter/tags/centralcoastcodecamp/

Blog Post about 2007 Code Camp: http://blog.davidmccarter.net/2007/09/23/ThingsIveLearnedThisWeek.aspx


 
Categories: .NET | AJAX | ASP.NET | C# | Code Camp | Defensive Programming | Development | dotNetDave | VB.NET

August 15, 2008
@ 01:20 PM

Do you want to retrieve all the Exceptions, including the inner Exceptions when an Exception is thrown for logging purposes? Since they are not enumerable, I wrote a block of recursive code below that will do the trick.

    1 Function RetrieveAllExceptions(ByVal ex As Exception) As ObjectModel.ReadOnlyCollection(Of Exception)

    2    Dim exceptions As New Generic.List(Of Exception)

    3 

    4    If ex IsNot Nothing Then

    5       exceptions.Add(ex)

    6 

    7       If ex.InnerException IsNot Nothing Then

    8          exceptions.AddRange(RetrieveAllExceptions(ex.InnerException))

    9       End If

   10    End If

   11 

   12    Return New ObjectModel.ReadOnlyCollection(Of Exception)(exceptions)

   13 

   14 End Function

Tip Submitted By: David McCarter


 
Categories: Development | VB.NET

August 8, 2008
@ 09:00 AM

The link below takes you to the Microsoft Express products like Visual Basic Express 2008 and SQL Server Express 2008.

http://www.microsoft.com/express/


 
Categories: Csharp | Link | SQL Server | VB.NET

Getting command line parameters or seeing if they are present is not as easy as you would think. I whipped up some code to make this flexible and easy.

   Private Const ParameterPrefix As Char = "/"c
       
   Private Function GetCommandLineArgument(ByVal parameter As String) As String
      Dim paramValue = String.Empty
      For Each tempValue As String In System.Environment.GetCommandLineArgs
         If tempValue.Contains(ParameterPrefix + parameter + "=") Then
            paramValue = tempValue.Split(Char.Parse("="))(1).ToString().Trim()
            Exit For
         End If
      Next
      Return paramValue
   End Function
   Private Function CommandLineArgumentExists(ByVal parameter As String) As Boolean
      Dim exists = False
      For Each tempValue As String In System.Environment.GetCommandLineArgs
         If tempValue.Contains(ParameterPrefix + parameter) Then
            exists = True
            Exit For
         End If
      Next
      Return exists
   End Function
   Private Function GetCommandLineArgument(ByVal parameter As String, ByVal prefix As String) As String
      Dim paramValue = String.Empty
      For Each tempValue As String In System.Environment.GetCommandLineArgs
         If tempValue.Contains(prefix + parameter + "=") Then
            paramValue = tempValue.Split(Char.Parse("="))(1).ToString().Trim()
            Exit For
         End If
      Next
      Return paramValue
   End Function
   Private Function CommandLineArgumentExists(ByVal parameter As String, ByVal prefix As String) As Boolean
      Dim exists = False
      For Each tempValue As String In System.Environment.GetCommandLineArgs
         If tempValue.Contains(prefix + parameter) Then
            exists = True
            Exit For
         End If
      Next
      Return exists
   End Function

Usage:

 Debug.WriteLine(CommandLineArgumentExists("source"))
 Debug.WriteLine(GetCommandLineArgument("source", "-"))

Tip Submitted By: David McCarter


 
Categories: Development | VB.NET

Here is some easy, generic code to serialize your objects to and from JSON:

Public Shared Function JsonEncode(ByVal input As Object) As String
  Dim serilizer = New DataContractJsonSerializer(input.GetType)
  Using ms = New MemoryStream()
    serilizer.WriteObject(ms, input)
    Return Encoding.Default.GetString(ms.ToArray())
  End Using
End Function
Public Shared Function JsonDecode(Of T)(ByVal input As String) As T
  Using ms = New MemoryStream(Encoding.Unicode.GetBytes(input))
    Dim serilizer = New DataContractJsonSerializer(GetType(T))
    Return DirectCast(serilizer.ReadObject(ms), T)
  End Using
End Function
public static string JsonEncode(object input)
{
var serilizer = new DataContractJsonSerializer(input.GetType());
  using (var ms = new MemoryStream())
{
serilizer.WriteObject(ms, input);
    return Encoding.Default.GetString(ms.ToArray());
}
}
public static T JsonDecode<T>(string input)
{
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(input)))
{
var serilizer = new DataContractJsonSerializer(typeof(T));
    return (T)serilizer.ReadObject(ms);
}
}

Tip Submitted By: David McCarter


 
Categories: ASP.NET | C# | JavaScript | VB.NET | Web Services | Generics

June 30, 2008
@ 02:33 PM

I recently started a new job that uses C#. I have been trying for two frickin hours to get Trace Listeners working in an application here with no luck at all. So to test that I have the web.config setup correctly, I added the following:

var log = new Microsoft.VisualBasic.Logging.Log();
log.WriteEntry("VB Log");

Bam, it works! Dang I LOVE VB.NET! Now I'm going to go ask my boss if I can use the VisualBasic.Logging class in our C# application ;-)

David McCarter


 
Categories: ASP.NET | VB.NET

June 1, 2008
@ 08:55 AM
Code

I hope everyone in southern California is planning to attend this years SoCal Code Camp up at University California San Diego on 6/28 - 6/29. It's always a great time and lots of free training! I will also be selling a limited number of my latest book "David McCarter's .NET Coding Standards" at my sessions for $11, cheaper than the web site (no tax and shipping), please bring exact change.

I will be presenting the following sessions and I hope you will attend.

dotNetDave's .NET Utility Assembly (My First CodePlex Project)

10:15 AM - Sunday, June 29, 2008 - Location: 141

zip_icon.gif dotNetDaves .NET Utility Assembly1.zip (1.11 MB)

CodePlex site: http://www.codeplex.com/dotNetTipsUtility

Building Rich & Interactive Web Applications with ASP.NET AJAX Part 1

8:45 AM - Saturday, June 28, 2008 - Location: 129

zip_icon.gif Building Rich & Interactive Web Applications with ASP.NET AJAX.zip (1.83 MB)

Building Rich & Interactive Web Applications with ASP.NET AJAX Part 2 

12:15 PM - Saturday, June 28, 2008 - Location: 129

zip_icon.gif Building Rich & Interactive Web Applications with ASP.NET AJAX Part 2 - 20081.zip (1.82 MB)

Why You Need .NET Coding Standards (2008)

1:45 PM - Sunday, June 29, 2008 - Location: 127

zip_icon.gif Why You Need .NET Coding Standards-20081.zip (2.86 MB)

Pictures and Video

Fullerton Code Camp - JAN 2008

Pictures from This Years Code Camp:

Pictures from past SoCal Code Camps:

Video from past Code Camps:

 


 
Categories: .NET | AJAX | ASP.NET | Code Camp | Csharp | Defensive Programming | Development | dotNetDave | News | VB.NET

April 14, 2008
@ 09:34 AM
If you live in the San Diego area, dotNetDave (a.k.a. David McCarter) will be teaching a 6 week Fundamentals of the .NET Framework course at the University of California, San Diego Extension beginning on Thursday 5/14/2008 from 5:30pm to 10:00pm. For more information and to enroll, please click here.


 
Categories: .NET | Csharp | dotNetDave | VB.NET

February 27, 2008
@ 12:00 PM

Today I released the first public version of my dotNetTips.com Utility assembly. This is an open source .NET 2.0 utility assembly that contains useful common code that anyone can use in just about any project. Helper classes include Active Directory, Validation, IIS, File IO, Security, Computer Info, Web, XML and more. Other classes include a better TextBox and ComboBox, sending e-mail, encryption and more.

To download go to:

http://www.codeplex.com/dotNetTipsUtility


 
Categories: .NET | VB.NET

January 18, 2008
@ 08:25 PM

I hope everyone in southern California is planning to attend this years SoCal Code Camp up at Cal State Fullerton on 1/26 -1/27. It's always a great time and lots of free training! My fav southern California band Killola will be playing again at the Geek dinner so make sure you arrive early on Saturday to grab one of the limited number of tickets available.

167020688v3_240x240_Front_Color-Black.jpg

I will be doing the following sessions and I hope you will attend.

dotNetDave's .NET Utility Assembly (My First CodePlex Project)

zip_icon.gif dotNetDaves .NET Utility Assembly.zip (614.15 KB)

Building Rich & Interactive Web Applications with ASP.NET AJAX Part 1

zip_icon.gif Building Rich & Interactive Web Applications with ASP.NET AJAX Part 1 - 2008.zip (1.39 MB)

Building Rich & Interactive Web Applications with ASP.NET AJAX Part 2 

zip_icon.gif Building Rich & Interactive Web Applications with ASP.NET AJAX Part 2 - 2008.zip (1.11 MB)

Why You Need .NET Coding Standards (2008)

zip_icon.gif Why You Need .NET Coding Standards-2008.zip (1.71 MB)

Pictures and Video

Fullerton Code Camp - JAN 2008

Pictures from This Years Code Camp:

Pictures from past SoCal Code Camps:

Video from past Code Camps:

 

 


 
Categories: .NET | AJAX | ASP.NET | Code Camp | Csharp | Development | dotNetDave | JavaScript | News | VB.NET

Often, it's a good idea to make sure the user trying to access the file has permissions to it before performing an operation like read, write or delete. Below is code that makes this pretty easy.

  Sub DemandFileReadPermission(ByVal fileName As String)

    If System.IO.File.Exists(fileName) Then

      Dim filePermission As New System.Security.Permissions.FileIOPermission(System.Security.Permissions.FileIOPermissionAccess.Read, System.Security.AccessControl.AccessControlActions.View, fileName)

      filePermission.Demand()

    End If

  End Sub

 

  Sub DemandFileWritePermission(ByVal fileName As String)

    If System.IO.File.Exists(fileName) Then

      Dim destinationFilePermission As New System.Security.Permissions.FileIOPermission(System.Security.Permissions.FileIOPermissionAccess.Write, System.Security.AccessControl.AccessControlActions.Change, fileName)

      destinationFilePermission.Demand()

    End If

  End Sub

One warning though... performing a permission .Demand takes time. In a quick test on my machine it was a pretty consistent 10 milliseconds. So you might not want to do this all of the time.

Tip by: David McCarter
 
Categories: VB.NET

dotdetdave-head-50.jpgIf you live in the San Diego area, dotNetDave (a.k.a. David McCarter) will be teaching a 6 week Building Rich & Interactive Web Applications with ASP.NET AJAX course at the University of California, San Diego Extension beginning on Thursday 2/21/2008 from 5:30pm to 10:00pm. For more information and to enroll, please click here.


 
Categories: .NET | AJAX | ASP.NET | Csharp | dotNetDave | JavaScript | VB.NET

December 15, 2007
@ 04:15 PM

If you need to convert a Bitmap to an Byte array, here is how you do it.

  Public Shared Function ConvertToByteArray(ByVal value As Bitmap) As Byte()

      Dim bitmapBytes As Byte()

 

      Using stream As New System.IO.MemoryStream

 

        value.Save(stream, value.RawFormat)

        bitmapBytes = stream.ToArray

 

      End Using

 

      Return bitmapBytes

 

  End Function

Tip By: David McCarter

This code can be found in the open source dotNetTips.Utility assembly


 
Categories: VB.NET

There are many times when I need to convert an array to a delimited string. Here is an easy way to do it using generics in .NET 2.0.

  Public Shared Function ConvertArrayToString(Of arrayType As {IEnumerable})(ByVal array As arrayType(), ByVal separator As Char) As String

 

      If Not IsValidArray(array) Then

        Throw New ArgumentNullException("array")

      End If

 

      If IsNothing(separator) Then

        Throw New ArgumentNullException("separator")

      End If

 

      Dim result As New System.Text.StringBuilder

 

      For Each arrayItem As arrayType In array

        If result.Length > 0 Then

          result.Append(separator)

        End If

 

        result.Append(arrayItem.ToString)

 

      Next

 

      Return result.ToString

 

  End Function

Tips By: David McCarter

This code can be found in the open source dotNetTips.Utility assembly


 
Categories: VB.NET

December 14, 2007
@ 12:44 PM

.NET still does not expose the drive serial number via the framework. For that you will need to use WMI. Here is the code.

Shared Function GetDriveSerialNumber(ByVal drive As String) As String

    Dim driveSerial As String = String.Empty

 

    'No matter what is sent in, get just the drive letter

    Dim driveFixed As String = System.IO.Path.GetPathRoot(drive)

    driveFixed = Replace(driveFixed, "\", String.Empty)

 

    'Perform Query

    Using querySearch As New ManagementObjectSearcher("SELECT VolumeSerialNumber FROM Win32_LogicalDisk Where Name = '" & driveFixed & "'")

      Using queryCollection As ManagementObjectCollection = querySearch.Get()

        Dim moItem As ManagementObject

        For Each moItem In queryCollection

          driveSerial = CStr(moItem.Item("VolumeSerialNumber"))

          Exit For

        Next

      End Using

    End Using

 

    Return driveSerial

 

End Function

You will also need to reference System.Management in your project.

Tips By: David McCarter

This code can be found in the open source dotNetTips.Utility assembly


 
Categories: VB.NET

December 14, 2007
@ 12:33 PM

Here is some simple code to validate that an array is valid. Before trying to use an array, you should always validate it with this code first.

  Public Shared Function IsValidArray(ByVal array As Array) As Boolean

      Dim valid As Boolean = False

 

      If array Is Nothing Then

        Throw New ArgumentNullException("array")

      End If

 

      If (array IsNot Nothing) AndAlso (array.Length > 0) Then

        valid = True

      End If

 

      Return valid

 

  End Function

Tip By: David McCater

This code can be found in the open source dotNetTips.Utility assembly


 
Categories: Defensive Programming | VB.NET

When data binding to a DropDownList control in ASP.NET, there are in many cases when you want the first selection of the control to be blank or say something like "<please select value>". In part one of this tip (back in 2003), I wrote that you could just add an empty row to the DataSet. In VS 2005 and the new way of data binding that I usually do to web services, this is more difficult. So here is another solution just using code in your ASP.NET code.

 Protected Sub DropDownList_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyControl1.DataBound, MyControl2.DataBound
      DirectCast(sender, DropDownList).Items.Insert(0, String.Empty)
 End Sub

The Insert method must be called after the DropDownList has been data bound.

Tip Submitted By: David McCarter


 
Categories: ASP.NET | VB.NET

November 15, 2007
@ 03:01 PM

Visual Basic Beer? Well not really, but we can only hope. Don't look for this in your local store unless you are in Australia.

VB Beer


 
Categories: Geek Humor | VB | VB.NET

September 20, 2007
@ 12:12 PM

If you need to convert RTF to text, here is a simple way of doing it:

    Public Shared Function ConvertRtfToText(ByVal input As String) As String
      Dim returnValue As String = String.Empty
      Using converter As New System.Windows.Forms.RichTextBox()
        converter.Rtf = input
        returnValue = converter.Text
      End Using
      Return returnValue
    End Function

Tip Submitted By: David McCarter

This code can be found in the open source dotNetTips.Utility assembly


 
Categories: VB.NET | WinForms

David McCarter's .NET Coding StandardThe second edition of this book (formerly VSDN Tips & Tricks .NET Coding Standards), is a consolidation of many of the .NET coding standards available today in one easy to read and understand book. It will guide any level of programmer or development department to greater productivity by providing the tools needed to write consistent, maintainable code.

The core of the book focuses on naming standards, how to order elements in classes, declaring methods, properties and much, much more. Code tips are even included to help you write better, error free applications. All code examples are shown in C# and VB.NET. I use this book just about
every day and I hope you will too.
-David McCarter

"David McCarter once again demonstrates his knack for pulling best practices into one cohesive unit with his new book. This book includes everything from how to set up your project to how to declare variables to how to use exception handling. It is a great place to start to build your own set of coding standards."
- Deborah Kurata 5/5/05

To order, go to: http://www.cafepress.com/geekmusicart.165478704


 
Categories: .NET | Books | Development | dotNetDave | News | VB.NET | Csharp

Refactor! is freely available to all Visual Basic .NET 2005 developers and offers a comprehensive suite of tools that enable you and your team to simplify and shape complex code - making it easier to read and less costly to maintain.

Download by going to: http://www.devexpress.com/Products/NET/IDETools/VBRefactor/


 
Categories: dotNetDave | Link | News | VB.NET

Line and Shape controls, PrintForm component, and Printer Compatibility Library

Microsoft Visual Basic 2005 Power Packs 2.0 includes a new set of Line and Shape controls and updated versions of the two previously released Visual Basic 2005 Power Packs, the PrintForm Component and the Printer Compatibility Library. All three are now included in a single assembly making them even easier to use and redistribute with your application.
 

 
Categories: Link | News | VB.NET

August 9, 2007
@ 12:03 PM

San Luis Obispo will be holding a code camp on September 22nd, 2007. I will be attending and presenting. For more info go to: http://www.centralcoastcodecamp.com/

Articles/News:

http://www.sanluisobispo.com/business/story/134783.html

Code Camp on KCOY

My sessions will be:

Building Rich & Interactive Web Applications with ASP.NET AJAX

Presentation: AjaxSession091807.zip (875.6 KB)

Code Example: AjaxExample.zip (703.12 KB)

Why You Need .NET Coding Standards

Presentation: StandardsSession.zip (1.6 MB)

Pictures from the event: http://www.flickr.com/photos/davidmccarter/tags/cccc/


 
Categories: AJAX | Csharp | Code Camp | Development | dotNetDave | News | VB.NET

August 9, 2007
@ 12:01 PM

Phoenix will be holding another code camp on September 15th, 2007. I will be attending and presenting. For more info go to: http://desertcodecamp.com/

My sessions will be:

Building Rich & Interactive Web Applications with ASP.NET AJAX

Presentation: AjaxSession.zip (1023.53 KB)

Code Example: AjaxExample.zip (703.12 KB)

Why You Need .NET Coding Standards

Presentation: StandardsSession.zip (1.6 MB)

 


 
Categories: AJAX | Csharp | Code Camp | Development | dotNetDave | News | VB.NET

I came up with some generic methods to do the job:

Public Shared Function DeserializeXMLToObject(ByVal input As String, ByVal type As System.Type) As Object
  Dim result As Object = Nothing
  Dim serializer As New XmlSerializer(type)
  Try
    result = serializer.Deserialize(New XmlTextReader(New StringReader(input)))
  Catch ex As Exception
    Debug.WriteLine(ex.Message)
  End Try
 
  Return result
End Function
Public Shared Function SerializeObjectToXML(ByVal input As Object, ByVal type As System.Type) As String
  Dim returnXML As String = String.Empty
  Dim serializer As New XmlSerializer(type)
  Dim writer As New StringWriter
  Try
    serializer.Serialize(New XmlTextWriter(writer), input)
    returnXML = writer.ToString()
  Catch ex As Exception
    Debug.WriteLine(ex.Message)
  Finally
    writer.Close()
  End Try
  Return returnXML
End Function

There are a few things to watch out for with the XmlSerilizer:

  • When deserializing, if the xml is not well-formed, then an exception will be thrown.
  • Also when deserializing, if there are empty elements like <author></author> or <author/> it seems to throw an exception. I am guessing that it expects empty elements to just not be in the xml. I have not found a way around this yet.
  • When you send in xml that does not match the object you are trying to deserialize, no exception is thrown, the object is basically empty.

When the XmlSerilizer serializes the object it comes out looking something like this:

<?xml version="1.0" encoding="utf-16"?>
<Books xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Book>
    <Title>Davi