After lots new coding and refactoring, dotNetTips.Utility 3.5 R2 is finally released! This assembly is much of the common code I have been writing for the past 9+ years all wrapped up in a nice package and easy to use. Here is just some of what is in the new version:

New Classes

  • EmailTraceListener - Send emails when trace events happen (I suggest using filters here)!
  • WebServiceTraceListener - Send trace events to a web service. I use this for logging events to a central back-end database!
  • Lots of new Extension methods and classes:
    • Color
    • DateTime
    • Decimal
    • Entity Framework
    • Image
    • Nullable
    • Xlement
    • And more!
  • GeoInfoHelper - Get geo location info based on IP address.
  • And lots more!
The documentation, binary and source code can be downloaded from CodePlex.

Coming soon... .NET 4.0 version!


 
November 13, 2009
@ 11:49 AM
I hope everyone in southern California is planning to attend this years SoCal Code Camp in San Diego on 11/21 - 11/22. It's always a great time and lots of free training!

I will be presenting the following sessions and I hope you will attend. Also, check out my new .NET discussion site called DotNet Army!

Building nTier Applications with Entity Framework Services

Learn how to build real world nTier applications with the new Entity Framework and related services introduced in .NET 3.5 SP1. With this new technology built into .NET, you can easily wrap an object model around your database and have all the data access automatically generated or use your own stored procedures and views. Then learn how to easily and securely expose your object model using WCF with just a few line of code using ADO.NET Data Services. The session will demonstrate how to create and consume these new technologies from the ground up. Lots of code!

Slides: Building nTier Applications with Entity Framework Services.pdf (2.88 MB)
Demo Code: EntityFramework.zip (859.84 KB)


dotNetDave's Favorite Programming Tools

This session will focus on my favorite Visual Studio add-ins and other tools that makes programming faster and easier. I will focus on tools that are either free or very affordable. Tool categories include Writing Better Code (easier, faster and correct the first time!), Code Helpers, Documentation (helper and creation), General Utilities and more. These tools are designed to impress your boss and get you home at a reasonable time. Packed full of demonstrations and very few PowerPoint slides! Licenses for some of the 3rd party products I will be demonstrating will be given away (over $1,100 worth), so be sure to attend and bring a business card!

Slides: dotNetDave's Favorite Programming Tools.pdf (1.82 MB)

Building Rich & Interactive Web Applications with ASP.NET AJAX

Learn how to build rich web application interfaces using ASP.NET AJAX and the ASP.NET AJAX Control Toolkit. This new technology makes programming JavaScript into your ASP.NET pages easy, increasing the power and functionality of your applications, reducing round trips to the server, and making it easy to consume web services for dynamic content. In this session you will be introduced to the new client and server controls for ASP.NET and Java Script to learn how to build a rich Web 2.0 experience for your users.

Slides: Building Rich & Interactive Web Applications with ASP.NET AJAX - 2009.pdf (2.36 MB)
Demo Code: AdventureWorksAjax.zip (803.65 KB)

Why You Need .NET Coding Standards (2009)

This session will guide any level of programmer to greater productivity by providing the information needed to write consistent, maintainable code. Learn about project setup, assembly layout, code style, defensive programming and much, much more. We will even go over some real in production code and see what the programmer did wrong in "What's Wrong With this Code?". Code tips are included to help you write better, error free applications. Lots of code examples in C# and VB.NET.

Slides: Why You Need .NET Coding Standards-2009.pdf (3.8 MB)
Demo Code: CodingStandards.zip (245.54 KB)


Pictures and Video

SoCal CodeCamp Fullerton - 2009

Pictures & Video from This Years Code Camp:

Pictures from past SoCal Code Camps:

Video from past Code Camps:


 
Categories: ADO.NET | AJAX | ASP.NET | Code Camp | Csharp | Defensive Programming | Development | dotNetDave | Entity Framework | Generics | LINQ | VB.NET | VS.NET | WCF

Please join me at the ASP.NET SIG of the San Diego .NET User Group December meeting to check out my session titled Why You Need .NET Coding Standards (2009). This session will guide any level of programmer to greater productivity by providing the information needed to write consistent, maintainable code. Learn about project setup, assembly layout, code style, defensive programming and much, much more. We will even go over some real in production code and see what the programmer did wrong in "What's Wrong With this Code?". Code tips are included to help you write better, error free applications. Lots of code examples in C# and VB.NET.

Food arrives at 6pm, Q&A and announcements start at 6:30 and my session starts at 7.

Hope to see you there!

Slides: Why You Need .NET Coding Standards-2009.pdf (3.8 MB)
Demo Code: CodingStandards.zip (245.54 KB)


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

