On Authentication Timeout - Save Web Form Contents

I was working on a project recently where I had to figure out how to persist user data in a web form after their Forms Authentication session as expired.

So I was thinking of ways to do this as I searched the know all Google. Walla!  Someone's already had to do this, why invent the wheel.  Found a post by Peter Ravnholt, on the MSDN site. http://code.msdn.microsoft.com/formsaver 

He Implements the HttpModule and handles saving the form state on FormAuthentication events. Really neat idea.  I tried is code, now keep in mind I'm doing this for Visual Basic, so I manually converted it all, but I couldn't get it work. Maybe I was converting something wrong.  I was getting "The state information is invalid for this page and might be corrupted."

Well RichardDeeming in the discussions for this post had an updated version that worked a little better then the original. http://code.msdn.microsoft.com/formsaver/Thread/View.aspx?ThreadId=88  Thanks to his code, I converted it to VB.Net and walla!  My pages now handle web content.

I'll post the converted VB version below. 

Thanks Richard and Peter if you ever find your names on here via Google :p

This is my VB version o the FormSaverHttpModule with Richard's changes.  I've modified it a bit since but this works.

Imports Microsoft.VisualBasic
Imports System.Security.Principal
Imports System.IO
Imports System.Web.Configuration
Imports System.Security.Permissions
 
''' <summary>
''' FormSaverModule Version 1.0
''' -Mastro:  Not my orignal idea, found this in use out on MSDN site. I manually converted it to VB
''' as the orignaly is in C#. No comments, so I'll add my own.
''' 
''' This class will handle every new request coming in and PostMapRequest. 
''' If user has Forms Authentication has timed out, class will save the state of the form into cache
''' with a Unique ID of that state to the user's cookie. 
''' 
''' When user logs back in, this class will check if they have the cookie set, if so it will then 
''' load that state back to their page and load the webcontent by generating a runtime transit page that
''' post submits the data back to the destination page and pre-fills in the values.
''' </summary>
''' <remarks></remarks>
<AspNetHostingPermission(SecurityAction.LinkDemand, Level:=System.Web.AspNetHostingPermissionLevel.Minimal)> _
<AspNetHostingPermission(SecurityAction.InheritanceDemand, Level:=AspNetHostingPermissionLevel.Minimal)> _
Public Class FormSaverHTTPModule
    Implements IHttpModule
 
#Region "Private Variables"
 
    Private Const CookieName As String = "#FormStateSaverModule/FormRestoreId"
    Private Shared ReadOnly StateCacheDuration As TimeSpan = TimeSpan.FromMinutes(40)
    Private Shared ReadOnly _AnonymousUser As IPrincipal = New GenericPrincipal(New GenericIdentity(String.Empty), Nothing)
    Private _FormsCookieName As String
    Private _LoginUrl As String
 
