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

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

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

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