Since many applications (like Smart Clients) use the internet to send/ retrieve data, it's a good thing to check to make sure the user has access to the internet before making your call. This will prevent connection exceptions. The code below first checks to make sure the user even has a network connection, then tries to ping up to three web sites to see if the ping is successful (of course you can change the sites to your linking or add more). The good thing that this code does that most other code I saw when researching this, is that it does not rely on an exception to determine that an internet connection is not available. Therefor it's much faster!

C#

public bool GetIsInternetConnectionAvailable()

{

   var success = false;

 

   if (NetworkInterface.GetIsNetworkAvailable() == false)

   {

      return success;

   }

 

   string[] sitesList = { "www.google.com", "www.microsoft.com", "www.mycompany.com" };

 

   try

   {

      using (var ping = new Ping())

      {

         foreach (var url in sitesList)

         {

            var reply = ping.Send(url, 300);

 

            if (reply.Status == IPStatus.Success)

            {

               success = true;

               break;

            }

         }

      }

   }

   catch (Exception ex)

   {

      Trace.WriteLine(ex.Message);

   }

 

   return success;

}


VB.NET

Public Function GetIsInternetConnectionAvailable() As Boolean

   Dim success = False

 

   If My.Computer.Network.IsAvailable = False Then

      Return success

   End If

 

   Dim sitesList As String() = {"www.google.com", "www.microsoft.com", "www.mycompany.com"}

 

   Try

      For Each url In sitesList

         If My.Computer.Network.Ping(url, 300) Then

            success = True

            Exit For

         End If

      Next

   Catch ex As Exception

      Trace.WriteLine(ex.Message)

   End Try

 

   Return success

End Function


Tip By: David McCarter


 
Categories: Csharp | Network | VB.NET

September 21, 2009
@ 03:05 PM
There might be times when you need the name of the method when logging Exceptions etc. The code below uses reflection and will also add the class name:

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

    2       Dim dir = String.Format("{0}.{1}", System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name, System.Reflection.MethodBase.GetCurrentMethod().Name)

The output would look like this:

>? dir
"Form1.Form1_Load"

If you also want the name of the application, use DeclaringType.FullName instead of just .Name.

Tip Submitted By: David McCarter


 
Categories: VB.NET

September 2, 2009
@ 10:22 AM
If you using an enum that uses bit flags, here is an easy way to check to see if one or more if the values are set.

VB

Public Shared Function CheckFlags(value As [Enum], flags As [Enum]) As Boolean
    If [Enum].GetUnderlyingType(value.[GetType]()) = GetType(ULong) Then
        Return (Convert.ToUInt64(value) And Convert.ToUInt64(flags)) <> 0
    Else
        Return (Convert.ToInt64(value) And Convert.ToInt64(flags)) <> 0
    End If
End Function

C#

public static bool CheckFlags(Enum value, Enum flags)
{
    if (Enum.GetUnderlyingType(value.GetType()) == typeof(ulong)) {
        return (Convert.ToUInt64(value) & Convert.ToUInt64(flags)) != 0;
    }
    else {
        return (Convert.ToInt64(value) & Convert.ToInt64(flags)) != 0;
    }
}


Usage

CheckFlags(value, EnumModes.Save | EnumModes.Store)
Tip By: David McCarter

 
Categories: Csharp | VB.NET

Entity Framework samples have not been released in VB.NET! Check out the blog link below.

Full Blog Entry: http://blogs.msdn.com/vbteam/archive/2009/06/18/vb-entity-framework-samples-now-available-lisa-feigenbaum.aspx


 
Categories: Entity Framework | Link | VB.NET

I hope everyone in Arizona and southern California is planning to attend this years Desert Code Camp on 6/13 and SoCal Code Camp in San Diego on 6/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 $12, cheaper than the web site (no tax and shipping), please bring exact change or check.

I will be presenting the following sessions and I hope you will attend. Also, check out my new .NET discussion site called DotNet Army!

Building nTier Applications with Entity Framework Services

Learn how to build real world nTier applications with the new Entity Framework and related services introduced in .NET 3.5 SP1. With this new technology built into .NET, you can easily wrap an object model around your database and have all the data access automatically generated or use your own stored procedures and views. Then learn how to easily and securely expose your object model using WCF with just a few line of code using ADO.NET Data Services. The session will demonstrate how to create and consume these new technologies from the ground up. Lots of code!

Slides: Building nTier Applications with Entity Framework Services.pdf (2.88 MB)
Demo Code: EntityFramework.zip (859.84 KB)


dotNetDave's Favorite Programming Tools

This session will focus on my favorite Visual Studio add-ins and other tools that makes programming faster and easier. I will focus on tools that are either free or very affordable. Tool categories include Writing Better Code (easier, faster and correct the first time!), Code Helpers, Documentation (helper and creation), General Utilities and more. These tools are designed to impress your boss and get you home at a reasonable time. Packed full of demonstrations and very few PowerPoint slides! Licenses for some of the 3rd party products I will be demonstrating will be given away, so be sure to attend and bring a business card!