#End Region
 
    ''' <summary>
    ''' This class is required from the IHttpModule contract
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub Dispose() Implements System.Web.IHttpModule.Dispose
 
    End Sub
 
    ''' <summary>
    ''' This is the first method to run on application start
    ''' </summary>
    ''' <param name="Context"></param>
    ''' <remarks></remarks>
    Public Sub IHttpModuleInit(ByVal Context As HttpApplication) Implements System.Web.IHttpModule.Init
        Me.Init(Context) 'Lets call our Init and send the Application state along with it
    End Sub
 
    ''' <summary>
    ''' We call this Init Method from the IHttpModuleInit and send it the Application State
    ''' and then turn on Events to capture
    ''' </summary>
    ''' <param name="Context">Hold's the Application State</param>
    ''' <remarks></remarks>
    Protected Overridable Sub Init(ByVal Context As HttpApplication)
        If Context Is Nothing Then
            Throw New ArgumentNullException("context")
        End If
 
        _LoginUrl = FormsAuthentication.LoginUrl 'Store the Login page name
        _FormsCookieName = FormsAuthentication.FormsCookieName 'Store the Forms Authentication Cookie Name
 
        If Not String.IsNullOrEmpty(_LoginUrl) Then 'If LoginUrl Exists....
            Dim index As Integer = _LoginUrl.IndexOf("?"c) 'Search for a ? for query string
            If -1 <> index Then 'If ? was found....
                _LoginUrl = _LoginUrl.Substring(0, index) 'Grab the first part of the URL before the ? and set LoginUrl
            End If
        End If
 
        'Add Handlers that now raise events on every Application BeginRequest... and Application PostMapRequest
        AddHandler Context.BeginRequest, New EventHandler(AddressOf Application_BeginRequest)
        AddHandler Context.PostMapRequestHandler, New EventHandler(AddressOf Application_PostMapRequestHandler)
 
    End Sub
 
    ''' <summary>
    ''' A Delegate receiver method for the Application.BeginRequest Event
    ''' </summary>
    ''' <param name="sender">Object</param>
    ''' <param name="e">EventArgs</param>
    ''' <remarks></remarks>
    Protected Overridable Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
        Dim application As HttpApplication = DirectCast(sender, HttpApplication)
        Dim context As HttpContext = application.Context
 
        Dim cookie As HttpCookie = context.Request.Cookies(CookieName)
        If cookie IsNot Nothing AndAlso Not String.IsNullOrEmpty(cookie.Value) Then 'If Cookie exist and has value....
            Dim state As FormState = FormState.Load(cookie.Value) 'Lets try and load the state via the CookieID
 
            'Lets see if the State is valid now that it's loaded and it's originaly location matches where the user is trying to go
            If state IsNot Nothing AndAlso String.Equals(state.Path, context.Request.Path, StringComparison.OrdinalIgnoreCase) Then
                FormState.SetCurrent(context, state) 'State is valid and it's for this request so lets create the object of the state to be used later by Application_PostMapRequestHandler
                Return
            End If
        End If
 
        If IsPost(context) AndAlso Not IsAccessingLoginPage(context, _LoginUrl) Then 'If user is doing a Post back and it's not to the login page...
            cookie = context.Request.Cookies(_FormsCookieName) 'Load Authenication cookie
            If cookie IsNot Nothing Then
                Try
                    Dim ticket As FormsAuthenticationTicket = FormsAuthentication.Decrypt(cookie.Value)
                    If ticket IsNot Nothing AndAlso ticket.Expired AndAlso Not HasAnonymousAccess(context) Then 'If the user has expired.....
                        Dim state As FormState = FormState.Create(context) 'Store current state into cache
                        If state IsNot Nothing Then
                            cookie = New HttpCookie(CookieName, state.StateId) 'save cache ID into user's cookie
 
                            cookie.HttpOnly = True
                            context.Response.Cookies.Add(cookie)
                        End If
                    End If
                Catch generatedExceptionName As ArgumentException
                End Try
            End If
        End If
    End Sub
 
    Protected Overridable Sub Application_PostMapRequestHandler(ByVal sender As Object, ByVal e As EventArgs)
        Dim application As HttpApplication = DirectCast(sender, HttpApplication)
        Dim context As HttpContext = application.Context
 
        Dim state As FormState = FormState.GetCurrent(context) 'Get the context from the cache if it's there
        If state IsNot Nothing AndAlso state.Form IsNot Nothing AndAlso 0 <> state.Form.Count Then 'if the context was there....
            context.Handler = New FormStateSaverHandler(state) 'Then load the runtime transit page and post it back to destination page
        End If
    End Sub
 
    ''' <summary>
    ''' Returns Boolean if request is a Post request to page.
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Protected Shared Function IsPost(ByVal context As HttpContext) As Boolean
        Return String.Equals("POST", context.Request.HttpMethod, StringComparison.OrdinalIgnoreCase)
    End Function
 
    ''' <summary>
    ''' Return Boolean after it checks to see if content matches the LoginURL. Basically is the user 
    ''' going to the login page.
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Protected Shared Function IsAccessingLoginPage(ByVal context As HttpContext, ByVal loginUrl As String) As Boolean
        Dim result As Boolean = False
        If Not String.IsNullOrEmpty(loginUrl) Then
            If String.Equals(context.Request.Path, loginUrl, StringComparison.OrdinalIgnoreCase) Then
                result = True
            ElseIf -1 <> loginUrl.IndexOf("%"c) Then
                Dim temp As String = HttpUtility.UrlDecode(loginUrl)
                If String.Equals(context.Request.Path, temp, StringComparison.OrdinalIgnoreCase) Then
                    result = True
                Else
                    temp = HttpUtility.UrlDecode(loginUrl, context.Request.ContentEncoding)
                    If String.Equals(context.Request.Path, temp, StringComparison.OrdinalIgnoreCase) Then
                        result = True
                    End If
                End If
            End If
        End If
 
        Return result
    End Function
 
    ''' <summary>
    ''' Returns Boolean if the destination URL in question has anonymouse access.
    ''' </summary>
    ''' <param name="context"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Protected Shared Function HasAnonymousAccess(ByVal context As HttpContext) As Boolean
        Return UrlAuthorizationModule.CheckUrlAccessForPrincipal(context.Request.Path, _AnonymousUser, context.Request.HttpMethod)
    End Function
 
    ''' <summary>
    ''' This class becomes the actual FormState the user was on and is Serialzied and then saved 
    ''' </summary>
    ''' <remarks></remarks>
    <Serializable()> _
    Protected NotInheritable Class FormState
        Private Shared ReadOnly FormRestoreKey As New Object()
 
        Private ReadOnly _id As String
        Private ReadOnly _path As String
        Private ReadOnly _form As NameValueCollection
 
        Private Sub New(ByVal id As String, ByVal path As String, ByVal form As NameValueCollection)
            _id = id
            _path = path
            _form = form
        End Sub
 
        Public ReadOnly Property StateId() As String
            Get
                Return _id
            End Get
        End Property
 
        Public ReadOnly Property Path() As String
            Get
                Return _path
            End Get
        End Property
 
        Public ReadOnly Property Form() As NameValueCollection
            Get
                Return _form
            End Get
        End Property
 
        ''' <summary>
        ''' Loads the state that was set by Setcurrent and tries to return it as a FormState object.
        ''' Returns nothing if it's invalid.
        ''' </summary>
        ''' <param name="context"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function GetCurrent(ByVal context As HttpContext) As FormState
            If context Is Nothing Then
                Return Nothing
            End If
            Return TryCast(context.Items(FormRestoreKey), FormState)
        End Function
 
        ''' <summary>
        ''' Takes the state sent and creates a valid formstate object
        ''' </summary>
        ''' <param name="context"></param>
        ''' <param name="state"></param>
        ''' <remarks></remarks>
        Public Shared Sub SetCurrent(ByVal context As HttpContext, ByVal state As FormState)
            If context IsNot Nothing Then
                context.Items(FormRestoreKey) = state
            End If
        End Sub
 
        ''' <summary>
        ''' Takes the Context of the current Request Form and stores it into Cache with a Unique ID
        ''' </summary>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function Create(ByVal context As HttpContext) As FormState
            Dim result As FormState = Nothing
            If context IsNot Nothing AndAlso context.Request.Form IsNot Nothing AndAlso 0 <> context.Request.Form.Count Then
                Dim id As String = Guid.NewGuid().ToString()
                result = New FormState(id, context.Request.Path, context.Request.Form)
                HttpRuntime.Cache.Add("FormStateSaver_" + id, result, Nothing, Cache.NoAbsoluteExpiration, StateCacheDuration, CacheItemPriority.Normal, _
                Nothing)
            End If
            Return result
        End Function
 
        ''' <summary>
        ''' Loads the Context stored in Cache using the Unique ID
        ''' </summary>
        ''' <param name="id">Unique GUID</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function Load(ByVal id As String) As FormState
            Dim result As FormState = Nothing
            If Not String.IsNullOrEmpty(id) Then
                result = TryCast(HttpRuntime.Cache("FormStateSaver_" + id), FormState)
            End If
 
            Return result
        End Function
 
        ''' <summary>
        ''' Deletes the stored Context from Cache
        ''' </summary>
        ''' <remarks></remarks>
        Public Sub Delete()
            HttpRuntime.Cache.Remove("FormStateSaver_" + _id)
        End Sub
    End Class
 
    ''' <summary>
    ''' This class is responsible for generating the Transit page on the fly. 
    ''' Basically a page that loads all the values then submits them back to the destination
    ''' page with the previous viewstate settings so that the form reloads the controls to where
    ''' they were prior.
    ''' 
    ''' This page quickly shows when the user is logging back in and loading a previous web form.
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Protected Class FormStateSaverHandler
        Implements IHttpHandler
 
        Private ReadOnly _state As FormState
 
        Public Sub New(ByVal state As FormState)
            _state = state
        End Sub
 
        Protected ReadOnly Property FormState() As FormState
            Get
                Return _state
            End Get
        End Property
 
        Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
            Get
                Return False
            End Get
        End Property
 
        Public Overridable Sub ProcessRequest(ByVal context As HttpContext) Implements System.Web.IHttpHandler.ProcessRequest
            Try
                Using writer As HtmlTextWriter = CreateHtmlTextWriter(context.Response.Output, context.Request.Browser)
                    Me.Render(writer)
                End Using
            Finally
                _state.Delete()
            End Try
        End Sub
 
        Protected Overridable Sub Render(ByVal writer As HtmlTextWriter)
            writer.RenderBeginTag(HtmlTextWriterTag.Html)
            writer.RenderBeginTag(HtmlTextWriterTag.Head)
            writer.RenderBeginTag(HtmlTextWriterTag.Title)
            writer.Write("Restoring form")
            writer.RenderEndTag()
            ' TITLE 
            writer.RenderEndTag()
            ' HEAD 
            writer.AddAttribute("onload", "document.forms[0].submit();")
            writer.RenderBeginTag(HtmlTextWriterTag.Body)
 
            writer.AddAttribute("method", "post")
            writer.RenderBeginTag(HtmlTextWriterTag.Form)
 
            Dim form As NameValueCollection = Me.FormState.Form
            For Each name As String In form.Keys
                RenderHiddenField(writer, name, form(name))
            Next
 
            'writer.AddAttribute(HtmlTextWriterAttribute.Align, "center")
            'writer.RenderBeginTag(HtmlTextWriterTag.P)
            'writer.Write("You should be redirected in a moment.")
            'writer.WriteFullBeginTag("br")
            'writer.Write("If nothing happens, please click ")
            'RenderSubmitButton(writer, "Submit")
            'writer.RenderEndTag()
            ' P 
            writer.RenderEndTag()
            ' FORM 
            writer.RenderEndTag()
            ' BODY 
            writer.RenderEndTag()
            ' HTML 
        End Sub
 
        Protected Shared Sub RenderHiddenField(ByVal writer As HtmlTextWriter, ByVal name As String, ByVal value As String)
            writer.AddAttribute(HtmlTextWriterAttribute.Type, "hidden")
            writer.AddAttribute(HtmlTextWriterAttribute.Name, name)
            writer.AddAttribute(HtmlTextWriterAttribute.Value, value)
            writer.RenderBeginTag(HtmlTextWriterTag.Input)
            writer.RenderEndTag()
            ' INPUT 
        End Sub
 
        Protected Shared Sub RenderSubmitButton(ByVal writer As HtmlTextWriter, ByVal text As String)
            writer.AddAttribute(HtmlTextWriterAttribute.Type, "submit")
            writer.AddAttribute(HtmlTextWriterAttribute.Value, text)
            writer.RenderBeginTag(HtmlTextWriterTag.Input)
            writer.RenderEndTag()
            ' INPUT 
        End Sub
 
        Protected Shared Function CreateHtmlTextWriter(ByVal writer As TextWriter, ByVal browser As HttpCapabilitiesBase) As HtmlTextWriter
            If browser Is Nothing Then
                Return New HtmlTextWriter(writer)
            End If
            Return browser.CreateHtmlTextWriter(writer)
        End Function
 
 
    End Class
 
 
End Class
 
 
 
 
 

 

Update: 6/10/10

Here is the original post, and it was moved to codeplex here.  Thanks Peter Revnholt!

VisitMix

I haven’t had the privilege yet of going to a MIX conference.  My eyes weep.  However, I applaud them for recording the sessions and putting them online.  Just seeing some of these, makes me want to go to a Mix Conference even more.

So for those of you like me, or for those of you that did go… I want to just bring to attention that the recordings are online at http://videos.visitmix.com/

There’s a lot here. Something for everyone. Mainly geared towards all .NET and Microsoft but there still .NET development with Ruby and Python and business development related videos. You have Silverlight, Web Services, Windows 7 Phone development, RIA, Sketchflow, Design for Developers, User Experience, Software Entrepreneurs, Social Networking Development, Windows Messenger Live Services and more..

Check out the list of these videos.

MIX 10 Conference Videos

Title

Changing our Game – an Introduction to Windows Phone 7 Series
Joe Belfiore

Authoring for Windows Phone, Silverlight 4 and WPF 4 with Expression Blend
Christian Schormann, Peter Blois

Prototyping Rich Microsoft Silverlight Applications with Expression SketchFlow
Chris Bernard

Designing Bing: Heart and Science
Paul Ray

Microsoft Silverlight 4 Overview: What's in Store for Silverlight 4?
Keith Smith

Microsoft Silverlight 4 Business Applications
Scott Morrison

Developing with WCF RIA Services Quickly and Effectively
Nikhil Kothari

Stepping Outside the Browser with Microsoft Silverlight 4
Ashish Shetty

Overview of the Windows Phone 7 Series Application Platform
Charlie Kindel

Windows Phone UI and Design Language
Chad Roberts, Michael Smuga, Albert Shum

An Introduction to Developing Applications for Microsoft Silverlight
Shawn Oster

Building Windows Phone Applications with Silverlight, Part 1
Mike Harsh

Building Windows Phone Applications with Silverlight, Part 2
Peter Torr

Windows Phone Application Platform Architecture
Istvan Cseri

Development and Debugging Tools for Building XNA Games for Windows Phone
Cullen Waters

Distributing and Monetizing Windows Phone Applications and Games
John Bruno, Todd Biggs

Building Windows Phone Games
Michael Klucher

Building a High Performance 3D Game for Windows Phone
Shawn Hargreaves, Tomas Vykruta

Designing and Developing for the Rich Mobile Web
Joe Marini

The Microsoft Silverlight Analytics Framework
Michael Scherotter, Alfonso Corretti

Microsoft Silverlight "Media" : Moving at 60fps
Eric Schmidt

Introducing the Silverlight Rough Cut Editor
Jason Suess

HTML5: Cross-Browser Best Practices
Tony Ross

In-Depth Look at Internet Explorer 9
Ted Johnson, John Hrvatin

HTML5: High-Performance Best Practices for Web Sites
Jason Weber

Building Innovative Windows Client Software
Tim Huckaby, Scott Hanselman, Scott Stanfield, Tim Sneath, Dave Wolf

Search Engine Optimization for Microsoft Silverlight
Brad Abrams

Building an Accessible Microsoft Silverlight Experience
Mark Rideout

Microsoft Silverlight Optimization and Extensibility with MEF
Glenn Block

Flash Skills Applied to Microsoft Silverlight Design and Development
Adam Kinney

Software and Web Entrepreneurs: Go Big with BizSpark and WebsiteSpark
Alex Souza, Julien Codorniou

Dynamic Layout and Transitions for Microsoft Silverlight 4 with Microsoft Expression Blend
Kenny Young

A Case Study: Rapid WordPress Design and Prototyping with Expression Web 3
Morten Rand-Hendriksen

Practical Strategies for Debugging Cross-Browser Display Issues
Lori Dirks

Accessing Web Services in Microsoft Silverlight
Yavor Georgiev

Unit Testing Silverlight and Windows Phone Applications
Jeff Wilcox

Silverlight Performance on Windows Phone
Seema Ramchandani

The Laws of User Experience
Anthony Franco

Treat Your Content Right
Tiffani Jones Brown

Running with Wireframes: Taking Information Architecture (IA) into Design
Matt Brown

Lifecycle of a Wireframe
Nick Finck

Total Experience Design
Paul Dawson

Touch in Public: Multi-touch Interaction Design for Kiosks and Architectural Experiences
Jason Brush

The Art, Technology and Science of Reading
Kevin Larson

Creating Great Experiences through Collaboration
Noah Gedrich, Eric Perez, Sean Scott

Peanut Butter and Jelly: Putting 'Content Management' Back into Context
Nick Katsivelos

Service Design Goes Social
Shelley Evenson

Great User Experiences: Seamlessly Blending Technology and Design
Ben Jones, Andy Hood

Total Experience: A Design Methodology for Agencies
Conor Brady

The Elephant in the Room
Nishant Kothary

The Democratization of the Design Industry
Mike Samson, Ross Kimbarovsky

The Type We Want
Jonathan Snook

An Hour With Bill Buxton
Bill Buxton

Cloud Computing Economies of Scale
James Hamilton

The Mono Project
Miguel de Icaza

Modern Web Form Design
Luke Wroblewski

Robots at MySpace: Massive Scaling a .NET Website with the Microsoft Robotic Studio
Erik Nelson, Tony Chow, Akash Patel

10 Ways to Attack a Design Problem and Come Out Winning
Robby Ingebretsen

Principles of Microsoft Silverlight Graphics and Animation
Jeff Paries

Building a Next-Generation Web Application with Microsoft ASP.NET MVC 2 and jQuery
Nate Kohari

Using Storage in the Windows Azure Platform
Chris Auld

Creating Effective Info Viz in Microsoft Silverlight
Matthias Shapiro

Microsoft Surface Goes Social: Research Project at the University of Linz
Mario Meir-Huber

Understanding the Model-View-ViewModel Pattern
Laurent Bugnion

Build Your Own MVVM Framework
Rob Eisenberg

Securing Microsoft Silverlight Applications
Shawn Wildermuth

IronRuby for the .NET Developer
Cory Foy

Developing Natural User Interfaces with Microsoft Silverlight and WPF 4 Touch
Joshua Blake

The OpenRasta Framework for Building RESTful Applications
Kyle Baley

Building Great Standards-Based Websites for the Big Wide World with Microsoft ASP.NET 4
Tatham Oddie, Damian Edwards

Syncing Audio, Video and Animations in Microsoft Silverlight Applications
Dan Wahlin

Six Things Every jQuery Developer Must Know
Elijah Manor

Building Facebook Apps with Microsoft .NET and Deploying to Windows Azure
Jim Zimmerman

Design the Ordinary, Like the Fixie
DL Byron, Kevin Tamura

From Comp to Code: A Design Communion
Evan Sharp

Do You Speak My Language? Microsoft Translator and the Power of Collaboration
Neil Roodyn, Vikram Dendi

Building Rich and Interactive User Experiences in SharePoint
Andre Engberts

Building Platforms and Applications for the Real-Time Web
Chris Saad, Brett Slatkin, Ari Steinberg, Ryan Sarver, Lili Cheng, Dare Obasanjo

SVG: The Past, Present and Future of Vector Graphics for the Web
Patrick Dengler, Doug Schepers

Developing Multiplayer Games with Microsoft Silverlight 4
Mike Downey, Grant Skinner

Smooth Streaming Live in HD: From Camera to Screen
Michael Hanley, Scott Stanfield

Smooth Streaming Live in HD: 2010 Olympic Winter Games
Bob Cowherd, Scott Stanfield

Participating in the Web of Data with Open Standards
Christian Heilmann

Opening Up Opportunity with Twitter
Ryan Sarver

How jQuery Makes Hard Things Simple
John Resig

Adding the "Where" to the "When" of Social Applications
Raffi Krikorian

Building Large-Scale, Data-Centric Applications with Silverlight
Roman Rubin, Ramya Parthasarathy

The Tale of JavaScript. I Mean ECMAScript.
Douglas Crockford

Debugging Microsoft Silverlight Applications
Shawn Wildermuth

Building Finance Applications with Microsoft Silverlight 4
Cai Junyi

Copyright: A Cloudy Subject
Jonathan Zuck

Storm Clouds: What to Consider About Privacy Before Writing a Line of Code
Jonathan Zuck

Building the eBay Simple Lister with Silverlight
Michael Wolf

Designing Rich Experiences for Data-Centric Applications
Yoshihiro Saito, Ken Azuma

Tips and Tricks for Making Web Forms Shine with Microsoft ASP.NET 4
Jon Galloway

What's New in Microsoft ASP.NET MVC 2
Phil Haack

The HaaHa Show: Microsoft ASP.NET MVC Security with Haack and Hanselman
Scott Hanselman, Phil Haack

Deep Dive into Orchard Extensibility for CMS Developers
Renaud Paquay

Beyond File | New Company: From Cheesy Sample to Social Platform
Scott Hanselman

Improving Software Quality for the Modern Web
Euan Garden

Pumping "Iron" on the Web: IronRuby and IronPython
Jimmy Schementi

Driving Experiences via Services Using the Microsoft .NET Framework
Ron Jacobs

Designing and Delivering Scalable and Resilient Web Services
Ron Jacobs

OData: There's a Feed for That
Pablo Castro

Implementing OData: How to Create a Feed for That
Mike Flasko

Web Deployment Made Awesome: If You're Using XCopy, You're Doing It Wrong
Scott Hanselman

Accessing Data in a Microsoft .NET-Connected Web Application
Shyam Pather

Advanced Web Debugging with Fiddler
Eric Lawrence

Internet Explorer Developer Tools
Jon Seitel

Reactive Extensions for JavaScript
Erik Meijer

Building Pivot Collections
Troy Schauls, Jeff Weir

Unlocking Audio/Video Content with Speech Recognition
Behrooz Chitsaz

Incarnate: Behind the Scenes
Karsten Januszewski

Quickly Implementing New Cross-Browser Features with Ruby and Python
Hans Hugli

Keynote Day 1

Keynote Day 2

Designing Corporate Web Sites using SharePoint 2010
Paul Stubbs

Designing an Internet-Facing Web Site Using SharePoint 2010
Elisabeth Olson

Using Windows Identity Foundation for Creating Identity-Driven Experiences in Microsoft Silverlight
Caleb Baker

Microsoft Project Code Name "Dallas": Data For Your Apps
Moe Khosravy

Using Ruby on Rails to Build Windows Azure Applications
Sriram Krishnan

Lap around the Windows Azure Platform
Steve Marx

Building Web Applications with Windows Azure Storage
Brad Calder

Microsoft Silverlight and Windows Azure: A Match Made for the Web
Matt Kerner

Building Web Applications with Microsoft SQL Azure
David Robinson

Connecting Your Applications in the Cloud with Windows Azure AppFabric
Clemens Vasters

Building and Deploying Windows Azure-Based Applications with Microsoft Visual Studio 2010
Jim Nakashima

Building Offline Web Apps Using Microsoft Sync Framework
Mike Clark

Building PHP Applications using the Windows Azure Platform
Craig Kitterman, Sumit Chawla

Improving the Usability and Security of OpenID
Mike Jones

 

 

MX09 Conference

Title

Semantic HTML and Unobtrusive JavaScript
Nate Koechley

Design Fundamentals for Developers
Robby Ingebretsen

Hiking Mt. Avalon
Robby Ingebretsen, Mike Hillberg, Jaime Rodriguez

Ask The Gu

Scaling a Rich Client to Half a Billion Users
Steve Zheng

Software Entrepreneurs: Go Big with BizSpark
Julien Codorniou

Copyright Laws for Web Designers and Developers
Jonathan Zuck

Enhancing Large Windows Media Platforms with Microsoft Silverlight
Matt Smith, Robert Ames

Exposing Web Content to a Global Audience Using Machine Translation
Dr. Neil Roodyn

Sketch Flow: From Concept to Production
Celso Gomes, Christian Schormann

Improving UX through Application Lifecycle Management
Christian Thilmany, Chris Bernard

Microsoft Expression Web: No Platform Left Behind
Tyler Simpson, Steve Guttman

The Future of Microsoft Expression Blend
Douglas Olson, Christian Schormann

C# for Designers
Jennifer Smith, Fred Gerantabee

Ten Ways to Ensure RIA Failure
Anthony Franco

Deep Zoom++ : Build Dynamic Deep Zoom Applications with Open Source
Allan Li, Ken Azuma

Using Total Experience Design to Transform the Digital Building
Daren May, Paul Dawson

A Website Named Desire
Nishant Kothary

Design Prototyping: Bringing Wireframes to Life
Dan Harrelson

Escaping Flatland in Application Design: Rich User Experiences
Peter Eckert, Jeff McLean

Go Beyond Best Practices: Evolving Next Practices to Prosper in the 21st Century
Lou Carbone

Interaction Techniques Using the Wii Remote (and Other HCI Projects)
Johnny Lee

Interactive Prototyping with DHTML
Bill Scott

Touch and Gesture Computing, What You Haven't Heard
Joseph Fletcher

The Way of the Whiteboard: Persuading with Pictures
Dan Roam

Web Form Design
Luke Wrobleski

Wireframes That Work: Designing (Rich Internet) Applications
Aaron Adams

How Razorfish Lights Up Brand with Microsoft SharePoint
Tony Jones

State of the Art in Web Site Design on Microsoft SharePoint
Chris Auld

User Experience Design Patterns for Business Applications with Microsoft Silverlight …
Corrina Black

Creating a Great Experience on Digg with Windows Internet Explorer 8
Joel K. Neubeck

Windows Internet Explorer 8 in the Real World: How Is Internet Explorer 8 Used
Paul Cutsinger

Measuring Social Media Marketing
Jason Burby, Ryan Turner

Designing the Windows 7 Desktop Experience
Stephan Hoefnagels

Creating Interactivity with Microsoft Expression Blend
Peter Blois

Integrating Microsoft Expression Blend with Adobe Creative Suite
Joanna Mason

Effective Infographics with Interactivity
Joshua Allen

User Experience Design for Non-Designers
Shawn Konopinsky

Day One Keynote
Bill Buxton, Scott Guthrie

Day Two Keynote
Deborah Adler, Dean Hachamovitch

A Lap around Microsoft .NET Services
Todd Holmquist-Sutherland , John Shewchuk

Simplifying Distributed Access Control with Microsoft .NET Services
Justin Smith

Connecting Applications across Networks with Microsoft .NET Services
Clemens Vasters

Mesh-Enabled Web Applications
Arash Ghanaie-Sichanie

Live Framework and Mesh Services: Live Services for Developers
Ori Amiga

What's New in Microsoft SQL Data Services
Nigel Ellis

Overview of Windows Azure
Manuvir Das

Windows Azure Storage
Brad Calder

Building Web Applications with Windows Azure
Steve Marx

RESTful Services for the Programmable Web with Windows Communication Foundation
Ron Jacobs

Developing RESTful Services and Clients with "M"
Chris Sells, Douglas Purdy

Principles of Microsoft Silverlight Animation
Jeff Paries

Working across the Client Continuum
Laurent Bugnion

What's New in Microsoft Silverlight 3
Joe Stegman

High-Speed RIA Development with the Microsoft Silverlight Toolkit
Shawn Oster

Building Microsoft Silverlight Controls
Karen Corby

Deep Dive into Microsoft Silverlight Graphics
Seema Ramchandani

Delivering Ads to a Silverlight Media Player Application
Nicholas Brookins

Creating Media Content for Microsoft Silverlight Using Microsoft Expression Encoder
James Clarke

Using Microsoft ASP.NET MVC to Easily Extend a Web Site into the Mobile Space
Jared Eischen, John Stockton

Running PHP on Microsoft Servers and Services
Michael Joffe, Shaun Hirschman

Using Dynamic Languages to Develop Microsoft Silverlight Applications
John Lam

Choosing between ASP.NET Web Forms and MVC
Rachel Appel

The Microsoft Web Sandbox: An Open Source Framework for Developing Secure …
Scott Isaacs

Web Development Using Microsoft Visual Studio: Now and in the Future
Jeff King

<3 the New Windows Live Messenger Web Toolkit for Social Websites
Steve Gordon, Keiji Kanazawa

Protecting Online Identities
Jorgen Thelin

Standards for Aggregating Activity Feeds and Social Aggregation Services
Luke Shepard, John McCrea, Marc Canter, Kevin Marks, Monica Keller, Dare Obasanjo

Adding Microsoft Silverlight to Your Company's Skill Set
Noah Gedrich, Ken Martin

Advance Your Design with UX Design Patterns
Ambrose Little

Microsoft Xbox "Lips" and "Fable II": Multi Channel Experiences
Charles Duncan

Cloud Computing: What's in It for Me?
John Keagy

Customized Live Search for Web and Client Applications
Alessandro Catorcini

Introducing the Microsoft Virtual Earth Silverlight Map Control CTP
Chris Pendleton

Building a Rich Social Network Application
Gilbok Lee, Miho Heo

Modeling RESTful Data Services: Present and Future
Pablo Castro

Extending Your Brand to the Desktop with Windows 7
Yochay Kiriaty

See through the Clouds: Introduction to the Azure Services Platform
James Conard

What's New in Windows Presentation Foundation (WPF) 4
Mark Wilson-Thomas, Kevin Gjerstad

Building Amazing Business Centric Applications with Microsoft Silverlight 3
Brad Abrams

.NET RIA Services - Building Data-Driven Applications with Microsoft Silverlight and …
Nikhil Kothari

Consuming Web Services in Microsoft Silverlight 3
Eugene Osovetsky

Microsoft Silverlight Media End-to-End
Alex Zambelli

Microsoft ASP.NET Model View Controller (MVC): Ninja on Fire Black Belt Tips
Phil Haack

Building Out of Browser Experiences with Microsoft Silverlight 3
Mike Harsh

Microsoft ASP.NET 4.0 : What's Next?
Stephen Walther

Microsoft ASP.NET 4.0 Data Access: Patterns for Success with Web Forms
David Ebbo

Microsoft ASP.NET: Taking AJAX to the Next Level
Stephen Walther

File|New -> Company: Creating NerdDinner.com with Microsoft ASP.NET Model …
Scott Hanselman

ASP.NET MVC: America's Next Top Model View Controller Framework
Phil Haack

The Microsoft Web Platform: Starring Internet Information Services (IIS) and Your …
Crystal Hoyer, Mai-lan Tomsen Bukovec

A Lap around Windows Internet Explorer 8
Giorgio Sardo

Building High Performance Web Applications and Sites
John Hrvatin

Securing Web Applications
Eric Lawrence

Creating a "Next Generation" E-Commerce Experience
Scott Cairney, Jean-Yves Martineau

Delivering Media with Internet Information Services 7 (IIS) Media Services and …
John Bishop, John Bocharov

Developing and Deploying Applications on Internet Information Services (IIS)
Thomas Deml

Build Applications on the Microsoft Platform Using Eclipse, Java, Ruby and PHP!
Vijay Rajagopalan

Building Scalable and Available Web Applications with Microsoft Project Code Name …
Murali Krishnaprasad

Miss March and Other Distractions
Scott Stanfield

Windows Mobile 6.5 Overview
Loke Uei Tan

There's a Little Scripter in All of Us: Building a Web App for the Masses
Rob Conery

Building Data-Driven Scalable AJAX Web Pages
Jon Flanders

Caching REST with Windows Communication Foundation
Jon Flanders

Building Accessible RIAs in Microsoft Silverlight
Reed Shaffner, Chris Auld

Building Microsoft Silverlight Applications with Eclipse
Shawn Wildermuth

Building an Optimized, Graphics-Intensive Application for Microsoft Silverlight
Seema Ramchandani

When Errors Happen: Debugging Microsoft Silverlight
John Papa

Microsoft Silverlight Is Ready for Business
Ward Bell

Optimizing Performance for Microsoft Expression Encoder
James Clarke

Going Inside Microsoft Silverlight: Exploring the Core CLR
Brandon Bray

Making XML Really, Really Easy with Microsoft Visual Basic 9
Alex Turner

What's New for Microsoft Silverlight and Microsoft Windows Presentation …
Mark Wilson-Thomas

Protecting Against Internet Service Abuse
John Scarrow

Five Killer Scenarios for the Windows Live Messenger Web Toolkit
Chris Parker

Lighting Up Web and Client Applications with Microsoft Live Services
Gregory Renard

Oomph: A Microformat Toolkit
Tim Aidlin

Offline Network Detection in Microsoft Silverlight 3
Peter Smith

How'd they do it? Real App. Real Code. Two Weeks. Nothing but .NET
Scott Hanselman

How I Learned to Stop Worrying and Love the Microsoft ADO.NET Entity Framework
Pablo Castro

Using the Windows Azure Tools for Microsoft Visual Studio to Build Cloud Services
Jim Nakashima

Introducing the Microsoft Web Platform
Lauren Cooney

Automated User Interface (UI) Testing with Microsoft Visual Studio Team System 2010
Brian Keller

A Shot of Windows Live Messenger and a Pint of Microsoft Silverlight
Jordan Snyder

Improving Mobile Experiences with the Microsoft Mobile Device Browser File
Chris Woods

Search Engine Optimization (SEO) for Web Developers
Thomas Deml

Microsoft Silverlight and Windows Presentation Foundation (WPF): Sharing Skills and …
Jeff Wilcox

“Hey honey, you want to watch a movie tonight?”

“No thanks, I’m already watching Design Fundamentals for Developers, it’s a 3 hours kick ass video”

VB.NET to C# Differences

Found this great link today by Dr. Frank McCown over at Harding University Computer Science Dept from 2009.

http://www.harding.edu/fmccown/vbnet_csharp_comparison.html

 

VB.NET

Program Structure

C#

Imports System
Namespace Hello
   Class HelloWorld
      Overloads Shared Sub Main(ByVal args() As String)
         Dim name As String = "VB.NET"
'See if an argument was passed from the command line
          If args.Length = 1 Then name = args(0)
          Console.WriteLine("Hello, " & name & "!")
      End Sub
   End Class
End Namespace

using System;
namespace Hello {
   public class HelloWorld {
      public static void Main(string[] args) {
         string name = "C#";
// See if an argument was passed from the command line
         if (args.Length == 1)
            name = args[0];
         Console.WriteLine("Hello, " + name + "!");
      }
   }
}

VB.NET

Comments

C#

' Single line only
REM Single line only
''' <summary>XML comments</summary>

