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”

IIS7 Windows7/Server2008 ApplicationPoolIdentity Security Change from Network Service

 

Yeah this one got me.. http://learn.iis.net/page.aspx/624/application-pool-identities/

The change microsoft made to have AppPool now run as “ApplicationPoolIdentity” instead of Network service.

So if you normally give Network Service rights needed to your webapp, you now have to stop doing that and change it to

IIS AppPool\DefaultAppPool

Or

IIS AppPool\<NAME OF YOUR APPPOOL>

End of that.

 

 

 

 

  1. Open Windows Explorer
  2. Select a file or directory.
  3. Right click the file and select "Properties"
  4. Select the "Security" tab
  5. Click the "Edit" and then "Add" button
  6. Click the "Locations" button and make sure you select your machine.
  7. Enter "IIS AppPool\DefaultAppPool" in the "Enter the object names to select:" text box.
  8. Click the "Check Names" button and click "OK".

By doing this the file or directory you selected will now also allow the "DefaultAppPool" identity access.

Optimizing Pages that use Telerik Controls. Mainly RadGrid

 

I was watching a webcast on Telerik TV, it’s called Optimizing RadGrid for ASP.NET Ajax.  There is a lot of useful information there. I summarized a bunch of it.

On my test page I…

  • Added Browserfile...
    • Compressing ViewState for RadTelerik controls  (Dropped viewstate considerably from sample page, 50,776 bytes to 5,428 bytes)
  • Added RadCompression for AJAX Calls to drop traffic size on ajax post-backs (Not handled by IIS compression)
  • Reduce Request using StyleManager and RadScriptManager
    • Added RadStyleSheetManager to MasterPage (Combines all CSS sheets into one download to limit requests)
    • Switched to RadScriptManager on Masterpage instead of ScriptManage
      • Request dropped from 71 to 47

 

Summarized Tips

  • Bind Grid Data on PreInit event, this will keep data from going to the ViewState and cut down on page size
  • If the Grid is ReadOnly and no editing takes place, then turn off viewstate for the Grid. EnableViewState="False"
    • Features that will NOT work when viewstate is off
      • Custom Edit Forms (User Control or Form Template)
      • Filtering
      • Grouping
      • Using Cached Data and Paging Together
    • Features that WILL work when view state is off
      • Indexes of Selected Items
      • Indexes of Edited Items
      • Group-by Expressions and Settings (but not the expanded state of grouped items)
      • Sort Expressions
      • Style Properties (But not if applied to a single cell or row in ItemDataBound event)
      • Column Order and other column properties
      • All settings concerning hierarchy structure (but not the expanded state of the items)
  • Optimized Column Editors on Grid
    • Used Shared Data Picker for Date columns in your grid
      • This requires a hidden data picker on page, and template column with textbox that uses js to talk to the datepicker with client-api (See Example Here)
    • Use Template column for comboxes and use Load-On-Demand
  • Ajaxify the Grid
    • Compresses Ajax calls which IIS misses, use RadCompression to drop traffic size
    • Use StyleManager and ScriptManager to bundle all css and scripts into one call each to server
  • More Tips Here
  • Other Ways to Optimize
    • Client-side Binding
    • Custom Paging
    • Virtual Scrolling
    • Caching Data server-side
    • Hierarchy Load modes
    • Group load modes
    • Filtering
    • .NET 3.5 + Linq
    • Upgrade from IE6

 

Other Controls

  • Other Controls
    • Use Shared Data Picker
    • Use RadInputManager if you want Validated or Stylized instead of using the the RadNumeric or RadTextbox controls
    • Use Load-On-Demand RadComboboxes
    • On RadMultiPage set RenderSelectedPageOnly = True
    • Hide Grid's with Visible="False" not with surrounding Div's set to display none.
      • Hiding the Grid itself, it doesn't render or get bound, grid will get data when visible is set to true again.
  • Add App_Browsers folder with a file that has.. (This one is HUGE, dropped my page significantly)
    • Create a file and add
    • <browsers>
          <browser refID="Default">
              <controlAdapters>
                  <!--<adapter controlType="System.Web.UI.Page" adapterType="Telerik.Web.UI.RadHiddenFieldPageStateCompression" />-->
                  <adapter controlType="System.Web.UI.Page" adapterType="Telerik.Web.UI.RadSessionPageStateCompression" />
              </controlAdapters>
          </browser>
      </browsers>