Slides: dotNetDave's Favorite Programming Tools.pdf (1.82 MB)

Building Rich & Interactive Web Applications with ASP.NET AJAX

Learn how to build rich web application interfaces using ASP.NET AJAX and the ASP.NET AJAX Control Toolkit. This new technology makes programming JavaScript into your ASP.NET pages easy, increasing the power and functionality of your applications, reducing round trips to the server, and making it easy to consume web services for dynamic content. In this session you will be introduced to the new client and server controls for ASP.NET and Java Script to learn how to build a rich Web 2.0 experience for your users.

Slides: Building Rich & Interactive Web Applications with ASP.NET AJAX - 2009.pdf (2.36 MB)
Demo Code: AdventureWorksAjax.zip (803.65 KB)

Why You Need .NET Coding Standards (2009)

This session will guide any level of programmer to greater productivity by providing the information needed to write consistent, maintainable code. Learn about project setup, assembly layout, code style, defensive programming and much, much more. We will even go over some real in production code and see what the programmer did wrong in "What's Wrong With this Code?". Code tips are included to help you write better, error free applications. Lots of code examples in C# and VB.NET.

Slides: Why You Need .NET Coding Standards-2009.pdf (3.8 MB)
Demo Code: CodingStandards.zip (245.54 KB)


Pictures and Video

SoCal CodeCamp Fullerton - 2009

Pictures from This Years Code Camp:

Pictures from past SoCal Code Camps:

Video from past Code Camps:


 
Categories: .NET | ADO.NET | AJAX | ASP.NET | C# | Code Camp | Defensive Programming | dotNetDave | Entity Framework | Generics | LINQ | VB.NET | VS.NET | WCF | Web Services

If you need to serialize and deserialize your objects and persist them to disk, the the code below is an easy way to accomplish this. The GetObjectTypes function correctly detects types so that the serializer will do it's job correctly. Without this you could run into problems (as I did).

VB

    ''' <summary>

    ''' Deserializes from XML file.

    ''' </summary>

    ''' <typeparam name="T">Type</typeparam>

    ''' <param name="fileName">Name of the file.</param>

    ''' <returns></returns>

    Public Shared Function DeserializeFromXmlFile(Of T)(ByVal fileName As String) As T

        Return Deserialize(Of T)(My.Computer.FileSystem.ReadAllText(fileName))

    End Function

 

    ''' <summary>

    ''' Deserializes the specified XML.

    ''' </summary>

    ''' <typeparam name="T">Type</typeparam>

    ''' <param name="xml">The XML.</param>

    ''' <returns></returns>

    Public Shared Function Deserialize(Of T)(ByVal xml As String) As T

        Dim serializer = New XmlSerializer(GetType(T))

 

        Return DirectCast(serializer.Deserialize(New XmlTextReader(New StringReader(xml))), T)

    End Function

 

    ''' <summary>

    ''' Serializes obj to XML file.

    ''' </summary>

    ''' <param name="obj">The obj.</param>

    ''' <param name="fileName">Name of the file.</param>

    Public Shared Sub SerializeToXmlFile(ByVal obj As Object, ByVal fileName As String)

        My.Computer.FileSystem.WriteAllText(fileName, Serialize(obj), False)

    End Sub

 

    ''' <summary>

    ''' Serializes the specified obj to xml.

    ''' </summary>

    ''' <param name="obj">The obj.</param>

    ''' <returns></returns>

    Public Shared Function Serialize(ByVal obj As Object) As String

 

        Dim returnXml As String = String.Empty

 

        Dim serializer = New XmlSerializer(obj.[GetType](), GetObjectTypes(obj).ToArray())

 

        Using writer As New StringWriter(CultureInfo.CurrentCulture)

            serializer.Serialize(New XmlTextWriter(writer), obj)

 

            returnXml = writer.ToString()

        End Using

 

        Return returnXml

    End Function

 

    Private Shared Function GetObjectTypes(ByVal input As Object) As List(Of Type)

 

        Dim types = New List(Of Type)()

 

        Dim currentAssembly = input.[GetType]().Assembly

 

        Dim currentType As Type = input.[GetType]()

 

        'Query our types. We could also load any other assemblies and

        'query them for any types that inherit from the currentType

 

        For Each tempType As Type In currentAssembly.GetTypes()

            If Not tempType.IsAbstract AndAlso Not tempType.IsInterface AndAlso currentType.IsAssignableFrom(tempType) Then

                types.Add(tempType)

            End If

        Next

 

        Return types

    End Function