// Single line
/* Multiple
    line  */
/// <summary>XML comments on single line</summary>
/** <summary>XML comments on multiple lines</summary> */

VB.NET

Data Types

C#

Value Types
Boolean
Byte, SByte
Char
Short, UShort, Integer, UInteger, Long, ULong
Single, Double
Decimal
Date

Reference Types
Object
String

Initializing
Dim correct As Boolean = True
Dim b As Byte = &H2A   'hex
Dim o As Byte = &O52   'octal
Dim person As Object = Nothing
Dim name As String = "Dwight"
Dim grade As Char = "B"c
Dim today As Date = #12/31/2007 12:15:00 PM#
Dim amount As Decimal = 35.99@
Dim gpa As Single = 2.9!
Dim pi As Double = 3.14159265
Dim lTotal As Long = 123456L
Dim sTotal As Short = 123S
Dim usTotal As UShort = 123US
Dim uiTotal As UInteger = 123UI
Dim ulTotal As ULong = 123UL

Type Information
Dim x As Integer
Console.WriteLine(x.GetType())          ' Prints System.Int32
Console.WriteLine(GetType(Integer))   ' Prints System.Int32
Console.WriteLine(TypeName(x))        ' Prints Integer

Type Conversion
Dim d As Single = 3.5
Dim i As Integer = CType(d, Integer)   ' set to 4 (Banker's rounding)
i = CInt(d)  ' same result as CType
i = Int(d)    ' set to 3 (Int function truncates the decimal)