.Net Resetting Scroll Position When MaintainScrollPositionOnPostBack = True

Had a friend have an issue where he had select buttons on a gridview and on selected changed event he would update control at the top of his page.  However, he had MaintainScrollPositionOnPostBack set to True, so of course the browser would reload and scroll down to where he had clicked the Select button.

Found this article how to override the MaintainScrollPosition so it would go to the top of the page.  Works like a charm.

http://www.4guysfromrolla.com/articles/111407-1.aspx

On postback, the ASP.NET page adds a call to the client-side function WebForm_RestoreScrollPosition(), which returns the browser's scroll position to the X and Y coordinates specified by the __SCROLLPOSITIONX and __SCROLLPOSITIONY form fields (which were assigned the browser's scroll position before the postback ensued). Consequently, the browser's scroll position is maintained across postbacks. The diagram below illustrates this interaction graphically.

In order to reset the scroll position, we need to add the above JavaScript to the rendered page's output and then call it before the call to WebForm_RestoreScrollPosition(). The following code adds a function (ResetScrollPosition) to the outputted markup and then injects a line of script that invokes this function. The server-side code uses the RegisterClientScriptBlock method to register the ResetScrollPosition function, which adds the function to the top of the form. As noted earlier, RegisterStartupScript adds a call to ResetScrollPosition at the bottom of the page.

Private Sub ResetScrollPosition()
If Not ClientScript.IsClientScriptBlockRegistered(Me.GetType(), "CreateResetScrollPosition") Then
'Create the ResetScrollPosition() function
ClientScript.RegisterClientScriptBlock(Me.GetType(), "CreateResetScrollPosition", _
"function ResetScrollPosition() {" & vbCrLf & _
" var scrollX = document.getElementById('__SCROLLPOSITIONX');" & vbCrLf & _
" var scrollY = document.getElementById('__SCROLLPOSITIONY');" & vbCrLf & _
" if (scrollX && scrollY) {" & vbCrLf & _
" scrollX.value = 0;" & vbCrLf & _
" scrollY.value = 0;" & vbCrLf & _
" }" & vbCrLf & _
"}", True)
'Add the call to the ResetScrollPosition() function
ClientScript.RegisterStartupScript(Me.GetType(), "CallResetScrollPosition", "ResetScrollPosition();", True)
End If
End Sub

To reset scroll position on postback, simply call the server-side ResetScrollPosition() method from the appropriate event handler (be it the Click event handler of a Button, the PageIndexChanged event of the GridView, or some other event).

Rest of Article

HTTP Error 404.17 Not Found – Using WCF .SVC Service

So you’re getting IIS error’s when trying to run a .svc file that’s coded to use WCF or Windows Communication Foundation.

HTTP Error 404.17 - Not Found

The requested content appears to be script and will not be served by the static file handler.

or maybe..

HTTP Error 404.3 - Not Found

The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.

Took me awhile to realize I need to setup/configure IIS and WCF properly.  Here are the steps from MS, I went through and realized I had missed one component (IIS6 Scripting tools, who would have thought), which I probably didn’t need, but the big ones that I didn’t have WCF Http Activation installed.  After that, I registered WCF..

"%WINDIR%\Microsoft.Net\Framework\v3.5\WFServicesReg.exe" /c

and then I was golden, but there might be other things you are lacking or missing. So go through all the steps.

One-Time Set Up Procedure for the Windows Communication Foundation Samples

Set the DefaultButton inside a LoginView Control in a MasterPage