C#

        /// <summary>

        /// Deserializes from XML file.

        /// </summary>

        /// <typeparam name="T">Type</typeparam>

        /// <param name="fileName">Name of the file.</param>

        /// <returns></returns>

        public static T DeserializeFromXmlFile<T>(string fileName)

        {

            return Deserialize<T>(Microsoft.VisualBasic.FileIO.FileSystem.ReadAllText(fileName));

        }

 

        /// <summary>

        /// Deserializes the specified XML.

        /// </summary>

        /// <typeparam name="T">Type</typeparam>

        /// <param name="xml">The XML.</param>

        /// <returns></returns>

        public static T Deserialize<T>(string xml)

        {

            var serializer = new XmlSerializer(typeof(T));

 

            return (T)serializer.Deserialize(new XmlTextReader(new StringReader(xml)));

        }

 

        /// <summary>

        /// Serializes obj to XML file.

        /// </summary>

        /// <param name="obj">The obj.</param>

        /// <param name="fileName">Name of the file.</param>

        public static void SerializeToXmlFile(object obj, string fileName)

        {

            Microsoft.VisualBasic.FileIO.FileSystem.WriteAllText(fileName, Serialize(obj), false);

        }

 

        /// <summary>

        /// Serializes the specified obj to xml.

        /// </summary>

        /// <param name="obj">The obj.</param>

        /// <returns></returns>

        public static string Serialize(object obj)

        {

 

            string returnXml = string.Empty;

 

            var serializer = new XmlSerializer(obj.GetType(), GetObjectTypes(obj).ToArray());

 

            using (StringWriter writer = new StringWriter(CultureInfo.CurrentCulture))

            {

                serializer.Serialize(new XmlTextWriter(writer), obj);

 

                returnXml = writer.ToString();

            }

 

            return returnXml;

        }

 

        private static List<Type> GetObjectTypes(object input)

        {

 

            var types = new List<Type>();

 

            var currentAssembly = input.GetType().Assembly;

 

            Type currentType = input.GetType();

 

            //Query our types. We could also load any other assemblies and

            //query them for any types that inherit from the currentType

 

            foreach (Type tempType in currentAssembly.GetTypes())

            {

                if (!tempType.IsAbstract && !tempType.IsInterface && currentType.IsAssignableFrom(tempType))

                {

                    types.Add(tempType);

                }

            }

 

            return types;

        }



Tip Submitted By: David McCarter


 
Categories: Csharp | Generics | VB.NET | XML

If you are stuck using VB6 and .NET check out the site below.

http://msdn.microsoft.com/en-ca/vbrun/ms788241.aspx


 
Categories: .NET | Link | VB | VB.NET

March 1, 2009
@ 10:51 PM
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 Wednesday 4/1/2008 from 5:30pm to 9:15pm. For more information and to enroll, please click here.


 
Categories: Csharp | dotNetDave | VB.NET

January 9, 2009
@ 03:19 PM
I hope everyone in southern California is planning to attend this years SoCal Code Camp at Cal State Fullerton on 1/24 - 1/25. 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. Also, check out my new .NET discussion site called DotNet Army!

Building nTier Applications with Entity Framework Services

1:30PM Saturday - Room: UH 246

Learn how to build real world nTier applications with the new Entity Framework and related services introduced in .NET 3.5 SP1. With this new technology built into .NET, you can easily wrap an object model around your database and have all the data access automatically generated or use your own stored procedures and views. Then learn how to easily and securely expose your object model using WCF with just a few line of code using ADO.NET Data Services. The session will demonstrate how to create and consume these new technologies from the ground up. Lots of code!

Slides: Building nTier Applications with Entity Framework Services.pdf (2.79 MB)
Demo Code: Building nTier Applications with Entity Framework Services.zip (849.73 KB)


dotNetDave's Favorite Programming Tools

1:15PM Saturday - Room: UH 250

This session will focus on my favorite Visual Studio add-ins and other tools that makes programming faster and easier. I will focus on tools that are either free or very affordable. Tool categories include Writing Code (easier, faster and correct the first time!), Code Helpers, Documentation (helper and creation), General Utilities and more. These tools are designed to impress your boss and get you home at a reasonable time. Packed full of demonstrations and very few PowerPoint slides! Licenses for some of the 3rd party products I will be demonstrating will be given away, so be sure to attend and bring a business card!

Slides: dotNetDave's Favorite Programming Tools.pdf (1.8 MB)

Building Rich & Interactive Web Applications with ASP.NET AJAX

11:30AM Saturday - Room: MH 121

Learn how to build rich web application interfaces using ASP.NET AJAX and the ASP.NET AJAX Control Toolkit. This new technology makes programming JavaScript into your ASP.NET pages easy, increasing the power and functionality of your applications, reducing round trips to the server, and making it easy to consume web services for dynamic content. In this session you will be introduced to the new client and server controls for ASP.NET and Java Script to learn how to build a rich Web 2.0 experience for your users.

Slides: Building Rich & Interactive Web Applications with ASP.NET AJAX - 2009.pdf (2.36 MB)
Demo Code: Building Rich & Interactive Web Applications with ASP.NET AJAX - 20091.zip (702.2 KB) UPDATED!

Why You Need .NET Coding Standards (2009)