Value Types
bool
byte, sbyte
char
short, ushort, int, uint, long, ulong
float, double
decimal
DateTime   (not a built-in C# type)

Reference Types
object
string

Initializing
bool correct = true;
byte b = 0x2A;   // hex
object person = null;
string name = "Dwight";
char grade = 'B';
DateTime today = DateTime.Parse("12/31/2007 12:15:00");
decimal amount = 35.99m;
float gpa = 2.9f;
double pi = 3.14159265;
long lTotal = 123456L;
short sTotal = 123;
ushort usTotal = 123;
uint uiTotal = 123;
ulong ulTotal = 123;

Type Information
int x;
Console.WriteLine(x.GetType());              // Prints System.Int32
Console.WriteLine(typeof(int));               // Prints System.Int32
Console.WriteLine(x.GetType().Name);   // prints Int32

Type Conversion
float d = 3.5f;
int i = (int)d;   // set to 3  (truncates decimal)

VB.NET

Constants

C#

Const MAX_STUDENTS As Integer = 25

' Can set to a const or var; may be initialized in a constructor
ReadOnly MIN_DIAMETER As Single = 4.93

const int MAX_STUDENTS = 25;

// Can set to a const or var; may be initialized in a constructor
readonly float MIN_DIAMETER = 4.93f;

VB.NET

Enumerations

C#

Enum Action
  Start 
  [Stop]   ' Stop is a reserved word
  Rewind
  Forward
End Enum
Enum Status
  Flunk = 50
  Pass = 70
  Excel = 90
End Enum

Dim a As Action = Action.Stop
If a <> Action.Start Then _
   Console.WriteLine(a.ToString & " is " & a)     ' Prints "Stop is 1"
Console.WriteLine(Status.Pass)     ' Prints 70
Console.WriteLine(Status.Pass.ToString())     ' Prints Pass

enum Action {Start, Stop, Rewind, Forward};
enum Status {Flunk = 50, Pass = 70, Excel = 90};
Action a = Action.Stop;
if (a != Action.Start)
  Console.WriteLine(a + " is " + (int) a);    // Prints "Stop is 1"
Console.WriteLine((int) Status.Pass);    // Prints 70
Console.WriteLine(Status.Pass);      // Prints Pass

VB.NET

Operators

C#

Comparison
=  <  >  <=  >=  <>

Arithmetic
+  -  *  /
Mod
(integer division)
(raise to a power)

Assignment
=  +=  -=  *=  /=  \=  ^=  <<=  >>=  &=

Bitwise
And   Or   Xor   Not   <<   >>

Logical
AndAlso   OrElse   And   Or   Xor   Not

Note: AndAlso and OrElse perform short-circuit logical evaluations

String Concatenation
&

Comparison
==  <  >  <=  >=  !=

Arithmetic
+  -  *  /
(mod)
(integer division if both operands are ints)
Math.Pow(x, y)

Assignment
=  +=  -=  *=  /=   %=  &=  |=  ^=  <<=  >>=  ++  --

Bitwise
&   |   ^   ~   <<   >>

Logical
&&   ||   &   |   ^   !

Note: && and || perform short-circuit logical evaluations

String Concatenation
+

VB.NET

Choices

C#

' Ternary/Conditional operator (Iff evaluates 2nd and 3rd expressions)
greeting = If(age < 20, "What's up?", "Hello")

' One line doesn't require "End If"
If age < 20 Then greeting = "What's up?"
If age < 20 Then greeting = "What's up?" Else greeting = "Hello"

' Use : to put two commands on same line
If x <> 100 AndAlso y < 5 Then x *= 5 : y *= 2 

' Preferred
If x <> 100 AndAlso y < 5 Then
  x *= 5
  y *= 2
End If

' To break up any long single line use _
If whenYouHaveAReally < longLine And _
  itNeedsToBeBrokenInto2 > Lines Then _
  UseTheUnderscore(charToBreakItUp)

'If x > 5 Then
  x *= y
ElseIf x = 5 OrElse y Mod 2 = 0 Then
  x += y
ElseIf x < 10 Then
  x -= y
Else
  x /= y
End If

Select Case color   ' Must be a primitive data type
Case "pink", "red"
    r += 1
Case "blue"
    b += 1
Case "green"
    g += 1
Case Else
    other += 1
End Select

// Ternary/Conditional operator
greeting = age < 20 ? "What's up?" : "Hello";

if (age < 20)
  greeting = "What's up?";
else
  greeting = "Hello";

// Multiple statements must be enclosed in {}
if (x != 100 && y < 5) {   
  x *= 5;
  y *= 2;
}

No need for _ or : since ; is used to terminate each statement.


if
(x > 5)
  x *= y;
else if (x == 5 || y % 2 == 0)
  x += y;
else if (x < 10)
  x -= y;
else
  x /= y;

// Every case must end with break or goto case
switch (color) {                          // Must be integer or string
case "pink":
case "red":    r++;    break;
case "blue":   b++;   break;
case "green": g++;   break;
default:    other++;  break; // break necessary on default
}

VB.NET

Loops

C#

Pre-test Loops:

While c < 10
  c += 1
End While

Do Until c = 10 
  c += 1
Loop

Do While c < 10
  c += 1
Loop

For c = 2 To 10 Step 2
  Console.WriteLine(c)
Next


Post-test Loops:

Do
  c += 1
Loop While c < 10

Do
  c += 1
Loop Until c = 10

'  Array or collection looping
Dim names As String() = {"Fred", "Sue", "Barney"}
For Each s As String In names
  Console.WriteLine(s)
Next

' Breaking out of loops
Dim i As Integer = 0
While (True)
  If (i = 5) Then Exit While
  i += 1
End While

' Continue to next iteration
For i = 0 To 4
  If i < 4 Then Continue For
  Console.WriteLine(i)   ' Only prints 4
Next

Pre-test Loops:

// no "until" keyword
while (c < 10)
  c++;
for (c = 2; c <= 10; c += 2)
  Console.WriteLine(c);

Post-test Loop:
do
  c++;
while (c < 10);

// Array or collection looping
string[] names = {"Fred", "Sue", "Barney"};
foreach (string s in names)
  Console.WriteLine(s);

// Breaking out of loops
int i = 0;
while (true) {
  if (i == 5)
break;
  i++;
}

// Continue to next iteration
for (i = 0; i < 5; i++) {
  if (i < 4)
continue;
  Console.WriteLine(i);   // Only prints 4
}

VB.NET

Arrays

C#

Dim nums() As Integer = {1, 2, 3} 
For i As Integer = 0 To nums.Length - 1
  Console.WriteLine(nums(i))
Next
' 4 is the index of the last element, so it holds 5 elements
Dim names(4) As String
names(0) = "David"
names(5) = "Bobby"  ' Throws System.IndexOutOfRangeException
' Resize the array, keeping the existing values (Preserve is optional)
ReDim Preserve names(6)

Dim twoD(rows-1, cols-1) As Single
twoD(2, 0) = 4.5
Dim jagged()() As Integer = { _
  New Integer(4) {}, New Integer(1) {}, New Integer(2) {} }
jagged(0)(4) = 5

int[] nums = {1, 2, 3};
for (int i = 0; i < nums.Length; i++)
  Console.WriteLine(nums[i]);
// 5 is the size of the array
string[] names = new string[5];
names[0] = "David";
names[5] = "Bobby";   // Throws System.IndexOutOfRangeException
// C# can't dynamically resize an array.  Just copy into new array.
string[] names2 = new string[7];
Array.Copy(names, names2, names.Length);   // or names.CopyTo(names2, 0);

float[,] twoD = new float[rows, cols];
twoD[2,0] = 4.5f;

int[][] jagged = new int[3][] {
  new int[5], new int[2], new int[3] };
jagged[0][4] = 5;

VB.NET

Functions

C#

' Pass by value (in, default), reference (in/out), and reference (out)
Sub TestFunc(ByVal x As Integer, ByRef y As Integer, ByRefz As Integer)
  x += 1
  y += 1
  z = 5
End Sub

Dim a = 1, b = 1, c As Integer   ' c set to zero by default
TestFunc(a, b, c)
Console.WriteLine("{0} {1} {2}", a, b, c)   ' 1 2 5

' Accept variable number of arguments
Function Sum(ByVal ParamArray nums As Integer()) As Integer
  Sum = 0 
  For Each i As Integer In nums
    Sum += i
  Next
End Function ' Or use Return statement like C#
Dim total As Integer = Sum(4, 3, 2, 1)   ' returns 10

' Optional parameters must be listed last and must have a default value
Sub SayHello(ByVal name As String, Optional ByVal prefix As String = "")
  Console.WriteLine("Greetings, " & prefix & " " & name)
End Sub
SayHello("Strangelove", "Dr.")
SayHello("Madonna")

// Pass by value (in, default), reference (in/out), and reference (out)
void TestFunc(int x, ref int y, out int z) {
  x++;  
  y++;
  z = 5;
}

int a = 1, b = 1, c;  // c doesn't need initializing
TestFunc(a, ref b, out c);
Console.WriteLine("{0} {1} {2}", a, b, c);  // 1 2 5

// Accept variable number of arguments
int Sum(params int[] nums) {
  int sum = 0;
  foreach (int i in nums)
    sum += i;
  return sum;
}

int total = Sum(4, 3, 2, 1);   // returns 10

/* C# doesn't support optional arguments/parameters.  Just create two different versions of the same function. */
void SayHello(string name, string prefix) {
  Console.WriteLine("Greetings, " + prefix + " " + name);

void SayHello(string name) {
  SayHello(name, "");
}

VB.NET

Strings

C#

Special character constants (all also accessible from ControlChars class)
vbCrLf, vbCr, vbLf, vbNewLine
vbNullString
vbTab
vbBack
vbFormFeed
vbVerticalTab
""

' String concatenation (use & or +)
Dim school As String = "Harding" & vbTab
school = school & "University" ' school is "Harding (tab) University"

' Chars
Dim letter As Char = school.Chars(0)   ' letter is H
letter = Convert.ToChar(65)                ' letter is A
letter = Chr(65)                                 ' same thing
Dim word() As Char = school.ToCharArray() ' word holds Harding

' No string literal operator
Dim msg As String = "File is c:\temp\x.dat"

' String comparison
Dim mascot As String = "Bisons"
If (mascot = "Bisons") Then   ' true
If (mascot.Equals("Bisons")) Then   ' true
If (mascot.ToUpper().Equals("BISONS")) Then  ' true
If (mascot.CompareTo("Bisons") = 0) Then   ' true

' String matching with Like - Regex is more powerful
If ("John 3:16" Like "Jo[Hh]? #:*") Then   'true

' Substring
s = mascot.Substring(2, 3)) ' s is "son"

' Replacement
s = mascot.Replace("sons", "nomial")) ' s is "Binomial"

' Split
Dim names As String = "Frank,Becky,Ethan,Braden"
Dim parts() As String = names.Split(",".ToCharArray())   ' One name in each slot

' Date to string
Dim dt As New DateTime(1973, 10, 12)
Dim s As String = "My birthday: " & dt.ToString("MMM dd, yyyy")   ' Oct 12, 1973

' Integer to String
Dim x As Integer = 2
Dim y As String = x.ToString()     ' y is "2"

' String to Integer
Dim x As Integer = Convert.ToInt32("-5")     ' x is -5

