Thursday, December 18, 2008

New acronym for the day POCO

The very helpful Wikipedia explains - Plain Old CLR Object.

Monday, December 15, 2008

Object-relational impedance mismatch

Recently I found myself discussing how to an application accesses data in a database. This Wikipedia article has some good arguments for an Object-relational mapping approach.

Thursday, December 4, 2008

Log file monitoring for log4net output

I was thinking of building a C# UDP listener to connect a log4net UDP appender to. Something like this - Code Project: A log4net Realtime Color Console for ASP.NET

The trick would be getting a setup that would work for multiple developers. A service that accepts the UDP packets and relays them out to registered listeners or something such similar.

After some quick Googling I found it would be quicker to have each developer just point a log monitoring tool at the output from a RollingFileAppender. BareTail seems to do a pretty good job.

Updated: When combined with a RollingFileAppender using XmlLayout Log4view works well to filter out the loggers.

Tuesday, November 11, 2008

Chinglish with cable tester

Posted by Picasa

This almost makes sense:

Do not use it beyond usage

But I'm really not sure what they were getting at with:

Do not change it on your mind

Monday, November 10, 2008

Find all stored procedures that contain a particular string

SELECT    so.Name, so.xtype as Type
FROM    dbo.sysobjects so
    JOIN dbo.syscomments scm ON =
WHERE scm.text like '%CorporationID%'
GROUP BY so.Name, so.xtype
or better yet:
SELECT  routine_name FROM INFORMATION_SCHEMA.ROUTINES WHERE routine_definition LIKE '%..%'

Wednesday, November 5, 2008

Detecting if the processor is 64 bit in a batch file

I needed a batch file to copy a different DLL depending on the processor architecture (one for x86 and one for x64).

Using the environment variables PROCESSOR_ARCHITECTURE did the trick.


Wednesday, October 29, 2008

ScriptResource.axd throws ArgumentOutOfRangeException

After doing a deployment from the build server in the NZ timezone to the production server in the US PST timezone I started seeing the following exception:

Exception information:
Exception type: ArgumentOutOfRangeException
Exception message: Specified argument was out of the range of valid values.
Parameter name: utcDate
Request information:
Request URL:

Turns out there were problems locating AJAX assemblies that, from the production servers perspective, were dated in the future.

The solution is to either wait for the timezone difference to sort itself out or to update the last modified date on the DLLS.

See the following link for an example of the latter.

Friday, October 3, 2008

Safari and Chrome "Red link" CSS bug

Came across a rather obscure CSS bug recently.

All the hyperlinks in the page were coming out red, regardless of the settings in the stylesheets. It was possible to change other properties, such as the background colour, but the text was always red in Safari and Chrome. IE7 and Firefox 3 showed the text as expected. It was like there was something overriding the defined styles.

Turns out the page in question had a CSS link in the HEAD tag to a file that didn't exist. The 404 page coming from IIS included styles to set the text to red. Somehow Safari and Chrome were using the styles defined in the 404 page as the CSS to be included. As the missing CSS file was the last in the list it was replacing the hyperlink colour.

Found another description of the problem here: CSS Advisor - Safari displays red links

Thursday, September 18, 2008

Compare schema between two databases

This is a bit rough, but the idea is to quickly find schema discrepancies between database1 and database2.
SELECT, l.type_desc,, m.type_desc
FROM database1.sys.objects as l
 full outer join database2.sys.objects as m on =
WHERE is null or is null

Wednesday, September 3, 2008

Tech Ed 2008

I think the song that was running on a loop in the corridors was by Opshop and is called Big Energy In Little Spaces

Tech Ed 2008 Day Three - DEV486 C# tips and tricks

Speakers: Jeremy Boyd, John Daniel Trask
  • PPTplex
  • Enum class to replace
    T blah = (T)Enum.Parse(typeof(T), value);
    var blah = Enum.Parse(value);
    See EnumHelper using generics to reduce casting
  • Codeplex
  • Umbrella
  • Utilities.NET
  • IDesign.NET - FormHost
  • Fluent Interfaces E.g. 3.March(2003)
  • Extension Methods
  • static methods in a static class
  • Link Bridge
  • IEnumerable Extensions
    Foreach(Person person in _nodes.OfType<x>(Person)) {}
    using(TransactionScope scope = new TransactionScope())
  • Invariance Checking
  • Object Initializer E.g. new DataTable{CaseSensitive=false};

Tech Ed 2008 Day Three - DEV313 Microsoft Visual Studio 2008 IDE tips and tricks