2:30PM Saturday - Room: UH 250

This session will guide any level of programmer to greater productivity by providing the information needed to write consistent, maintainable code. Learn about project setup, assembly layout, code style, defensive programming and much, much more. We will even go over some real in production code and see what the programmer did wrong in "What's Wrong With this Code?". Code tips are included to help you write better, error free applications. Lots of code examples in C# and VB.NET.

Slides: Why You Need .NET Coding Standards-2009.pdf (3.46 MB)
Demo Code: Why You Need .NET Coding Standards-2009.zip (94.46 KB)


Pictures and Video

SoCal CodeCamp Fullerton - 2009

Pictures from This Years Code Camp:

Pictures from past SoCal Code Camps:

Video from past Code Camps:


 

As most of you might know (I hope) it is unwise to call methods on a Control from a non-UI thread. This can cause all sorts of issues. Actually, I think in most cases .NET will throw and Exception. If you need to set a property on a Control this is how you would properly do it.

VB.NET

 Delegate Sub SetPropertyValueDelegate(ByVal obj As Object, ByVal val As Object, ByVal index As Object())

 

    Public Sub SetControlProperty(ByVal ctrl As Control, ByVal propName As String, ByVal val As Object)

        Dim propInfo As PropertyInfo = ctrl.[GetType]().GetProperty(propName)

        Dim propertyDelegate As [Delegate] = New SetPropertyValueDelegate(propInfo.SetValue)

        'index

        ctrl.Invoke(propertyDelegate, New Object(2) {ctrl, val, Nothing})

    End Sub

 

    Private Sub UpdateSent(ByVal item As String)

        _chat.AppendLine(item)

 

        If Me.SentTextBox.InvokeRequired Then

            ' This is a worker thread so delegate the task.

            SetControlProperty(SentTextBox, "Text", _chat.ToString())

        Else

            ' This is the UI thread so perform the task.

            Me.SentTextBox.Text = _chat.ToString()

        End If

 

 

    End Sub

C#

        delegate void SetPropertyValueDelegate(Object obj, Object val, Object[] index);

 

        public void SetControlProperty(Control ctrl, String propName, Object val)

        {

            PropertyInfo propInfo = ctrl.GetType().GetProperty(propName);

            Delegate propertyDelegate = new SetPropertyValueDelegate(propInfo.SetValue);

            ctrl.Invoke(propertyDelegate, new Object[3] { ctrl, val, /*index*/null });

        }

 

        private void UpdateSent(string item)

        {

            _chat.AppendLine(item);

 

            if (this.SentTextBox.InvokeRequired)

            {   // This is a worker thread so delegate the task.

                SetControlProperty(SentTextBox, "Text", _chat.ToString());

            }

            else

            {   // This is the UI thread so perform the task.      

                this.SentTextBox.Text = _chat.ToString();

            }

 

        }

UpdateSent is example code on how to use the code. Also, _chat is a StringBuilder object. This code is taken from a chat program I wrote at where I work.

Tip Submitted By: David McCarter


 
Categories: Csharp | VB.NET | WinForms

October 29, 2008
@ 01:01 PM
Learn about the future of VB.NET!

http://code.msdn.microsoft.com/vbfuture

Here is some of what is new:

* sub lambdas, and multiline sub/function lambdas

* sub lambdas, and multiline sub/function lambdas

* AsParallel. (well, this was a plinq feature rather than a VB feature, but cool as heck)

* DLR interop: invoke DLR methods from VB; create dynamic objects from VB; pass .net objects to DLR code; pass DLR objects to VB code. Note: unfortunately, this feature wasn’t ready in time for inclusion in the CTP.