' Mutable string
Dim buffer As New System.Text.StringBuilder("two ")
buffer.Append("three ")
buffer.Insert(0, "one ")
buffer.Replace("two", "TWO")
Console.WriteLine(buffer)         ' Prints "one TWO three"

Escape sequences
\r    // carriage-return
\n    // line-feed
\t    // tab
\\    // backslash
\"    // quote

// String concatenation
string school = "Harding\t";
school = school + "University";   // school is "Harding (tab) University"

// Chars
char letter = school[0];            // letter is H
letter = Convert.ToChar(65);     // letter is A
letter = (char)65;                    // same thing
char[] word = school.ToCharArray();   // word holds Harding

// String literal
string msg = @"File is c:\temp\x.dat";
// same as
string msg = "File is c:\\temp\\x.dat";

// String comparison
string mascot = "Bisons";
if (mascot == "Bisons")    // true
if (mascot.Equals("Bisons"))   // true
if (mascot.ToUpper().Equals("BISONS"))   // true
if (mascot.CompareTo("Bisons") == 0)    // true

// String matching - No Like equivalent, use Regex

// Substring
s = mascot.Substring(2, 3))     // s is "son"

// Replacement
s = mascot.Replace("sons", "nomial"))     // s is "Binomial"

// Split
string names = "Frank,Becky,Ethan,Braden";
string[] parts = names.Split(",".ToCharArray());   // One name in each slot

// Date to string
DateTime dt = new DateTime(1973, 10, 12);
string s = dt.ToString("MMM dd, yyyy");     // Oct 12, 1973

// int to string
int x = 2;
string y = x.ToString();     // y is "2"

// string to int
int x = Convert.ToInt32("-5");     // x is -5

// Mutable string
System.Text.StringBuilder buffer = new System.Text.StringBuilder("two ");
buffer.Append("three ");
buffer.Insert(0, "one ");
buffer.Replace("two", "TWO");
Console.WriteLine(buffer);     // Prints "one TWO three"

VB.NET

Regular Expressions

C#

Imports System.Text.RegularExpressions

' Match a string pattern
Dim r As New Regex("j[aeiou]h?. \d:*", RegexOptions.IgnoreCase Or _
        RegexOptions.Compiled)
If (r.Match("John 3:16").Success) Then   'true
    Console.WriteLine("Match")
End If

' Find and remember all matching patterns
Dim s As String = "My number is 305-1881, not 305-1818."
Dim r As New Regex("(\d+-\d+)")
Dim m As Match = r.Match(s)     ' Matches 305-1881 and 305-1818
While m.Success
    Console.WriteLine("Found number: " & m.Groups(1).Value & " at position " _
            & m.Groups(1).Index.ToString)
    m = m.NextMatch()
End While

' Remeber multiple parts of matched pattern
Dim r As New Regex("(\d\d):(\d\d) (am|pm)")
Dim m As Match = r.Match("We left at 03:15 pm.")
If m.Success Then
    Console.WriteLine("Hour: " & m.Groups(1).ToString)       ' 03
    Console.WriteLine("Min: " & m.Groups(2).ToString)         ' 15
    Console.WriteLine("Ending: " & m.Groups(3).ToString)   ' pm
End If

' Replace all occurrances of a pattern
Dim r As New Regex("h\w+?d", RegexOptions.IgnoreCase)
Dim s As String = r.Replace("I heard this was HARD!", "easy")  ' I easy this was easy!

' Replace matched patterns
Dim s As String = Regex.Replace("123 < 456", "(\d+) . (\d+)", "$2 > $1")   ' 456 > 123

' Split a string based on a pattern
Dim names As String = "Frank, Becky, Ethan, Braden"
Dim r As New Regex(",\s*")
Dim parts() As String = r.Split(names)   ' One name in each slot

using System.Text.RegularExpressions;

// Match a string pattern
Regex r = new Regex(@"j[aeiou]h?. \d:*", RegexOptions.IgnoreCase |
        RegexOptions.Compiled);
if (r.Match("John 3:16").Success)   // true
    Console.WriteLine("Match");

// Find and remember all matching patterns
string s = "My number is 305-1881, not 305-1818.";
Regex r = new Regex("(\\d+-\\d+)");
// Matches 305-1881 and 305-1818
for (Match m = r.Match(s); m.Success; m = m.NextMatch())
    Console.WriteLine("Found number: " + m.Groups[1] + " at position " +
        m.Groups[1].Index);

// Remeber multiple parts of matched pattern
Regex r = new Regex("@(\d\d):(\d\d) (am|pm)");
Match m = r.Match("We left at 03:15 pm.");
if (m.Success) {
    Console.WriteLine("Hour: " + m.Groups[1]);       // 03
    Console.WriteLine("Min: " + m.Groups[2]);         // 15
    Console.WriteLine("Ending: " + m.Groups[3]);   // pm
}

// Replace all occurrances of a pattern
Regex r = new Regex("h\\w+?d", RegexOptions.IgnoreCase);
string s = r.Replace("I heard this was HARD!", "easy"));   // I easy this was easy!

// Replace matched patterns
string s = Regex.Replace("123 < 456", @"(\d+) . (\d+)", "$2 > $1");   // 456 > 123

// Split a string based on a pattern
string names = "Frank, Becky, Ethan, Braden";
Regex r = new Regex(@",\s*");
string[] parts = r.Split(names);   // One name in each slot

VB.NET

Exception Handling

C#

' Throw an exception
Dim ex As New Exception("Something is really wrong.")
Throw  ex

' Catch an exception
Try
  y = 0
  x = 10 / y
Catch ex As Exception When y = 0 ' Argument and When is optional
  Console.WriteLine(ex.Message)
Finally
  Beep()
End Try

' Deprecated unstructured error handling
On Error GoTo MyErrorHandler
...
MyErrorHandler: Console.WriteLine(Err.Description)

// Throw an exception
Exception up = new Exception("Something is really wrong.");
throw up;  // ha ha

// Catch an exception
try
  y = 0;
  x = 10 / y;
}
catch (Exception ex) {   // Argument is optional, no "When" keyword
  Console.WriteLine(ex.Message);
}
finally {
  Microsoft.VisualBasic.Interaction.Beep();
}

VB.NET

Namespaces

C#

Namespace Harding.Compsci.Graphics 
  ...
End Namespace

' or

Namespace Harding
Namespace Compsci
Namespace Graphics 
      ...
End Namespace
End Namespace
End Namespace

Imports Harding.Compsci.Graphics

namespace Harding.Compsci.Graphics {
  ...
}

// or

namespace Harding {
namespace Compsci {
namespace Graphics {
      ...
    }
  }
}

using Harding.Compsci.Graphics;

VB.NET

Classes / Interfaces

C#

Accessibility keywords
Public
Private
Friend                   
Protected
Protected Friend
Shared

' Inheritance
Class FootballGame
Inherits Competition
  ...
End Class

' Interface definition
Interface IAlarmClock 
  ...
End Interface

// Extending an interface
Interface IAlarmClock
Inherits IClock
  ...
End Interface

// Interface implementation
Class WristWatch 
Implements IAlarmClock, ITimer 
   ...
End Class

Accessibility keywords
public
private
internal
protected
protected internal
static

// Inheritance
class FootballGame : Competition {
  ...
}


// Interface definition
interface IAlarmClock {
  ...
}

// Extending an interface
interface IAlarmClock : IClock {
  ...
}


// Interface implementation
class WristWatch : IAlarmClock, ITimer {
   ...
}

VB.NET

Constructors / Destructors

C#

Class SuperHero
  Private _powerLevel As Integer
  Public Sub New()
    _powerLevel = 0
  End Sub
  Public Sub New(ByVal powerLevel As Integer)
    Me._powerLevel = powerLevel
  End Sub
  Protected Overrides Sub Finalize() 
' Desctructor code to free unmanaged resources
    MyBase.Finalize()
  End Sub
End Class

class SuperHero {
  private int _powerLevel;
  public SuperHero() {
     _powerLevel = 0;
  }
  public SuperHero(int powerLevel) {
    this._powerLevel= powerLevel; 
  }
~SuperHero() {
// Destructor code to free unmanaged resources.
    // Implicitly creates a Finalize method
  }
}

VB.NET

Using Objects

C#

Dim hero As SuperHero = New SuperHero
' or
Dim hero As New SuperHero

With hero
  .Name = "SpamMan"
  .PowerLevel = 3
End With

hero.Defend("Laura Jones")
hero.Rest()     ' Calling Shared method
' or
SuperHero.Rest()

Dim hero2 As SuperHero = hero  ' Both reference the same object
hero2.Name = "WormWoman"
Console.WriteLine(hero.Name)   ' Prints WormWoman

hero = Nothing ' Free the object

If hero Is Nothing Then _
  hero = New SuperHero

Dim obj As Object = New SuperHero
If TypeOf obj Is SuperHero Then _
  Console.WriteLine("Is a SuperHero object.")

' Mark object for quick disposal
Using reader As StreamReader = File.OpenText("test.txt")
  Dim line As String = reader.ReadLine()
  While Not line Is Nothing
    Console.WriteLine(line)
    line = reader.ReadLine()
  End While
End Using

SuperHero hero = new SuperHero();

// No "With" construct
hero.Name = "SpamMan";
hero.PowerLevel = 3;

hero.Defend("Laura Jones");
SuperHero.Rest();   // Calling static method

SuperHero hero2 = hero;   // Both reference the same object
hero2.Name = "WormWoman";
Console.WriteLine(hero.Name);   // Prints WormWoman

hero = null ;   // Free the object

if (hero == null)
  hero = new SuperHero();

Object obj = new SuperHero(); 
if (obj is SuperHero)
  Console.WriteLine("Is a SuperHero object.");

// Mark object for quick disposal
using (StreamReader reader = File.OpenText("test.txt")) {
  string line;
  while ((line = reader.ReadLine()) != null)
    Console.WriteLine(line);
}

VB.NET

Structs

C#

Structure StudentRecord
  Public name As String
  Public gpa As Single
  Public Sub New(ByVal name As String, ByVal gpa As Single)
    Me.name = name
    Me.gpa = gpa
  End Sub
End Structure

Dim stu As StudentRecord = New StudentRecord("Bob", 3.5)
Dim stu2 As StudentRecord = stu  
stu2.name = "Sue"
Console.WriteLine(stu.name)    ' Prints Bob
Console.WriteLine(stu2.name)  ' Prints Sue

struct StudentRecord {
  public string name;
  public float gpa;
  public StudentRecord(string name, float gpa) {
    this.name = name;
    this.gpa = gpa;
  }
}

StudentRecord stu = new StudentRecord("Bob", 3.5f);
StudentRecord stu2 = stu;  
stu2.name = "Sue";
Console.WriteLine(stu.name);    // Prints Bob
Console.WriteLine(stu2.name);   // Prints Sue

VB.NET

Properties

C#

Private _size As Integer
Public Property Size() As Integer
Get
    Return _size
End Get
Set (ByVal Value As Integer)
    If Value < 0 Then
      _size = 0
    Else
      _size = Value
    End If
End Set
End Property

foo.Size += 1

private int _size;
public int Size {
get {
    return _size;
  }
set {
    if (value < 0)
      _size = 0;
    else
      _size = value;
  }
}

foo.Size++;

VB.NET

Delegates / Events

C#

Delegate Sub MsgArrivedEventHandler(ByVal message As String)

Event MsgArrivedEvent As MsgArrivedEventHandler

' or to define an event which declares a delegate implicitly
Event MsgArrivedEvent(ByVal message As String)

AddHandler MsgArrivedEvent, AddressOfMy_MsgArrivedCallback
' Won't throw an exception if obj is Nothing
RaiseEvent MsgArrivedEvent("Test message")
RemoveHandler MsgArrivedEvent, AddressOfMy_MsgArrivedCallback

Imports System.Windows.Forms

Dim WithEvents MyButton As Button   ' WithEvents can't be used on local variable
MyButton = New Button