Ok if you google this you’ll get some solutions that say set the DefaultButton to ParentControlID$ButtonID

However, this didn’t work for me. I kept getting the same error no matter what I tried.

The DefaultButton of '<PanelID>' must be the ID of a control of type IButtonControl.

So I tried another approach that worked great.

On page load I found the Panel Control and found the button control and set the default button programmatically.

<asp:LoginView ID="LoginView1" runat="server">
    <AnonymousTemplate>
        <asp:Panel ID="pnlLogin" runat="server">
            <telerik:RadTextBox ID="tbUsername" runat="server" EmptyMessage="Username" />&nbsp;
            <telerik:RadTextBox ID="tbPassword" runat="server" EmptyMessage="Password" TextMode="Password" />&nbsp;
            <div id="SignIn" style="position: relative; z-index: 1; float: right; bottom: 21px;">
                 <asp:LinkButton ID="lbSignIn" runat="server" Font-Bold="true" Font-Size="Small" Text="SIGN IN" OnClick="lbSignIn_Click" />
            </div>
            <div id="divLoginLinks" style="position:relative; clear:both">
                <span class="GrayFooterFont"><asp:HyperLink ID="hlRegister" runat="server" Text="Register" NavigateUrl="~/Registration.aspx" /> | <asp:HyperLink ID="hlForgot" runat="server" Text="Forgot Password" NavigateUrl="~/ForgotPassword.aspx" /></span>
            </div>
        </asp:Panel>
    </AnonymousTemplate>
    <LoggedInTemplate>
        <small><asp:Label ID="lblLoggedInUsername" runat="server" /> | <asp:LinkButton ID="lbSignOut" runat="server" Text="SIGN OUT" OnClick="lbSignOut_Click" /></small>
        <asp:LinkButton ID="lbSignIn" runat="server" Font-Bold="true" Font-Size="Small" Text="SIGN IN" OnClick="lbSignIn_Click" CssClass="hidden" />
    </LoggedInTemplate>
</asp:LoginView>

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    'If User is not logged in do this        
    Dim pnlLogin As Panel
    Dim lbSignIn As LinkButton
    pnlLogin = CType(LoginView1.Controls(0).FindControl("pnlLogin"), Panel)
    lbSignIn = CType(LoginView1.Controls(0).FindControl("lbSignIn"), LinkButton)
    pnlLogin.DefaultButton = lbSignIn.ID
    pnlLogin = Nothing
    lbSignIn = Nothing
End Sub

I’m sure I could have just hardcoded the lblSignIn ID to the pnlLogin, but no idea why I didn’t.

State DropDown List

My list for project when I need a State DropDownList

Full State Names using asp:DropDownList