* array literals, including inference of array structure (e.g. {{1,0},{0,1}} and {({1,2,3,4}),({1,2})}

* collection initializers: “dim x as new dictionary(of string,integer) from {{“hello”,1},{“world”,2}}

* auto-implemented properties, including initializers for them

* generic co- and contra-variance. Note: the VB support for co- and contra-variance was in the CTP. Unfortunately the covariant version IEnumerable(Of Out T) wasn’t ready in time for inclusion in the CTP, nor any of the other BCL classes. Also the CTP has a crummy bug that’s my fault which crashes when you use variance as part of overload resolution.

* line continuations (also www.unemployedunderscores.com!)

* No-PIA
 
Categories: Link | VB.NET

If you came to my talk at the OC .NET User group meeting today, below is a link to the presentation. Enjoy!

Why You Need .NET Coding Standards (2008)

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

Link to my book: http://www.cafepress.com/geekmusicart.165478704


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

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>David McCarter's VB Tips & Techniques</Title>
  </Book>
</Books>

Where I work, we are saving our xml to hardware devices with limited memory. So the <?xml> element and "xmlns" attributes are taking up limited resources and have to be removed. You would think there would be a property in the XmlSerilizer to omit this extra stuff, but there isn't. So I had to roll my own. I changed the SerilizeObjectToXML call a little and added a new method called CleanXML.

Public Shared Function SerializeObjectToXML(ByVal input As Object, ByVal type As System.Type, ByVal clean As Boolean) 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()
    If clean Then
      returnXML = CleanXML(returnXML)
    End If
    Catch ex As Exception
      Debug.WriteLine(ex.Message)
    Finally
      writer.Close()
  End Try
  Return returnXML
End Function
  
Private Shared Function CleanXML(ByVal input As String) As String
Dim readerXML As New XmlTextReader(New StringReader(input))
Dim writer As New StringWriter
Dim writerXML As New XmlTextWriter(writer)
Dim returnXML As String = String.Empty
  Try
    'writerXML.WriteStartDocument()
    While readerXML.Read()
      Select Case readerXML.NodeType
        Case XmlNodeType.Element
          writerXML.WriteStartElement(readerXML.Name)
          If (readerXML.HasAttributes) Then
            'Cannot just use writer.WriteAttributes,
            'else it will also emit xmlns attribute              
            While readerXML.MoveToNextAttribute()
              If (readerXML.Name.CompareTo("xmlns") = -1) Then
                writerXML.WriteAttributeString(readerXML.Name, readerXML.Value)
              End If
            End While
            readerXML.MoveToElement()
          End If
          If (readerXML.IsEmptyElement) Then
            writerXML.WriteEndElement()
          End If
        Case XmlNodeType.Text
          writerXML.WriteString(readerXML.Value)
        Case XmlNodeType.CDATA
          writerXML.WriteCData(readerXML.Value)
        Case XmlNodeType.ProcessingInstruction
          writerXML.WriteProcessingInstruction(readerXML.Name, readerXML.Value)
        Case XmlNodeType.Comment
          writerXML.WriteComment(readerXML.Value)
        Case XmlNodeType.EntityReference
          writerXML.WriteEntityRef(readerXML.Name)
        Case XmlNodeType.EndElement
          writerXML.WriteEndElement()
      End Select
    End While
    'writerXML.WriteEndDocument()
    writerXML.Flush()
    returnXML = writer.ToString()
  Finally
    writerXML.Close()
    readerXML.Close()
    writer.Close()
  End Try
  Return returnXML
End Function

The readerXML.Name.CompareTo("xmlns") line in the method above will remove the "xmlns" attributes and the commented out WriteStartDocument and WriteEndDocument calls to the writer will remove the <?xml> element. Now your xml is bare!

But be careful when using this CleanXML, as I just found out, if your classes specify the xml namespace by using the XmlRoot or XmlType attributes, then deserializing won't work unless you put the "xmlns" attribute back in (that is my next task to do after I post this tip).

.NET 2.0 And Generics

 Here is the same code but for .NET 2.0 using generics:

Public Shared Function DeserializeXML(Of T)(ByVal xml As String) As T
  Dim serializer As New Serialization.XmlSerializer(GetType(T))
  Return DirectCast(serializer.Deserialize(New XmlTextReader(New IO.StringReader(xml))), T)
End Function
Public Shared Function SerializeToXML(Of T)(ByVal obj As T) As String
  Dim returnXML As String = String.Empty
  Dim serializer As New Serialization.XmlSerializer(GetType(T))
  Using writer As New IO.StringWriter
    serializer.Serialize(New XmlTextWriter(writer), obj)
    returnXML = writer.ToString()
  End Using
  Return returnXML
End Function

Tip Submitted By: David McCarter


 
Categories: .NET | Generics | VB.NET | XML

To download go to: http://go.microsoft.com/?linkid=5559918

 


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

Great article on generating docs for your VB.NET Application:

http://msdn2.microsoft.com/en-us/library/Aa289191(VS.71).aspx


 
Categories: dotNetDave | VB.NET | Link

Instead you need to actually use a p/invoke api call. Here is the code:

Imports System.Text
Imports System.Runtime.InteropServices
 
  <DllImport("kernel32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
  Public Shared Function GetShortPathName(ByVal lpszLongPath As String, _
ByVal lpszShortPath As StringBuilder, ByVal cchBuffer As Integer) As Integer
  End Function
 
  Private Function ConvertLongPathToShort(ByVal longPathName As String) As String
    Dim shortNameBuffer = New StringBuilder
    Dim size As Integer = Me.GetShortPathName(longPathName, shortNameBuffer, _
shortNameBuffer.Capacity)
    If (size >= shortNameBuffer.Capacity) Then
      shortNameBuffer.Capacity = size + 1
      GetShortPathName(longPathName, shortNameBuffer, shortNameBuffer.Capacity)
    End If
    Return shortNameBuffer.ToString()
  End Function

Example:

 ConvertLongPathToShort("E:\My Documents\My Pictures\10dollarbill.jpg")

returns

E:\MYDOCU~1\MYPICT~1\10DOLL~1.JPG

I needed to do this because an open source program I am using via command-line had issues if I sent a long path/file name into it surrounded by quotes into one of its parameters. Also, the managed code calling GetShortPathName will full system permissions to call unmanaged code.

 

Tip By: David McCarter (with help from www.pinvoke.net and Igor Zinkovsky [MSFT])


 
Categories: VB.NET

The Power Pack controls consist of:

  • BlendPanel. This provides a background for a form where the color fades from one shade to another.
  • UtilityToolbar. This is a toolbar whose look and feel is similar to the Internet Explorer toolbar.
  • ImageButton. This is a button that displays a graphic over a transparent background.
  • NotificationWindow. This displays text and graphics in a pop-up window (commonly known as "toast").
  • TaskPane. This is a container that provides collapsible frames for displaying additional information on a form.
  • FolderViewer. This displays directories in a hierarchical format.
  • FileViewer. This displays a list of the files in a specified directory.

For more information, go to: http://msdn.microsoft.com/vbasic/default.aspx?pull=/library/en-us/dv_vstechart/html/vbpowerpack.asp


 
Categories: dotNetDave | Link | VB.NET | WinForms

  Dim stream As MemoryStream = New MemoryStream
  Dim bitmapBytes As Byte()
  'Create bitmap
  Dim bitmap As Bitmap = New Bitmap(50, 50)
  bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg)
  bitmapBytes = stream.ToArray
  stream.Close()
  bitmap.Dispose()

 

Tip Submitted By: David McCarter


 
Categories: VB.NET

Just use the code below. I'm sure you will want to replace the hard-coded values with parameters from a method.

Dim mailProcess As New Process()
Dim processInfo As New System.Diagnostics.ProcessStartInfo()
  processInfo.FileName = "mailto:someone@someone.com?" _
                            & "cc=someoneelse@someone.com&" _
                            & "subject=Sample Subject&" _
                            & "body=Body of Message"
  processInfo.UseShellExecute = True
  processInfo.WindowStyle = ProcessWindowStyle.Normal
  mailProcess.StartInfo = processInfo
  mailProcess.Start(processInfo)

Tip Submitted By: David McCarter

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


 
Categories: VB.NET

It’s was told to me that this can never be shown to the client and further more the number can never be rounded (anyone ever see Office Space… sound familiar?).

So I went searching on how to do this in .NET. After many, many hours of searching and testing, I could not find any way in .NET to do this. Every function I found would always round the number! I found myself wishing for just a way to flip a switch to tell .NET to stop doing that. So I finally gave up and came up with a short function that will do what the client needs.

The ConvertDecimal function will simply return a decimal number with the desired decimal places with NO ROUNDING.

 

Shared Function ConvertDecimal(ByVal inputValue As Decimal, ByVal placesAfter As Integer) As Decimal
Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder()
  Dim tempValue As String = Convert.ToString(inputValue)
  Dim tempSplit() As String = tempValue.Split(Convert.ToChar("."))
  If (tempSplit.GetLowerBound(0) = 0) Then
   sb.Append(tempSplit(0))
  End If
  If (tempSplit.GetUpperBound(0) = 1) Then
   sb.Append(".")
    sb.Append(tempSplit(1).Substring(0, placesAfter))
  End If
  Return Convert.ToDecimal(sb.ToString())
End Function

 

Tip Submitted By: David McCarter

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


 
Categories: VB.NET

August 15, 2003
@ 01:50 AM

The function below returns the appliction path for an appliction in the Compact Framework.

Shared Function GetAppPath() As String
Dim mstrPath As String
mstrPath = _
   System.IO.Path.GetDirectoryName
   (System.Reflection.Assembly.GetExecutingAssembly().GetModules
   (0).FullyQualifiedName)
If Right(mstrPath, 1) <> "\" Then
mstrPath += "\"
End If
Return mstrPath
End Function

Tip Submitted By: David McCarter & Marquis Howard


 
Categories: Compact Framework | VB.NET

So I created the nifty little Function below:

Private Function GetWebFormValue(ByRef WebForm As System.Collections.Specialized.NameValueCollection, _
                                   ByVal ControlName As String) As String
  Try
    Return WebForm(ControlName).ToString
  Catch
    Return String.Empty
  End Try
End Function


Here is how to use it:

pstrTemp = GetWebFormValue(Request.Form, "txtZipCode")

If you have an easier, better way to do this same thing, please let me know. Best of all, this will not cause an exception!!! 

Tip Submitted By: David McCarter


 
Categories: ASP.NET | VB.NET

Below are some converted VB6 methods that do common database connection tasked. The first one (CheckSQLConnection) checks to make sure that a connection can be made to the database. This could be used at the beginning of your application or web application to make sure that the database is up. If it's not, doubt if there is much need in continuing.

The next method (CloseSQLConnection), closes a SQLConnection object if it is open. NEVER assume that the connection was successfully opened during the course of your application.

The last method (OpenSQLConnection), will open a SQLConnection object (and pass it back to the calling method) based on the connection string passed to it. The method will return True if it succeeded with no errors.

I always uses these methods wrapped with exception handling to open and close SQLConnections... safer that way. Also these methods use the new .NET SQLConnection object not the ADO object. The built in SQL objects in .NET have faster access to SQL than the ADO objects do! 

Imports System.Data
Imports System.Data.SqlClient
Public Function CheckSQLConnection(ByVal DBConnection As String) As Boolean
Dim pcnConnection As SQLConnection
  Try
    pcnConnection = New SQLConnection()
  Catch poExcep As Exception
    Return False
    Exit Function
  End Try
  Try
    pcnConnection.ConnectionString = DBConnection
    pcnConnection.Open()
  Catch poExcep As Exception
    'Could not make connection
    Return False
    Exit Function
  End Try
  If pcnConnection.State = ConnectionState.Open Then
    Return True
    Else
      Return False
  End If
  If Not pcnConnection Is Nothing Then
    CloseSQLConnection(pcnConnection)
  End If
End Function
Public Sub CloseSQLConnection(ByRef SQLConnObj As SQLConnection)
  Try
    If SQLConnObj.State <> ConnectionState.Closed Then
      SQLConnObj.Close()
    End If
  Catch poExcep As Exception
    'Blow by any errors
  End Try
End Sub
Public Function OpenSQLConnection(ByVal DBConnection As String, _
                                    ByRef SQLConnObj As SQLConnection, _
                                    Optional ByVal ConnectionTimeout As Integer = 15 _
                                    ) As Boolean
  If SQLConnObj Is Nothing Then
    Try
      SQLConnObj = New SQLConnection()
    Catch poExcep As Exception
      Return False
      Exit Function
    End Try
  End If
  'Setup Connection
  Try
    SQLConnObj.ConnectionTimeout = ConnectionTimeout
    SQLConnObj.ConnectionString = DBConnection
    SQLConnObj.Open()
  Catch poExcep As Exception
    Return False
    Exit Function
  End Try
  'Make sure it's open
  If SQLConnObj.State = ConnectionState.Open Then
    Return True
    Else
      Return False
  End If
End Function

Tip By: David McCarter


 
Categories: ADO.NET | VB.NET

Okay, I need to give you some history of .NET... at first, by default, Options Strict was turned on. This is a good thing! It makes for better bug free code. Many of us have been waiting for this for a long time. But, some of the big-wigs in the VB world started crying?!?!  Why... because they said that this would hamper their efforts to migrate VB6 code to VB.NET. Ha! Migrating code is a pipe dream and should be avoided at all costs. For some STUPID reason Microsoft actually listened to them and in the final release of VB.NET turned it off. So now, when a new project is created, we have to remember to go turn it on. What a pain!

Well, there is a way to fix it, but it's not pretty. When you create a project in VB.NET using File | New | Project and select a project type, it's actually using a project template. To find the templates, navigate to:

<drive>:\Program Files\Microsoft Visual Studio .NET\Vb7\VBWizards

Then it gets kinda tricky. Find the project template folder that needs to be edited. For example, ClassLibrary for creating DLL like assemblies or WindowsApplication for a Windows application (duh). Then navigate to the Templates folder. Then bring up the .vbproj file in an text editor. Under the <Settings> node add the following:

OptionStrict = "On"

You should end up with something that looks like this:

<Settings
  OutputType = "Library"
  OptionStrict = "On"
  StartupObject = ""
>

Save the file and your done! You will need to do this to every project template that you use.

 

Tip Submitted By: David McCarter


 
Categories: VB.NET

When setting a string object to an empty string, I did a test and I found that doing this:

Dim ContentFieldName As String = String.Empty

Is slightly faster than doing this:

Dim ContentFieldName As String = ""

Your results my vary 

 

Tip Submitted By: David McCarter


 
Categories: VB.NET

August 15, 2003
@ 01:28 AM

Using VB6, it took a lot of code to read values from the Registration Database. Well, not anymore with with VB.NET! Take a look at the code below.

 

Imports Microsoft.Win32
Function GetDBConnect() As String
Dim pobjRegKey As RegistryKey
Dim pstrValue As String
 pobjRegKey = _
 Registry.LocalMachine.OpenSubKey("SYSTEM\CurrentControlSet\Services\MyService\Parameters", False)
 If Not IsNothing(pobjRegKey) Then
   pstrValue = pobjRegKey.GetValue("DBConnect", vbNullString).ToString
   Return pstrValue
   Else
     Return vbNullString
  End If
End Function

 

That's all there is to it! Basically two lines of code! This function gets a a value called "DBConnect" (database connection string) out of the Registry for a Windows Service.

 

Tip By: David McCarter


 
Categories: VB.NET