Speaker: Kirk Jackson
  1. Disable save on create
  2. Track Active Item in Solution Explorer
  3. Save new projects when created
  • Shortcuts:
  1. Ctrl + shift + space - show parameters again
  2. Ctrl + shift + f - find in files
  3. F8 + shift F8 - Edit.Goto Next/Prev Location
  4. ? - Box selection
  5. Ctrl + shift + v Clipboard ring
  6. Ctrl / ">" - Command Window
  7. Ctrl + F6 - ?
  8. F11 - Fullscreen
  • Object Test Bench

Tech Ed 2008 Day Three - WEB315 Object Oriented MS AJAX

Speaker: Scott Cate
  • Everything in Javascript is essentially a HashTable
  • String.format() from the AJAX library
  • Sys.StringBuilder
  • .apply(null, arguments);
  • Type.registerNamespace
  • Create methods with .prototype
  • Delegate
  • Events this.raiseEvent('overHeat', {OverMaxSpeed})

Tech Ed 2008 Day Three - SEC201 Do These 10 Things or Get 0wn3d

Speaker: Steve Riley
  • identity ≠ authentication
  • encryption ≠ integrity
  • inspection ≠ intent
  • secrecy ≠ trust
  • people ≠ technology
  • "Defense in depth" = "I am a parrot"
  • Stupidity ≠ malice
  • Usable ? secure
  • Microsoft isn't after world domination... only where there is land
  • AES - Advanced Encryption Standard

Tech Ed 2008 Day Three - WEB309 Silverlight 2 for developers

Speaker: Jonas Follesø
  • Silverlight does not normally deal with credentials
  • Model View ViewModel
  • Presentation Model/Pattern