Private Sub MyButton_Click(ByVal sender As System.Object, _
  ByVal e As System.EventArgs) Handles MyButton.Click
  MessageBox.Show(Me, "Button was clicked", "Info", _
    MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub

delegate void MsgArrivedEventHandler(string message);

event MsgArrivedEventHandler MsgArrivedEvent;

// Delegates must be used with events in C#
MsgArrivedEvent += new MsgArrivedEventHandler(My_MsgArrivedEventCallback);
MsgArrivedEvent("Test message");    // Throws exception if obj is null
MsgArrivedEvent -= new MsgArrivedEventHandler(My_MsgArrivedEventCallback);

using System.Windows.Forms;

Button MyButton = new Button(); 
MyButton.Click += new System.EventHandler(MyButton_Click);

private void MyButton_Click(object sender, System.EventArgs e) {
  MessageBox.Show(this, "Button was clicked", "Info",
    MessageBoxButtons.OK, MessageBoxIcon.Information);
}

VB.NET

Console I/O

C#

Console.Write("What's your name? ")
Dim name As String = Console.ReadLine()
Console.Write("How old are you? ")
Dim age As Integer = Val(Console.ReadLine())
Console.WriteLine("{0} is {1} years old.", name, age) 
' or
Console.WriteLine(name & " is " & age & " years old.")
Dim c As Integer
c = Console.Read()    ' Read single char
Console.WriteLine(c)   ' Prints 65 if user enters "A"

Console.Write("What's your name? ");
string name = Console.ReadLine();
Console.Write("How old are you? ");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("{0} is {1} years old.", name, age);
// or
Console.WriteLine(name + " is " + age + " years old.");

int c = Console.Read();  // Read single char
Console.WriteLine(c);    // Prints 65 if user enters "A"

VB.NET

File I/O

C#

Imports System.IO

' Write out to text file
Dim writer As StreamWriter = File.CreateText("c:\myfile.txt")
writer.WriteLine("Out to file.")
writer.Close()

' Read all lines from text file
Dim reader As StreamReader = File.OpenText("c:\myfile.txt")
Dim line As String = reader.ReadLine()
While Not line Is Nothing
  Console.WriteLine(line)
  line = reader.ReadLine()
End While
reader.Close()

' Write out to binary file
Dim str As String = "Text data"
Dim num As Integer = 123
Dim binWriter As NewBinaryWriter(File.OpenWrite("c:\myfile.dat")) 
binWriter.Write(str) 
binWriter.Write(num) 
binWriter.Close()

' Read from binary file
Dim binReader As NewBinaryReader(File.OpenRead("c:\myfile.dat"))
str = binReader.ReadString()
num = binReader.ReadInt32()
binReader.Close()

using System.IO;

// Write out to text file
StreamWriter writer = File.CreateText("c:\\myfile.txt");
writer.WriteLine("Out to file.");
writer.Close();

// Read all lines from text file
StreamReader reader = File.OpenText("c:\\myfile.txt");
string line = reader.ReadLine();
while (line != null) {
  Console.WriteLine(line);
  line = reader.ReadLine();
}
reader.Close();

// Write out to binary file
string str = "Text data";
int num = 123;
BinaryWriter binWriter = new BinaryWriter(File.OpenWrite("c:\\myfile.dat"));
binWriter.Write(str);
binWriter.Write(num);
binWriter.Close();

// Read from binary file
BinaryReader binReader = new BinaryReader(File.OpenRead("c:\\myfile.dat"));
str = binReader.ReadString();
num = binReader.ReadInt32();
binReader.Close();

Sending Generic.List collection back to WCF ObservableCollection

Found a good article and helped with a problem I was having, trying to send a list of collection back to a WCF service that was set to accept Observable Collections. 

Source: http://smehrozalam.wordpress.com/2009/01/18/ienumerabletoobservablecollection/

In WPF/Silverlight, binding UI objects such as DataGrid or ListBox to collections is typically done using an ObservableCollectioninstead of the generic List object. This way, our UI is automatically synchronized since the observable collection provides event notification to WPF data binding engine whenever items are added, removed, or when the whole list is refreshed. The LINQ extension methods that return a collection actually return IEnumerable<T>. The .NET framework for Silverlight provides built-in extension methods to convert IEnumerable<T> to List<T> and Array<T> but there’s no method available to convert the collection to ObservableCollection<T>(WPF developers can simply use this constructor overload) . So here’s one you may find useful:

  1. Public Static Class CollectionExtensions
  2. {
  3.     public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> enumerableList)
  4.     {
  5.         if (enumerableList != null)
  6.         {
  7.             //create an emtpy observable collection object
  8.             var observableCollection = new ObservableCollection<T>();
  9.  
  10.             //loop through all the records and add to observable collection object
  11.             foreach (var item in enumerableList)
  12.                 observableCollection.Add(item);
  13.  
  14.             //return the populated observable collection
  15.             return observableCollection;
  16.         }
  17.         return null;
  18.     }
  19. }

Extension methods are very powerful and I am planning to post an example demonstrating their potential.

I’ve converted the above example to VB.Net version for you to copy.

Public Shared Function ToObservableCollection(Of T)(ByVal enumerableList As IEnumerable(Of T)) As ObservableCollection(Of T)
    If enumerableList IsNot Nothing Then
        'create an emtpy observable collection object
        Dim observableCollection As New ObservableCollection(Of T)()

        'loop through all the records and add to observable collection object
        For Each item As T In enumerableList
            observableCollection.Add(item)
        Next

        'return the populated observable collection
        Return observableCollection
    End If
    Return Nothing
End Function

Now you can call your List and send it back as a ObservableCollection

Mapping a DataTable to an Object Class. Like a homemade Linq to SQL. Send over WCF to SilverLight

Application Foundation

An application I work has architecture in a way where we have a Class object that represents each table. So for example we might have a “Customer” table in the database. So our class would be something like..

Customer.vb class file…

Public Class Customer

    Private _FirstName As String = String.Empty
    Public Property FirstName() As String
        Get
            Return _FirstName
        End Get
        Set(ByVal value As String)
            _FirstName = value
        End Set
    End Property

    Private _LastName As String = String.Empty
    Public Property LastName() As String
        Get
            Return _LastName
        End Get
        Set(ByVal value As String)
            _LastName = value
        End Set
    End Property

End Class

In this class is a function to say list all customers, we call this “GetList” method. You might use another way to bring back a list of data. Ideally now we’d want to bring back Enumerable Lists, but the app was already structured for DataSets and DataTables. So I was trying to reuse what we had.

Customer.vb class file

Public Function GetList() As Data.DataTable
    Dim oDS As Data.DataSet
    Try
        oDS = DataAccess.SqlHelper.ExecuteDataset(_ConnectionString, Data.CommandType.StoredProcedure, "CustomerGetList")
        Return oDS.Tables(0)
    Catch ex As Exception
        Throw ex
    Finally
        oDS = Nothing
    End Try
End Function

So on our pages we might do something like this…

Default.aspx.vb

Protected Sub Button1_ClickSave()
    Dim oCustomer As New Customer
    oCustomer.FirstName = "Fred"
    oCustomer.LastName = "Mastro"
    oCustomer.SaveToDB()

    GridView1.DataSource = oCustomer.GetList()
    GridView1.DataBind()

    oCustomer = Nothing

End Sub

 

And this returns a nice DataTable and populates the grid. Great!

Problem Areas over WCF to SliverLight

I was working on a SilverLight application that would talk to an existing business application, to pull back and list records.  I had to use a Service, so I went with WCF since RIA.Net is not in production yet.  The problem was that DataTables can not be serialized and set over WCF to SilverLight.  So I tried messing with Linq to SQL to pull data back and populate classes I already had, but LinqTables are not serializable either, and instead of modifying all the Linq classes generated in my class I wanted to find an easier solution.

DataTable to List(Of Customer) Solution

I can across these two posts: Datatable to List of Objects Mapper and Creating datarow to object mapper and was amazed. Using reflection Chris Rock (lol) was able to read the properties of the object and map each column of the datatable to the desired property of the object. This is what I’m looking to do.  This would manually mimic Linq type functionality. The Bulk of the code is this

My Helper.vb class file

  1.  
  2. Public Class Helper
  3.  
  4.     Public Function MapDatarowToObject(Of T)(ByVal dr As DataRow) As T
  5.         Try
  6.  
  7.             If dr Is Nothing Then
  8.                 Return Nothing
  9.             End If
  10.  
  11.             Dim instance As T = Activator.CreateInstance(Of T)()
  12.  
  13.             Dim properties() As Reflection.PropertyInfo = instance.GetType().GetProperties()
  14.  
  15.             If (properties.Length > 0) Then
  16.                 For Each propertyObject As Reflection.PropertyInfo In properties
  17.  
  18.                     Dim valueSet As Boolean = False
  19.  
  20.                     For Each attributeObject As Object In propertyObject.GetCustomAttributes(False)
  21.  
  22.                         If attributeObject.GetType() Is GetType(MapperColumn) Then
  23.                             Dim columnAttributeObject As MapperColumn = CType(attributeObject, MapperColumn)
  24.  
  25.                             If (columnAttributeObject.ColumnName <> String.Empty) Then
  26.  
  27.                                 If dr.Table.Columns.Contains(columnAttributeObject.ColumnName) AndAlso Not dr(columnAttributeObject.ColumnName) Is DBNull.Value Then
  28.                                     propertyObject.SetValue(instance, dr(columnAttributeObject.ColumnName), Nothing)
  29.                                     valueSet = True
  30.  
  31.                                 End If
  32.  
  33.                             End If
  34.                         End If
  35.                     Next
  36.  
  37.                     If Not valueSet Then
  38.                         If dr.Table.Columns.Contains(propertyObject.Name) AndAlso Not dr(propertyObject.Name) Is DBNull.Value Then
  39.                             propertyObject.SetValue(instance, dr(propertyObject.Name), Nothing)
  40.                         End If
  41.                     End If
  42.  
  43.                 Next
  44.             End If
  45.  
  46.             Return instance
  47.         Catch ex As Exception
  48.             Throw ex
  49.         End Try
  50.     End Function
  51.  
  52.     Public Function MapDataTableToList(Of T)(ByVal dt As DataTable) As Collections.Generic.IList(Of T)
  53.         If dt Is Nothing Then
  54.             Return Nothing
  55.         End If
  56.  
  57.         Dim list As IList(Of T) = New List(Of T)
  58.  
  59.         For Each dr As DataRow In dt.Rows
  60.             list.Add(MapDatarowToObject(Of T)(dr))
  61.         Next
  62.  
  63.         Return list
  64.     End Function
  65.  
  66. End Class
  67.  
  68. <AttributeUsage(AttributeTargets.Property)> _
  69. Public Class MapperColumn
  70.     Inherits Attribute
  71.  
  72.     Private mColumnName As String
  73.  
  74.     Public Sub New(ByVal columnName As String)
  75.         mColumnName = columnName
  76.     End Sub
  77.  
  78.     Public Property ColumnName() As String
  79.         Get
  80.             Return mColumnName
  81.         End Get
  82.         Set(ByVal value As String)
  83.             mColumnName = value
  84.         End Set
  85.     End Property
  86.  
  87. End Class

Using Mapper in WCF

Now in my WCF Service methods I can just instantiate Customers like I always do in the normal application and apply the new Mapper method to get a List of the class objects.

WCFServiceMethods.vb file (which is code-behind to WCFServiceMethods.svc)

  1. Imports System.ServiceModel
  2. Imports System.ServiceModel.Activation
  3. Imports System.Runtime.Serialization 'For DataContract
  4. Imports System.Collections.Generic
  5.  
  6. <ServiceContract(Namespace:="")> _
  7. <ServiceBehavior(IncludeExceptionDetailInFaults:=True)> _
  8. <AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
  9. Public Class WCFServiceMethods
  10.     <OperationContract()> _
  11.     Public Function GetCustomers() As Collections.Generic.List(Of Customer)
  12.         Dim oCustomer As New Customer
  13.  
  14.         Dim Customers As Collections.Generic.List(Of Customer)
  15.         Customers = Helper.MapDataTableToList(Of Customer)(oCustomer.GetList())
  16.  
  17.         oCustomer = Nothing
  18.         Return Customers
  19.  
  20.     End Function
  21. End Class

You’ll see in Line 15, I can take the DataTable and now create a List(Of Customer) object, which is serializable and send it over the wire.

Applying it in SilverLight or Other Application that uses your WCF Service

Assuming you referenced your WCF Service.. Now on my SilverLight app on a button click I can get the List of Customers and show it natively in a datagrid.

MainPage.xaml code-behind

Private Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnSearch.Click
    Dim oWCFProxy As New WCFService.WCFServiceClient

    AddHandler oWCFProxy.GetCustomers, AddressOf oWCFProxy_GetCustomersCompleted
    oWCFProxy.GetCustomersAsync()

    oWCFProxy = Nothing

End Sub

Private Sub oWCFProxy_GetCustomersCompleted(ByVal sender As Object, ByVal e As WCFService.GetCustomersCompletedEventArgs)
    Dim Customers As Collections.ObjectModel.Collection(Of oWCFProxy.Customer)
    Customers = e.Result

    DataGrid1.ItemsSource = Customers
End Sub

Problem Area With Mapper Casting Types and Solution

So with all that above you should have enough to re-create all this. Read through Chris’ posts because it does a good job of explaining the mapper.  I ran into a problem with the mapper though on line 39. Problem is when it tries to map data from the database, it all comes back as a string, and you don’t know until run-time what System.Type you need, so you can’t CType or DirectCast by using System.Type.GetType(), so I had to create a crappy function to Throw ex check every possible combination. This the best way? I sure hope it isn’t. Hope to find a better solution for it but was pressed for time.