<asp:DropDownList ID="ddlStates" runat="server">
    <asp:ListItem Value="AL">Alabama</asp:ListItem>
    <asp:ListItem Value="AK">Alaska</asp:ListItem>
    <asp:ListItem Value="AZ">Arizona</asp:ListItem>
    <asp:ListItem Value="AR">Arkansas</asp:ListItem>
    <asp:ListItem Value="CA">California</asp:ListItem>
    <asp:ListItem Value="CO">Colorado</asp:ListItem>
    <asp:ListItem Value="CT">Connecticut</asp:ListItem>
    <asp:ListItem Value="DC">District of Columbia</asp:ListItem>
    <asp:ListItem Value="DE">Delaware</asp:ListItem>
    <asp:ListItem Value="FL">Florida</asp:ListItem>
    <asp:ListItem Value="GA">Georgia</asp:ListItem>
    <asp:ListItem Value="HI">Hawaii</asp:ListItem>
    <asp:ListItem Value="ID">Idaho</asp:ListItem>
    <asp:ListItem Value="IL">Illinois</asp:ListItem>
    <asp:ListItem Value="IN">Indiana</asp:ListItem>
    <asp:ListItem Value="IA">Iowa</asp:ListItem>
    <asp:ListItem Value="KS">Kansas</asp:ListItem>
    <asp:ListItem Value="KY">Kentucky</asp:ListItem>
    <asp:ListItem Value="LA">Louisiana</asp:ListItem>
    <asp:ListItem Value="ME">Maine</asp:ListItem>
    <asp:ListItem Value="MD">Maryland</asp:ListItem>
    <asp:ListItem Value="MA">Massachusetts</asp:ListItem>
    <asp:ListItem Value="MI">Michigan</asp:ListItem>
    <asp:ListItem Value="MN">Minnesota</asp:ListItem>
    <asp:ListItem Value="MS">Mississippi</asp:ListItem>
    <asp:ListItem Value="MO">Missouri</asp:ListItem>
    <asp:ListItem Value="MT">Montana</asp:ListItem>
    <asp:ListItem Value="NE">Nebraska</asp:ListItem>
    <asp:ListItem Value="NV">Nevada</asp:ListItem>
    <asp:ListItem Value="NH">New Hampshire</asp:ListItem>
    <asp:ListItem Value="NJ">New Jersey</asp:ListItem>
    <asp:ListItem Value="NM">New Mexico</asp:ListItem>
    <asp:ListItem Value="NY">New York</asp:ListItem>
    <asp:ListItem Value="NC">North Carolina</asp:ListItem>
    <asp:ListItem Value="ND">North Dakota</asp:ListItem>
    <asp:ListItem Value="OH">Ohio</asp:ListItem>
    <asp:ListItem Value="OK">Oklahoma</asp:ListItem>
    <asp:ListItem Value="OR">Oregon</asp:ListItem>
    <asp:ListItem Value="PA">Pennsylvania</asp:ListItem>
    <asp:ListItem Value="RI">Rhode Island</asp:ListItem>
    <asp:ListItem Value="SC">South Carolina</asp:ListItem>
    <asp:ListItem Value="SD">South Dakota</asp:ListItem>
    <asp:ListItem Value="TN">Tennessee</asp:ListItem>
    <asp:ListItem Value="TX">Texas</asp:ListItem>
    <asp:ListItem Value="UT">Utah</asp:ListItem>
    <asp:ListItem Value="VT">Vermont</asp:ListItem>
    <asp:ListItem Value="VA">Virginia</asp:ListItem>
    <asp:ListItem Value="WA">Washington</asp:ListItem>
    <asp:ListItem Value="WV">West Virginia</asp:ListItem>
    <asp:ListItem Value="WI">Wisconsin</asp:ListItem>
    <asp:ListItem Value="WY">Wyoming</asp:ListItem>
</asp:DropDownList>

asp:DropDownList with Abbreviate States