if(HtmlPage.IsEnabled) { //web connection } else { //Mock Service }
  • Command Pattern to decouple interface from the actions
  • Strategy Pattern
  • Inversion of Control - Separate code to construct objects
  • Windsor, Unity, Ninject

Tuesday, September 2, 2008

Tech Ed 2008 Day Two - WEB317 Explore the new ASP.NET AJAX SP1 Script combining and history controls

Speaker: Scott Cate
  • Fiddler
  • ScriptManager EnableHistory="true" EnableSecurutyHistoryState Adds __historyFrame
  • JS pageLoad() - runs after page fully loaded (or AJAX postback)
  • Server
  • Combine
  • ScriptManager
  • ScriptReference
  • CompositeScript
  • Encrypted by machine key (important to consider for a server farm)
  • ScriptProfiler
  • Faster load time.
  • Script Combining - What's the big deal?
Not part of the presentation, but RPO (Runtime Page Optimizer) is another option for improving script performance.

Tech Ed 2008 Day Two - WEB308 Pumping iron: Dynamic languages on .NET

  • (Speaker: Harry Pierson)
DevHawk Dynamic - more at runtime than compile time. E.g. JavaScript Type creation Can manipulate more at runtime. Less security that is provided by the compiler More flexibility. Sual Scheme - definition in multiple places infinity - 1 types of errors. Can't ship by just compiling Static languages have the edge for performance Short on ceremony Whitespace is significant - convention. Aspect oriented programming - cross cutting concerns Functional programming programming Meta programming Interop with other .NET code Embeddable

Tech Ed 2008 Day Two - SOA309 Implementing RESTful Services with Windows communication foundation 3.5 concepts and introduction (Part 1 of 2)

  • (Speaker: Rob Ragby) REST - Representational State Transfer Tenets Work the way the web works Simple and Open Unified API - HTTP Linked Resources Services Scale Best When - Stateless, Cached (built into the HTTP protocol) Hi-REST - Purists/Zealots Lo-REST - Pragmatists SOAP vs REST webHttpBinding Fx 3.5 WebGet WebInvoke POST/PUT/DELETE WCF REST StarterKit enableWebScript httpbinding webHttp No reason, or method, just madness.

Tech Ed 2008 Day Two - WEB313 Advanced Cross-Browser layout with Microsoft Internet Explorer 8

  • (Speaker: Matt Hellar)
Transition to standards Full CSS 2.1 compliance Depreciation of hasLayout (bolted CSS support into IE) Tenet # 1 - Better support for web standards Compatibility view to the right of the address bar replaces emulate IE 7 button Tools > Compatibility View Settings Content="IE=EmulateIE8" Tenet #2 - Allow developers to choose IE7 compatibility mode if they want/need it. IE <= 6 Quirks mode, IE 7 Standards mode Meta overrides - Also changes the user agent string - IE 8 may pretend to be an earlier browser Quirks IE=5 IE7Standards IE=7 EmulateIE7 IE=EmulateIE7 IE8 Standards IE=8 EmulateIE8 IE=EmulaterIE8 AlwaysUseLatestMode IE=edge document.documentMode

Tech Ed 2008 Day Two - WEB304 Web futures - the next 18 months

Speakers: Jork Odolphi, Harry Pierson, Scott Hanselman, et al.
  • PRISM - Turn a Web Application into a desktop application. Dedicated link and window.
  • Ease of use - efficiency Ease of learning
  • "Moved my cheese"
  • Ways to draw attention using a fear response: Saturated Colour Faces Animation
  • - onenote for the web. Includes OCR
  • Cooliris, formally known as PicLens

Tech Ed 2008 Day Two - SOA305 Getting workflows running and talking in your applications

  • (Speaker: Mark Rees)
Use for: Long Running Episodic - Start/Stop State Machine or sequential Will it increase your productivity One workflow runtime per app domain. Typically create the workflow runtime using the singleton pattern. Each workflow will have an instanceID GUID that is used to reference instance beyond the lifetime of the application. SqlWorkflowPersistenceService Threading - 1 thread per worklow at any time. Give thread safety and Data syncronisation. However, there is no assurance that it will always be on the same thread. Thread affinity. Default scheduler from the thread pool. Async to the caller thread (returns instantly) Manual Scheduler - caller thread will wait for the workflow to return. Important for controlling the number of threads. High load environments. Has different behaviour for handling delays. Will need to manually resume. True will create a new thread to resume after the delay. Persistence In memory by default. Can't handle restarts. SqlWorkflowPersistenceService - Scheme and Logic (stored proc) install scripts DB polling time defaults to 60 seconds select * from InstanceState Tracking Capture events and data during the execution of a workflow. Performance measurement Profiles to filter what to track - points and locations Tracking_schema.sql Tracking_Logic.sql Useful to let processes outside of workflow know the state. Communication Input/output params .NET 3.0 External Data Exchange Model Recommend Microsoft .NET 3.5 Send Receive Activity Full WCF for WWF. Send - Call a WCF Service Receive - A WCF Service will call the workflow WorkflowServicehost - WCF WWF Hybrid ContextBinding for WWF like wsHTTPBinding with instanceId in header

Monday, September 1, 2008

Tech Ed 2008 Day One - DEV 335 Visual Basic 2008: Developer Productivity

  • (Speaker: Nick Randolph)
This was not really for me being a C# developer. Was hoping to pick up some interesting tips. I should have probably gone to BIN252 on SQL Server 2008 reporting services.

Tech Ed 2008 Day One - WEB 302 ADO.NET Data Services - The zen of RESTfulness and the Art of "Astoria"

  • (Speaker: Scott Hanselman)
POX - Plain old XML REST - Representational State Transfer HTTP GET, POST, PUT, DELETE ADO.NET Date Services This code was generated by a tool. tcpTrace - port forwarding Ctrl + . - Intillicrack DataService.js Fiddler MCSE (Microsoft Certified Solitaire Expert)

Tech Ed 2008 Day One - DAT 302 Overview of SQL Server 2008 - new features

  • (Speaker: Jeremy Boyd)
  • Auditing to file
  • windows application log
  • windows security log
  • Native Encryption
  • Enhanced Mirroring - Auto Page repair and log stream compression

sp_estimate_data_compression_savings ROW/PAGE

Filtered Index
Create Nonclusted index blah on (blah, blah) WHERE PID >= 27 AND PID <= 36;

Resource Governor
(Handles Contention) E.g Limit resources used for reporting. Resource Pools, Workload Groups, Classifier Functions (Which workload group to assign a connection to)

New Data Types
Date, Time, DataTime2 (System clock precision), DatetimeOffset (For use with timezones) select * from sys.systypes where name like '%date%' or name like '%time%' SELECT SYSDATETIME() AS SYSDATETIME, SYSDATETIMEOFFSET() as SYSDATETIMEOFFSET, SYSUTCDATETIME() as SYSUTCDATETIME SELECT SWITCHOFFSET ( '2005-01-20 23:00:00.00000 +4:00', datepard(TZoffset, sysdatatimeoffset()) TODATETIMEOFFSET - Adds timezone information to a DateTimeOffset.

HierarchyID - supports depth-first and breadth-first indexes. CLR based. Parent.GetDescendant(Child1, Child2) Node.IsDescendantOf() Node.GetLevel GetRoot Node.GetReparentValue(oldParent, newParent)

Grouping Sets - multiple group by clauses

Multirow insert CREATE TABLE tbl_RowCon (PDT VARCHAR(10) PRIMARY KEY, val int) INSERT tbl_RowCon VALUES ('PDT A', 10), ('PDT B', 5), ('PDT C', 10)

+= assignment

Merge Statement insert (DML statement combining multiple operations into one) WHEN MATCHED THEN (so UPDATE) WHEN NOT MATCHED THEN (so INSERT) SOURCE NOT MATCHED (so DELETE)

conditional insert

Table parameters - Readonly when used as a parameter. - using multiple parameters requires multiple round trips for multirow data. - temporary tables use disk resources and could be prone to locking. Leads to stored procedure recompilation. + offers more flexibility. Well defined scope - won't require locks. Can reduce round trips. CREATE TYPE EmployeeTableType AS TABLE (EmpID INT, EmpName nvarchar(100))

Spares columns - Generally the column wont have any data c XML COLUMN_SET FOR ALL_SPARSE_COLUMNS Values stored in XML will be expanded out to columns.

Large user defined types supported (>8000)

Spatial Data - Vector based. Geometry (Points, line strings, polygons) - Geography (geodetic)

Filestream Storage Attribute on varbinary(MAX) Use when objects are larger than 1MB and provides faster read access. Small objects are often better stored in the database. Exists as a folder on disk as specified - $FSLOG & filestream.hdr (header) .PathName() - filepath of the varbinary(max) column.

Tech Ed 2008 Day One - SOA 205 Extending the application platform with cloud services

  • (Speaker: Chris Auld)
XOML (Basically XAML)

Tech Ed 2008 Day One - WEB 301 ASP.NET MVC - Should you care?

(Speaker Scott Hanselman)
  • bin deployable (System.Web.Adstractions, System.Web.Mvc, System.Web.Routing)
  • Testable via System.Web.Abstractions
  • Rely more on convention over configuration (I.e. expected folder structure). The idea being reduced complexity.
One man's magic is another man's convention.
  • In the stack trace window in VS 2008 - Show External Code
  • The general flow of a page request is controller > model > view > render
  • The routing components aren't specific to the MVC web applications.
  • MVC Contrib
  • NHaml
  • Moq
  • ASP.NET MVC doesn't use viewstate or postbacks (In the sense of a more traditional ASP.NET web application)
  • ZoomIt - Presentation tool

Tech Ed 2008 Day One - Keynote

Live Mesh Folders At first glance it appears to be a internet based file sync tool with the added ability to share the folders with friends and family. All files must be sync'ed up to the online storage, although it also appears to sync directly across the local network.

Remote Desktop There is also the ability to create a type of remote desktop session. Sitting at home on my local network it doesn't appear to make much use of p2p technology as a remote session between my desktop and laptop is painfully slow compared to a standard remote desktop connection.

Sunday, August 31, 2008

Auckland Codecamp 2008

Links and resources from Codecamp:

Thursday, August 14, 2008

Viewstate and the C# ?? null-coalescing operator

The ?? (null coalescing) operator is a handy way to check whether a value is null, and if so return an alternate value.

I find it particularly useful in combination with viewstate for putting terse properties on user controls with default values.

/// A Property that defaults to false unless set otherwise.
public bool SomeProperty
  get { return ViewState["viewstateKey"] as bool? ?? false; }
  set { ViewState["viewstateKey"] = new bool?(value); }

See Also: Scott Gu - The C# ?? null coalescing operator (and using it with LINQ)

Wednesday, August 13, 2008

Microsoft .NET Framework 2.0 - Application Development Foundation - Multicast Delegate

During my study for the 70-536 exam I came across a blog page with some questions from the exam. One of which is about multicast delegates:
Q. You need to write a multicast delegate that accepts a DateTime argument and returns a Boolean value. Which code segment should you use?
  1. public delegate int PowerDeviceOn(bool, DateTime);
  2. public delegate bool PowerDeviceOn(Object, EventErgs);
  3. public delegate void PowerDeviceOn(DateTime);
  4. public delegate bool PowerDeviceOn(DateTime);
The first observation I'd make about the available answers it that they are all missing the parameter names. They may also be missing ref and/or out keywords. Who knows. I'll assume that only the parameter names are missing.

Looking past that, I've seen comments floating round the web that "Multicast delegates must contain only methods that return void". This is misleading. It's quite possible to have a return value. See the MSDN article Multicast Delegate Internals, particularly the "Method Returns and Pass-By-Reference" section towards the end.

The issue identified in the above article is that if the "subscribers return a value, it is ambiguous which subscriber’s return value would be used". In cases such as this where the return value from each invoked method is of interest the MulticastDelegate.GetInvocationList() method can be used to manually enumerate through the list of subscribers and call them individually.

While it is possible to have return types other than void I'd be wary of doing so in practice unless there was a compelling reason.