So what was my crappy solution? I don’t even want to post it haha. I swapped out line 39 and 28 with the a call to this method of 1531 lines of code.

Private Sub TryCastTypeToPropertyType(ByRef propertyObject As Reflection.PropertyInfo, ByRef instance As Object, ByRef dr As DataRow, ByRef ColumnName As String)

Try
'Try to Default Types
propertyObject.SetValue(instance, dr(ColumnName), Nothing)
Catch exDefault1 As InvalidCastException
Try
'Try to String
propertyObject.SetValue(instance, CType(dr(ColumnName), String), Nothing)
Catch exString1 As InvalidCastException
'Try to Integer
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Integer), Nothing)
Catch exInt32a As ArgumentException
'Try to DateTime
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), DateTime), Nothing)
Catch exDate1 As ArgumentException
'Try to Decimal
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Decimal), Nothing)
Catch exDecimal1 As ArgumentException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
Catch exDecimal2 As InvalidCastException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
End Try
Catch exDate2 As InvalidCastException
'Try to Decimal
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Decimal), Nothing)
Catch exDecimal1 As ArgumentException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
Catch exDecimal2 As InvalidCastException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
End Try
End Try
Catch exInt32b As InvalidCastException
'Try to DateTime
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), DateTime), Nothing)
Catch exDate1 As ArgumentException
'Try to Decimal
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Decimal), Nothing)
Catch exDecimal1 As ArgumentException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
Catch exDecimal2 As InvalidCastException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
End Try
Catch exDate2 As InvalidCastException
'Try to Decimal
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Decimal), Nothing)
Catch exDecimal1 As ArgumentException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
Catch exDecimal2 As InvalidCastException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
End Try
End Try
End Try
Catch exString2 As ArgumentException
'Try to Integer
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Integer), Nothing)
Catch exInt32a As ArgumentException
'Try to DateTime
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), DateTime), Nothing)
Catch exDate1 As ArgumentException
'Try to Decimal
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Decimal), Nothing)
Catch exDecimal1 As ArgumentException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
Catch exDecimal2 As InvalidCastException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
End Try
Catch exDate2 As InvalidCastException
'Try to Decimal
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Decimal), Nothing)
Catch exDecimal1 As ArgumentException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
Catch exDecimal2 As InvalidCastException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
End Try
End Try
Catch exInt32b As InvalidCastException
'Try to DateTime
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), DateTime), Nothing)
Catch exDate1 As ArgumentException
'Try to Decimal
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Decimal), Nothing)
Catch exDecimal1 As ArgumentException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
Catch exDecimal2 As InvalidCastException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
End Try
Catch exDate2 As InvalidCastException
'Try to Decimal
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Decimal), Nothing)
Catch exDecimal1 As ArgumentException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
Catch exDecimal2 As InvalidCastException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
End Try
End Try
End Try
End Try
Catch exDefault2 As ArgumentException
Try
'Try to String
propertyObject.SetValue(instance, CType(dr(ColumnName), String), Nothing)
Catch exString1 As InvalidCastException
'Try to Integer
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Integer), Nothing)
Catch exInt32a As ArgumentException
'Try to DateTime
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), DateTime), Nothing)
Catch exDate1 As ArgumentException
'Try to Decimal
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Decimal), Nothing)
Catch exDecimal1 As ArgumentException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
Catch exDecimal2 As InvalidCastException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
End Try
Catch exDate2 As InvalidCastException
'Try to Decimal
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Decimal), Nothing)
Catch exDecimal1 As ArgumentException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
Catch exDecimal2 As InvalidCastException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
End Try
End Try
Catch exInt32b As InvalidCastException
'Try to DateTime
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), DateTime), Nothing)
Catch exDate1 As ArgumentException
'Try to Decimal
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Decimal), Nothing)
Catch exDecimal1 As ArgumentException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
Catch exDecimal2 As InvalidCastException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
End Try
Catch exDate2 As InvalidCastException
'Try to Decimal
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Decimal), Nothing)
Catch exDecimal1 As ArgumentException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
Catch exDecimal2 As InvalidCastException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
End Try
End Try
End Try
Catch exString2 As ArgumentException
'Try to Integer
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Integer), Nothing)
Catch exInt32a As ArgumentException
'Try to DateTime
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), DateTime), Nothing)
Catch exDate1 As ArgumentException
'Try to Decimal
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Decimal), Nothing)
Catch exDecimal1 As ArgumentException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
Catch exDecimal2 As InvalidCastException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
End Try
Catch exDate2 As InvalidCastException
'Try to Decimal
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Decimal), Nothing)
Catch exDecimal1 As ArgumentException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
Catch exDecimal2 As InvalidCastException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
End Try
End Try
Catch exInt32b As InvalidCastException
'Try to DateTime
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), DateTime), Nothing)
Catch exDate1 As ArgumentException
'Try to Decimal
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Decimal), Nothing)
Catch exDecimal1 As ArgumentException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
Catch exDecimal2 As InvalidCastException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
End Try
Catch exDate2 As InvalidCastException
'Try to Decimal
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Decimal), Nothing)
Catch exDecimal1 As ArgumentException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
Catch exDecimal2 As InvalidCastException
'Try to Double
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Double), Nothing)
Catch exDouble1 As ArgumentException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
Catch exDouble2 As InvalidCastException
'Try to Boolean
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Boolean), Nothing)
Catch exBoolean1 As ArgumentException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
Catch exBoolean2 As InvalidCastException
'Try To Date
Try
propertyObject.SetValue(instance, CType(dr(ColumnName), Date), Nothing)
Catch ex As Exception
Throw ex
End Try
End Try
End Try
End Try
End Try
End Try
End Try
End Try
End Sub

Maybe I’ll get lucky and someone will post up a “Oh you can just do this, which is new in .Net 3.5 or 4.0.. “ and I can get rid of this thing. But hey it works!

Resource: How to Consume WCF and ASP.Net Web Services in Silverlight

Convert Pipe Delimited File to CSV File and Choose and Reorder Columns

A friend need a small program to take a Pipe file and convert it to a CSV file. Easy enough, replace the “|”,s with “,”’s.  Until you add more requirements, allow the user to choose which columns they want to convert over and allow them to re-order the columns and save the file as something else.  Ok now you’re talking about streamreaders, streamwriter, some type or reorder control and choosing columns. Turning a 45min project into a  3 hour project going at full pace, as I’m not much of a Windows Form developer, I generally stick in the asp.net world.

Anyway.. here’s the project in VB.Net and source code.

The executable is in it’s default location TextPipeConverter\TextPipeConverter\bin\Debug\TextPipeConverter.exe

Notes: There’s no error checking, very minor, no try catches, quick and dirty.

Casting Types in VB.Net and More

Source: Cheat Sheet - Casting in VB.NET and C#

Great little find, and since I’m a VB.Net whore, I’ll just post up the VB.Net version :)

Casting in VB.NET

  1. By default in VB, casting is automatically done for you when you assign objects to variables. The objects are then automatically casted to the variables' type.

    This behavior can be influenced by an option line on top of your code file:

    Option Strict On
    Option Strict Off

    When on, casting is strict and not automatic.

  2. Explicit casting can be done with the cast operator CType() or DirectCast():

    textbox = CType(obj, TextBox)
    textbox = DirectCast(obj, TextBox)


    The difference between the two keywords is that CType succeeds as long as there is a valid conversion defined between the expression and the type, whereas DirectCast requires the run-time type of an object variable to be the same as the specified type. If the specified type and the run-time type of the expression are the same, however, the run-time performance of DirectCast is better than that of CType. DirectCast throws an InvalidCastException error if the argument types do not match.

  3. Testing if an object is of a particular type, can be done with the TypeOf...Is operator:

    If TypeOf obj Is TextBox Then...
  4. Obtaining a System.Type object for a given type can be done with the GetType operator:

    Dim t As System.Type
    t = GetType(String)
    MessageBox.Show(t.FullName)
  5. Obtaining a System.Type object for a given object can be done with the GetType method:

    Dim t as System.Type
    t = obj.GetType()
    MessageBox.Show(t.FullName)

Now to build on and add one more of my own…

Get the type based on an arbitrary string.

System.Type.GetType("System.String")

Problem with this though is you can not use it to cast using CType or DirectCast. Looking at the CType Function..

typename - Any expression that is legal within an As clause in a Dim statement, that is, the name of any data type, object, structure, class, or interface.

You can only use types that are compiled and can’t use types that show up at runtime. So trying to use CType(obj, System.Type.GetType(“System.String”)) will only get you an error.  Array bounds cannot appear in type specifiers.

How to get around this? I have no freaking idea, yet. I’m think I might could create a custom type of my own and do something so that it converts to the proper method but for now I’ll just catch a few ArgumentExceptions and try different cast types then.

C# - Singleton Pattern vs. Static Classes

Link sent to me from Justin.. as we’ve been discussing using Singleton’s in Win Services for the previous post I talked about. I’ll convert to VB later.

Original Article: http://dotnet.dzone.com/news/c-singleton-pattern-vs-static-

By Sam Allen

Problem: Store some common data in a singleton or static class about your program in an object array, which you store in a class. It saves state between usages and stores some caches, and must be initialized only once and shared in many code locations. Making a new object each time would be expensive.

Solution

This article covers the differences between the singleton design pattern and the static keyword on C# classes. Static classes and singletons both provide sharing of redundant objects in memory, but they are very different in usage and implementation.

Introducing the Singleton Pattern

Our ideal solution is called the singleton design pattern. Here is an implementation of a singleton that I will use. As you know, a singleton is a single-instance object. It is highly efficient and very graceful. Singletons have a static property that you must access to get the object reference.

view source

print?

01./// <summary>

02./// Sample singleton object.

03./// </summary>

04.public sealed class SiteStructure

05.{

06. /// <summary>

07. /// Possible an expensive resource we need to only store in one place.

08. /// </summary>

09. object[] _data = new object[10];

10. /// <summary>

11. /// Allocate ourselves. We have a private constructor, so no one else can.

12. /// </summary>

13. static readonly SiteStructure _instance = new SiteStructure();

14. /// <summary>

15. /// Access SiteStructure.Instance to get the singleton object.

16. /// Then call methods on that instance.

17. /// </summary>

18. public static SiteStructure Instance

19. {

20. get { return _instance; }

21. }

22. /// <summary>

23. /// This is a private constructor, meaning no outsides have access.

24. /// </summary>

25. private SiteStructure()

26. {

27. // Initialize members, etc. here.

28. }

29.}

Static Class Example

In the following example, look carefully at how the static keyword is used on the class and constructor. Static classes may be simpler, but the singleton example has many important advantages, which I will elaborate on after this code block.

view source

print?

01./// <summary>

02./// Static class example. Pay heed to the static keywords.

03./// </summary>

04.static public class SiteStatic

05.{

06. /// <summary>

07. /// The data must be a static member in this example.

08. /// </summary>

09. static object[] _data = new object[10];

10. /// <summary>

11. /// C# doesn't define when this constructor is run, but it will

12. /// be run right before it is used most likely.

13. /// </summary>

14. static SiteStatic()

15. {

16. // Initialize all of our static members.

17. }

18.}

You can use static classes to store single-instance, global data. The class will be initialized at any time, but it is my experience that it is initialized lazily, meaning at the last possible moment. However, you lose control over the exact behavior of the class by using a static class.

Singleton Advantages

Singletons preserve the conventional class approach, and don't require that you use the static keyword everywhere. They may be more demanding to implement at first, but will greatly simplify the architecture of your program. Unlike static classes, we can use singletons as parameters or objects.

view source

print?

1.// We want to call a function with this structure as an object.

2.// Get a reference from the Instance property on the singleton.

3.{

4. SiteStructure site = SiteStructure.Instance;

5. OtherFunction(site); // Use singleton as parameter.

6.}

Interface Inheritance

In C#, an interface is a contract, and objects that have an interface must meet all of the requirements of that interface. Usually, the requirements of the interface are a subset of the object in question. Here is how we can use a singleton with an interface, which in the example is called ISiteInterface.

view source

print?

01./// <summary>

02./// Stores signatures of various important methods related to the site.

03./// </summary>

04.public interface ISiteInterface

05.{

06.};

07./// <summary>

08./// Skeleton of the singleton that inherits the interface.

09./// </summary>

10.class SiteStructure : ISiteInterface

11.{

12. // Implements all ISiteInterface methods.

13. // [omitted]

14.}

15./// <summary>

16./// Here is an example class where we use a singleton with the interface.

17./// </summary>

18.class TestClass