<asp:DropDownList ID="ddlStates" runat="server">
    <asp:ListItem value="AK">AK</asp:ListItem>
    <asp:ListItem value="AL">AL</asp:ListItem>
    <asp:ListItem value="AR">AR</asp:ListItem>
    <asp:ListItem value="AZ">AZ</asp:ListItem>
    <asp:ListItem value="CA">CA</asp:ListItem>
    <asp:ListItem value="CO">CO</asp:ListItem>
    <asp:ListItem value="CT">CT</asp:ListItem>
    <asp:ListItem value="DC">DC</asp:ListItem>
    <asp:ListItem value="DE">DE</asp:ListItem>
    <asp:ListItem value="FL">FL</asp:ListItem>
    <asp:ListItem value="GA">GA</asp:ListItem>
    <asp:ListItem value="HI">HI</asp:ListItem>
    <asp:ListItem value="IA">IA</asp:ListItem>
    <asp:ListItem value="ID">ID</asp:ListItem>
    <asp:ListItem value="IL">IL</asp:ListItem>
    <asp:ListItem value="IN">IN</asp:ListItem>
    <asp:ListItem value="KS">KS</asp:ListItem>
    <asp:ListItem value="KY">KY</asp:ListItem>
    <asp:ListItem value="LA">LA</asp:ListItem>
    <asp:ListItem value="MA">MA</asp:ListItem>
    <asp:ListItem value="MD">MD</asp:ListItem>
    <asp:ListItem value="ME">ME</asp:ListItem>
    <asp:ListItem value="MI">MI</asp:ListItem>
    <asp:ListItem value="MN">MN</asp:ListItem>
    <asp:ListItem value="MO">MO</asp:ListItem>
    <asp:ListItem value="MS">MS</asp:ListItem>
    <asp:ListItem value="MT">MT</asp:ListItem>
    <asp:ListItem value="NC">NC</asp:ListItem>
    <asp:ListItem value="ND">ND</asp:ListItem>
    <asp:ListItem value="NE">NE</asp:ListItem>
    <asp:ListItem value="NH">NH</asp:ListItem>
    <asp:ListItem value="NJ">NJ</asp:ListItem>
    <asp:ListItem value="NM">NM</asp:ListItem>
    <asp:ListItem value="NV">NV</asp:ListItem>
    <asp:ListItem value="NY">NY</asp:ListItem>
    <asp:ListItem value="OH">OH</asp:ListItem>
    <asp:ListItem value="OK">OK</asp:ListItem>
    <asp:ListItem value="OR">OR</asp:ListItem>
    <asp:ListItem value="PA">PA</asp:ListItem>
    <asp:ListItem value="RI">RI</asp:ListItem>
    <asp:ListItem value="SC">SC</asp:ListItem>
    <asp:ListItem value="SD">SD</asp:ListItem>
    <asp:ListItem value="TN">TN</asp:ListItem>
    <asp:ListItem value="TX">TX</asp:ListItem>
    <asp:ListItem value="UT">UT</asp:ListItem>
    <asp:ListItem value="VA">VA</asp:ListItem>
    <asp:ListItem value="VT">VT</asp:ListItem>
    <asp:ListItem value="WA">WA</asp:ListItem>
    <asp:ListItem value="WI">WI</asp:ListItem>
    <asp:ListItem value="WV">WV</asp:ListItem>
    <asp:ListItem value="WY">WY</asp:ListItem>
</asp:DropDownList>

Or if you use Telerik controls like I do… then the RadComboBox is for you