19.{

20. /// <summary>

21. /// Sample.

22. /// </summary>

23. public TestClass()

24. {

25. // Send singleton object to any function that can take its interface.

26. SiteStructure site = SiteStructure.Instance;

27. CustomMethod((ISiteInterface)site);

28. }

29. /// <summary>

30. /// Receives a singleton that adheres to the ISiteInterface interface.

31. /// </summary>

32. private void CustomMethod(ISiteInterface interfaceObject)

33. {

34. // Use the singleton by its interface.

35. }

36.}

Now we can reuse our singleton for any of the implementations of interface-conforming objects. There may be 1, 2, or 10. We don't need to rewrite anything over and over again. We store state more conventionally, use objects by their interfaces, and can use traditional object-oriented programming best practices.

Conclusion

Here we can reuse code and control object state much easier. This allows you greatly improved code-sharing, and a far cleaner body of code. With less code, your programs will usually have fewer bugs and will be easier to maintain. One good book about this topic is called C# Design Patterns and is written by Judith Bishop.

.Net – Improve garbage collection and performance

My friend Pasha, found a great article by QuestPond over at DotNetFunda that covers the theory and best practices of proper .Net garbage collection.

-----------------

Ask any developer which is the best place in a .NET class to clean unmanaged resources?, 70% of them will say the destructor. Although it looks the most promising place for cleanup it has a huge impact on performance and memory consumption. Writing clean up code in the destructor leads to double GC visits and thus affecting the performance multifold times.

In order to validate the same we will first start with bit of theory and then we will actually see how GC algorithm performance is impacted using destructor. So we will first understand the concept of generations and then we will see the finalize dispose pattern.

Is this Article worth reading ahead?

With this article you will understand how performance of GC algorithm can be improved using finalize dispose pattern. Below figure shows the comparison of what we will be achieving after this article.

Introduction and Goal

Ask any developer which is the best place in a .NET class to clean unmanaged resources?, 70% of them will say the destructor. Although it looks the most promising place for cleanup it has a huge impact on performance and memory consumption. Writing clean up code in the destructor leads to double GC visits and thus affecting the performance multifold times.
In order to validate the same we will first start with bit of theory and then we will actually see how GC algorithm performance is impacted using destructor. So we will first understand the concept of generations and then we will see the finalize dispose pattern.
I am sure this article will change your thought process regarding destructor, dispose and finalize.
Please feel free to download my free 500 question and answer eBook which covers .NET , ASP.NET , SQL Server , WCF , WPF , WWF@ http://www.questpond.com .

Assumptions

This article uses CLR profiler to profile how GC works. In case you are new to CLR profiler please do read net-best-practice-no-1-detecting-high-memory-consuming-functions-in-net-code   before you go ahead with this one.

Thanks Mr. Jeffrey Richter and Peter Sollich

Let’s start this article by first thanking Mr. Jeffery Richter for explaining in depth how garbage collection algorithm works. He has written two legendary articles about the way garbage collector work. I actually wanted to point to the MSDN magazine article written by Jeffery Richter but for some reason it’s not showing up in MSDN. So I am pointing to a different unofficial location, you can download both the articles from http://www.cs.inf.ethz.ch/ssw/files/GC_in_NET.pdf in a PDF format.
Also thanks to Mr. Peter Sollich who is the CLR Performance Architect to write such a detail help on CLR profiler. When you install the CLR profiler please do not forget to read the detail help document written by Peter Sollich. In this article we will use the CLR profiler to check how the garbage collector performance is affected using finalize.
Thanks a lot to you guys. There was no way I would have completed this article without reading articles written by you. Any time you guys pass by article please do comment on the same would love to hear from you guys.

Garbage collector – The unsung Hero

As said in the introduction writing clean up code in constructor leads to double GC visits. Many developers would like to just shrug off and say ‘Should we really worry about GC and what it does behind scenes?”. Yes, actually we should not worry about GC if you write your code properly. GC has the best algorithm to ensure that your application is not impacted. But many times the way you have written your code and assigned/cleaned memory resources in your code affects GC algorithm a lot. Sometimes this impact leads to bad performance of GC and hence bad performance for your application.
So let’s first understand what different tasks are performed by the garbage collector to allocate and clean up memory in an application.
Let’s say we have 3 classes where in class ‘A’ uses class ‘B’ and class ‘B’ uses class ‘C’.

When the first time your application starts predefined memory is allocated to the application. When the application creates these 3 objects they are assigned in the memory stack with a memory address. You can see in the below figure how the memory looks before the object creation and how it looks after object creation. In case there was an object D created it will be allocated from the address where Object C ends.

Internally GC maintains an object graph to know which objects are reachable. All objects belong to the main application root object. The root object also maintains which object is allocated on which memory address. In case an object is using other objects then that object also holds a memory address of the used object. For example in our case object A uses Object B. So object A stores the memory address of Object B.

Now let’s say Object ‘A’ is removed from memory. So the Object ‘A’ memory is assigned to Object ‘B’ and Object ‘B’ memory is assigned to object ‘C’. So the memory allocation internally looks something as shown below.

As the address pointers are updated GC also needs to ensure that his internal graph is updated with new memory addresses. So the object graph becomes something as shown below. Now that’s a bit of work for GC it needs to ensure that the object is removed from graph and the new addresses for the existing objects is updated throughout the object tree.

An application other than his own custom objects also has .NET objects which also form the part of the graph. The addresses to those objects also need to be updated. The number of objects of .NET runtime is very high. For instance below is the number of objects created for a simple console based hello world application. The numbers of objects are approximately in 1000’s. Updating pointers for each of these objects is a huge task.

Generation algorithm – Today, yesterday and day before yesterday

GC uses the concept of generations to improve performance. Concept of generation is based on the way human psychology handles tasks. Below are some points related to how tasks are handled by humans and how garbage collector algorithm works on the same lines:-
• If you decide some task today there is a high possibility of completion of those tasks.
• If some task is pending from yesterday then probably that task has gained a low priority and it can be delayed further.
• If some task is pending from day before yesterday then there is a huge probability that the task can be pending forever.
GC thinks in the same lines and has the below assumptions:-
• If the object is new then the life time of the object can be short.
• If an object is old then it can have a long life time.
So said and done GC supports three generations (Generation 0, Generation 1 and Generation 2).

Generation 0 has all the newly created objects. When the application creates objects they first come and fall in the Generation 0 bucket. A time comes when Generation 0 fills up so GC needs to run to free memory resources. So GC starts building the graph and eliminating any objects which are not used in application any more. In case GC is not able to eliminate an object from generation 0 it promotes it to generation 1. If in the coming iterations it’s not able to remove objects from generation 1 it’s promoted to generation 2. The maximum generation supported by .NET runtime is 2.
Below is a sample display of how generation objects are seen when you run CLR profiler. In case you are new to CLR profiler you can catch up the basics from net-best-practice-no-1-detecting-high-memory-consuming-functions-in-net-code

Ok, so how does generation help in optimization

As the objects are now contained in generations, GC can make a choice which generation objects he wants to clean. If you remember in the previous section we talked about the assumptions made by GC regarding object ages. GC assumes that all new objects have shorter life time. So in other words GC will mainly go through generation 0 objects more rather than going through all objects in all generations.
If clean up from generation 0 does not provide enough memory it will then move towards cleaning from generation 1 and so on. This algorithm improves GC performance to a huge extent.

Conclusion about generations

• Huge number of object in Gen 1 and 2 means memory utilization is not optimized.
• Larger the Gen 1 and Gen 2 regions GC algorithm will perform more worst.

Using finalize/destructor leads to more objects in Gen 1 and Gen 2

The C# compiler translates (renames) the destructor into Finalize. If you see the IL code using IDASM you can see that the destructor is renamed to finalize. So let’s try to understand why implementing destructor leads to more objects in gen 1 and gen 2 regions. Here’s how the process actually works:-
• When new objects are created they are moved to gen 0.
• When gen 0 fills out GC runs and tries to clear memory.
• If the objects do not have a destructor then it just cleans them up if they are not used.
• If the object has a finalize method it moves those objects to the finalization queue.
• If the objects are reachable it’s moved to the ‘Freachable’ queue. If the objects are unreachable the memory is reclaimed.
• GC work is finished for this iteration.
• Next time when GC again starts its goes to Freachable queue to check if the objects are not reachable. If the objects are not reachable from Freachable memory is claimed back.

In other words objects which have destructor can stay more time in memory.
Let’s try to see the same practically. Below is a simple class which has destructor.

class clsMyClass 
{ 
public clsMyClass()
{ 
}
~clsMyClass()
{
}
}

We will create 100 * 10000 objects and monitor the same using CLR profiler.

for (int i = 0; i < 100 * 10000; i++)
{
clsMyClass obj = new clsMyClass();
}

If you see the CLR profiler memory by address report you will see lot of objects in gen 1.

Now let’s remove the destructor and do the same exercise.

class clsMyClass 
{ 
public clsMyClass()
{ 
}
}

You can see the gen 0 has increased considerably while gen 1 and 2 are less in number.

If we see a one to one comparison it’s something as shown in the below figure.

Get rid of the destructor by using Dispose

We can get rid of the destructor by implementing our clean up code in the dispose method For that we need to implement the ‘IDisposable’ method , write our clean up code in this and call suppress finalize method as shown in the below code snippet. ‘SuppressFinalize’ dictates the GC to not call the finalize method. So the double GC call does not happen.

class clsMyClass : IDisposable
{ 
public clsMyClass()
{ 
}
~clsMyClass()
{
}

public void Dispose()
{
GC.SuppressFinalize(this);
} 
}

The client now needs to ensure that it calls the dispose method as shown below.

for (int i = 0; i < 100 ; i++)
{
clsMyClass obj = new clsMyClass();
obj.Dispose(); 
}

Below is the comparison of how Gen 0 and 1 distribution looks with constructor and with dispose. You can see there is marked improvement in gen 0 allocation which signifies good memory allocation.

What if developers forget to call Dispose?

It’s not a perfect world. We cannot ensure that the dispose method is always called from the client. So that’s where we can use Finalize / Dispose pattern as explained in the coming section.
There is a detailed implementation of this pattern at http://msdn.microsoft.com/en-us/library/b1yfkh5e(VS.71).aspx.
Below is how the implementation of finalize / dispose pattern looks like.

class clsMyClass : IDisposable
{ 
public clsMyClass()
{

}

~clsMyClass()
{
// In case the client forgets to call
// Dispose , destructor will be invoked for
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// Free managed objects.
}
// Free unmanaged objects

}

public void Dispose()
{
Dispose(true);
// Ensure that the destructor is not called
GC.SuppressFinalize(this);
} 
}

Explanation of the code:-
• We have defined a method called as Dispose which takes a Boolean flag. This flag says is this method called from Dispose or from the destructor. If this is called from the ‘Dispose’ method then we can free both managed and unmanaged resources.
• If this method is called from the destructor then we will just free the unmanaged resources.
• In the dispose method we have suppressed the finalize and called the dispose with true.
• In the destructor we have called the dispose function with false value. In other words we assume that the GC will take care of managed resources and let’s take the destructor call to clean unmanaged resources.
In other words if the client does not call the dispose function the destructor will take care of cleaning the unmanaged resources.

Conclusion

• Do not have empty constructors in your classes.
• In case you need to clean up use finalize dispose pattern with ‘SupressFinalize’ method called.
• If there is a dispose method exposed by a class , ensure to call the same from your client code.
• Application should have more objects allocated in Gen 0 than Gen 1 and Gen 2. More objects in Gen 1 and 2 is sign of bad GC algorithm execution.

Source code

You can find the sample source code for the dispose pattern at from here

Call your Win Service from your Web Application

Some quick code snippets from my brother.  If you have a running Windows Service, you can call it from your Web Application to run a custom command. UPDATE: There’s some better VB Sample Code here and quick and easy of both the Windows Service and the ASP.Net

So you have your Win Service named “Encoder” and when you say, upload a video, you then call the Service and send it an argument value of 10.  Then in your web service when it see’s the value 10 come in, it knows to start encoding any videos uploaded. 

Here’s some sample code:

Web application must have full trust. Partial trust not allowed.

In your application: (add reference to System.ServiceProcess.dll)

System.ServiceProcess.ServiceController controller = new System.ServiceProcess.ServiceController(“serviceName”)
controller.ExecuteCommand(commandinteger);


In your Win service here is your code:

protected override void OnCustomCommand(int commandinteger){
 
switch(commandinteger){
case 129:
//do something
break;
case 130:
//do something else
break;
}
 
}

commandinteger values must be between 128 and 256.

128 and below are system reserved.

Check the link below for msdn description
http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.oncustomcommand.aspx

http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.oncustomcommand(VS.80).aspx

Found this blog post with more info, cause I’m lazy :p

http://blogs.msdn.com/kaevans/archive/2005/03/17/397505.aspx

Updated Blog Post On This Topic