<telerik:RadComboBox ID="RadComboBox1" runat="server">
    <Items>
        <telerik:RadComboBoxItem value="AK" Text="AK" />
        <telerik:RadComboBoxItem value="AL" Text="AL" />
        <telerik:RadComboBoxItem value="AR" Text="AR" />
        <telerik:RadComboBoxItem value="AZ" Text="AZ" />
        <telerik:RadComboBoxItem value="CA" Text="CA" />
        <telerik:RadComboBoxItem value="CO" Text="CO" />
        <telerik:RadComboBoxItem value="CT" Text="CT" />
        <telerik:RadComboBoxItem value="DC" Text="DC" />
        <telerik:RadComboBoxItem value="DE" Text="DE" />
        <telerik:RadComboBoxItem value="FL" Text="FL" />
        <telerik:RadComboBoxItem value="GA" Text="GA" />
        <telerik:RadComboBoxItem value="HI" Text="HI" />
        <telerik:RadComboBoxItem value="IA" Text="IA" />
        <telerik:RadComboBoxItem value="ID" Text="ID" />
        <telerik:RadComboBoxItem value="IL" Text="IL" />
        <telerik:RadComboBoxItem value="IN" Text="IN" />
        <telerik:RadComboBoxItem value="KS" Text="KS" />
        <telerik:RadComboBoxItem value="KY" Text="KY" />
        <telerik:RadComboBoxItem value="LA" Text="LA" />
        <telerik:RadComboBoxItem value="MA" Text="MA" />
        <telerik:RadComboBoxItem value="MD" Text="MD" />
        <telerik:RadComboBoxItem value="ME" Text="ME" />
        <telerik:RadComboBoxItem value="MI" Text="MI" />
        <telerik:RadComboBoxItem value="MN" Text="MN" />
        <telerik:RadComboBoxItem value="MO" Text="MO" />
        <telerik:RadComboBoxItem value="MS" Text="MS" />
        <telerik:RadComboBoxItem value="MT" Text="MT" />
        <telerik:RadComboBoxItem value="NC" Text="NC" />
        <telerik:RadComboBoxItem value="ND" Text="ND" />
        <telerik:RadComboBoxItem value="NE" Text="NE" />
        <telerik:RadComboBoxItem value="NH" Text="NH" />
        <telerik:RadComboBoxItem value="NJ" Text="NJ" />
        <telerik:RadComboBoxItem value="NM" Text="NM" />
        <telerik:RadComboBoxItem value="NV" Text="NV" />
        <telerik:RadComboBoxItem value="NY" Text="NY" />
        <telerik:RadComboBoxItem value="OH" Text="OH" />
        <telerik:RadComboBoxItem value="OK" Text="OK" />
        <telerik:RadComboBoxItem value="OR" Text="OR" />
        <telerik:RadComboBoxItem value="PA" Text="PA" />
        <telerik:RadComboBoxItem value="RI" Text="RI" />
        <telerik:RadComboBoxItem value="SC" Text="SC" />
        <telerik:RadComboBoxItem value="SD" Text="SD" />
        <telerik:RadComboBoxItem value="TN" Text="TN" />
        <telerik:RadComboBoxItem value="TX" Text="TX" />
        <telerik:RadComboBoxItem value="UT" Text="UT" />
        <telerik:RadComboBoxItem value="VA" Text="VA" />
        <telerik:RadComboBoxItem value="VT" Text="VT" />
        <telerik:RadComboBoxItem value="WA" Text="WA" />
        <telerik:RadComboBoxItem value="WI" Text="WI" />
        <telerik:RadComboBoxItem value="WV" Text="WV" />
        <telerik:RadComboBoxItem value="WY" Text="WY" />
    </Items>
</telerik:RadComboBox>

Simple Grid Boolean Value Yes/No from DB or CustomYes/CustomNo

I'm just putting this up here so I have it somewhere when I forget.

Sometimes I pull data from my database from a Bit column or boolean column and want to display more then True/False.

With a simple statement you can make it say anything you want.

<asp:TemplateField HeaderText="Is Active">
<ItemTemplate>
<asp:Label id="lblActive" runat="server" Text='<%#IIf(Boolean.Parse(Eval("Active").ToString()), "Yes", "No")%>' />
</ItemTemplate>
</asp:TemplateField>

Using Resource File to Populate DropDownList

I had desire to populate a DropDownList with values from a resource file. Using the resource name as the ddl value and the resource value as ddl text.  There’s other reasons I need to do this but I’m simplifying it here.

The resource file name is: “BatchFields_ADMRACClaim
The DropDownList is called “ddlFeilds”

So first I get the resource file object and then I do a GetType() to initialize it. If anyone has any other suggestions for this, please let me know. Without the GetType() line or pulling out a value first, the GetResourceSet later is Nothing.

Dim BatchFileResource As ResourceManager
BatchFileResource = Resources.BatchFields_ADMRACClaim.ResourceManager()
Dim Value As String = BatchFileResource.GetType.Assembly.FullName
 

Then once I have the resource file in the “BatchFileResource” object, I can then loop through the items and dump them into a DropDownList.

Dim BatchResourceSet As ResourceSet = BatchFileResource.GetResourceSet(System.Globalization.CultureInfo.CurrentCulture, True, False)
Dim BatchEnumerator As IDictionaryEnumerator = BatchResourceSet.GetEnumerator()
ddlFields.Items.Clear()
While BatchEnumerator.MoveNext
Dim ddlItem As New ListItem(BatchEnumerator.Value, BatchEnumerator.Key)
ddlFields.Items.Add(ddlItem)
End While

And that’s it. I’ve found other samples on the web but I’ve combined the best of both worlds here.