OdeToCode IC Logo

The Canonical Transaction Example Is Flawed

Monday, February 28, 2005 by scott

Almost every article ever written about database transactions includes the example of an ATM machine dispensing money. The articles will describe how the bank uses a transaction to prevent people from overdrawing the account during simultaneous access, or how the bank can rollback a transaction if an error occurs at the ATM.

They are all wrong.

About 7 years ago I went to a local ATM, punched in my PIN, and asked the ATM to withdraw $80 from my account. The machine thought about the request for a bit, and then started to make the happy fluttering noise ATM machines will do just before delivering cash. The happy fluttering noise was followed by a fateful POP sound in the distance, and then a total blackout. Power failure.

When power came back seconds later I still had no money, and the ATM had an OS/2 boot screen.

Cool! I remember thinking. The bank’s database just rolled back my transaction! I drove off in search of a working machine. Of course I was a bit younger then and had not learned the secret mission statement of every major financial institution: “Customer inconvenience is our first priority”. When my bank statement arrived the next month I was genuinely surprised to see the bank had committed the $80 transaction against my account.

One might think ATM machines would be equipped with some sort of UPS to keep them running in the event of a power failure during an open transaction, but one would be forgetting the second mission statement of all financial institutions: “Mistakes are acceptable, as long as we screw the customer and not ourselves”.

For the curious, here is how the story ends.

A month later I went to the bank, approached a teller, and told her if she gave me $80 in unmarked bills nobody would get hurt.

Well, not really, but it felt that way.

I showed the teller my statement and told her my story. She asked me to stand by a door to the left and walked through a back door behind the counter.

While waiting in the lobby I thought about the possibility of the teller returning to tell me the bank records were never wrong. Not only would I not get my $80 back, but they’d deduct a $10 service fee for seeing me in person. I’m always optimistic like that when dealing with banks. Thieves.

I was surprised when a woman burst out from the door beside the counter, ran over and practically hugged me. The bank had noticed an $80 discrepancy in the ATM records and this lady’s sole purpose was to find out what happened. I made her day and got my money back.

The End.

Roadmap To Delegation

Friday, February 25, 2005 by scott

One of the thorny areas in writing a distributed application is keeping the logical thread of execution authenticated and authorized as calls hop from server to server. If you want to flow the original client’s identity across these servers you’ll quickly run into the “single network hop” restriction of NTLM (sometimes called the “double hop” issue). A client’s identity can only make a single hop. The first hop happens from the web browser to the web server. The web server can impersonate the client when accessing local resources, but it make a second hop to a third machine. Larry Osterman has details on this behavior.

The single hop issue turns up a lot these days as more products (Reporting Services, SharePoint) rely on Windows authentication, but we rarely see these applications on the same server as our ASP.NET applications.

One solution to the problem is the trusted subsystem model. However, the trusted subsystem model does not flow the original client’s identity automatically, and it becomes your application’s responsibility to perform authorization checks. Tricky.

Another solution is to use Kerberos delegation. If you want to enlighten yourself on the subject, I’d recommend the following roadmap.

Start with David Chappell’s “Exploring Kerberos, the Protocol for Distributed Security in Windows 2000”, and chase this article with Keith Brown’s “Exploring S4U Kerberos Extensions in Windows Server 2003”.

The next step is to watch delegation in action. A two part webcast walks through every detail of setting up delegation in a typical ASP.NET application environment: “Getting Delegation to Work with IIS and ASP.NET: The Ins and Outs of Protocol Transition” (Part 1 and Part 2).

At this point it’s time to take the IT department out to lunch, or perhaps send fruit baskets to their house. You’ll need their sign-off and support to pull it all off.

Two documents that can help during the implementation phase are “HOW TO: Configure an ASP.NET Application for a Delegation Scenario” and “Troubleshooting Kerberos Delegation”.

Just imagine how popular you’ll be at the next neighborhood social event if you can hang out at the punch bowl and explain the nuances of S4U2Self and S4U2Proxy.

OpenMyMind.net

Wednesday, February 23, 2005 by scott

Karl Seguin’s site (OpenMyMind.net) has some good articles for ASP.NET developers. The two articles on creating multilingual websites (Part I, Part II) jump out at me, and the “Mastering Page-UserControl Communication” is a must read if you are starting to write user controls which interact with the parent page. (Hint: using Request.Form or FindControl to pull values from a user control is path filled with peril).  

Reporting Services & VSLive! Miscellany

Tuesday, February 22, 2005 by scott

Maxim Karpov has a nice post about his VSLive! experience. Max is a bright guy and a blast to hang out with.

I’m still tying up lose ends and requests for information from my presentation on SQL Server Reporting Services Integration.

If you have any performance or exporting problems, make sure you have Service Pack 1 in place. To determine the version of Reporting Services, go to the base URL for the report server (typically http://machinename/reportserver/). At the bottom of the browser page will be the version number - 8.00.878.00 is SP1.

To see what is the future holds with Service Pack 2, see Geoff Snowman’s webcast: “New Features in Reporting Services Service Pack 2”. We are still waiting for the blog to update, Geoff.

In ASP.NET we are used to sorting data in a DataGrid by clicking on a column header. This same functionality is difficult to achieve in SSRS, but see MSFTie Bruce Johnson’s newsgroup post to see one approach (copy out the inline RDL and paste into a new report). I believe sorting will be much easier to implement in the 2005 version of Reporting Services.

If you have the Enterprise edition of Reporting Services and want to look at custom authentication schemes, try the article “Using Forms Authentication in Reporting Services” for some background information and a code to build on. Also, there is a data processing extension to read XML files on GotDotNet.

Finally, there are some articles here on OdeToCode to help with learning the web service API:

For anyone looking on information on setting up Kerberos delegation with ASP.NET, I have a post in the works for that topic…

CodeBetter.com

Monday, February 21, 2005 by scott

Raymond is wondering what people think of CodeBetter.com. Let me tell you what I think.

The real problem with group blogs is the number of people who post breaking news – like “Microsoft is going to release IE7!”. Oh, wait – that’s not a problem on CodeBetter.com.

It’s good to see the CB’ers function as a group. Instead of sounding like a scratched CD, they feed off each other to build better content. It’s collaborative and interesting. CodeBetter.com is what a group blog should be. I like Darrell’s agile news, Brendan’s forays into the .NET framework, Geoff’s quirkiness, and then there is Sahil. Let me tell you about Sahil. Sahil came to the Columbia user group meeting last month to give a talk on serialization. During the talk he serialized DataSet objects, customer objects, and Star Trek characters with two different versions of .NET. I thought I was going to leave the building as a blob of 1,568 bytes on Sahil’s hard drive.

Keep up the great work CB’ers, and Raymond – keep the OOP articles coming. These articles are well written and I know many people will benefit.

P.S. I know many people don’t like the amount off “off-topic” material on other group blogs. Me? I like to know what people are feeding their cat every now and then. For example, you never know what you’ll see or hear on the John Elliot and Bill Ryan blogs, but I find their blogs delightfully entertaining. Perhaps they are never boring because John cuts code 20 hours a day and Bill is a philosophy major and insomniac. I say this even though John calls me names and Bill leaves me hanging in San Francisco. Thanks, guys.

Reporting Services and Scriptomatic

Saturday, February 19, 2005 by scott

This week I’m going to tie up some lose strings from my VSLive! presentation…

One can programmatically interact with Reporting Services across the network by sending requests via an URL, via a web service request (SOAP), and via Windows Management Instrumentation (WMI). Of these three – I spend no time covering WMI because it’s typically not an interface used to deliver features to end users. I’ll provide some more information here.

In general, WMI exposes classes to configure and mange both hardware and software on computers throughout the network. Reporting Services provides WMI classes that let us query and make changes to report server configurations.

WMI is one of those pieces of software that requires a reference manual nearby unless you work with it everyday, but there is a very easy way to get started: Scriptomatic 2.0. Just pick a WMI class and the tool will code-gen a runnable sample script in VBScript, Jscript, Python, or Perl. Scriptomatic itself is an interesting application written as a single HTA file and run in IE.

Here is a script from Scriptomatic showing the properties of the MSReportServer_ConfigurationSetting class from the root\Microsoft\SqlServer\ReportingServices\v8 namespace:

On Error Resume Next

 

Const wbemFlagReturnImmediately = &h10

Const wbemFlagForwardOnly = &h20

 

arrComputers = Array("REPORTING")

For Each strComputer In arrComputers

   WScript.Echo

   WScript.Echo "=========================================="

   WScript.Echo "Computer: " & strComputer

   WScript.Echo "=========================================="

 

   Set objWMIService = GetObject("winmgmts:\\" & strComputer & _

            "\root\Microsoft\SqlServer\ReportingServices\v8")

   Set colItems = objWMIService.ExecQuery _

           ("SELECT * FROM MSReportServer_ConfigurationSetting", "WQL", _

            wbemFlagReturnImmediately + wbemFlagForwardOnly)

 

   For Each objItem In colItems

      WScript.Echo "DatabaseIntegratedSecurity: " & _

                       objItem.DatabaseIntegratedSecurity

      WScript.Echo "DatabaseLogonName: " & objItem.DatabaseLogonName

      WScript.Echo "DatabaseLogonPassword: " & objItem.DatabaseLogonPassword

      WScript.Echo "DatabaseLogonTimeout: " & objItem.DatabaseLogonTimeout

      WScript.Echo "DatabaseName: " & objItem.DatabaseName

      WScript.Echo "DatabaseQueryTimeout: " & objItem.DatabaseQueryTimeout

      WScript.Echo "DatabaseServerName: " & objItem.DatabaseServerName

      WScript.Echo "Impersonate: " & objItem.Impersonate

      WScript.Echo "ImpersonateDomain: " & objItem.ImpersonateDomain

      WScript.Echo "ImpersonatePassword: " & objItem.ImpersonatePassword

      WScript.Echo "ImpersonateUserName: " & objItem.ImpersonateUserName

      WScript.Echo "InstallationID: " & objItem.InstallationID

      WScript.Echo "InstanceName: " & objItem.InstanceName

      WScript.Echo "PathName: " & objItem.PathName

      WScript.Echo "UnattendedExecutionLogonDomain: " & _

                      objItem.UnattendedExecutionLogonDomain

      WScript.Echo "UnattendedExecutionLogonName: " & _

                      objItem.UnattendedExecutionLogonName

      WScript.Echo "UnattendedExecutionLogonPassword: " & _

                      objItem.UnattendedExecutionLogonPassword

      WScript.Echo "VirtualRoot: " & objItem.VirtualRoot

      WScript.Echo

   Next

Next

 

 

If you’d rather have the code in .NET, then the System.Management namespace contains all the WMI goo. WMI is probably underutilized due to the quirky mixture of SQL like syntax with a namespace traversed like a file system. It seems powerful, and it’s something I need to keep in mind next time I need a configuration script.

The 5 Stages Of Mocking

Thursday, February 17, 2005 by scott

When we write unit tests, we write a piece of test code to verify a piece of production code. The trouble is, production code has the nasty habit of relying on dependencies that are hard to control. Dependencies may be infrastructure dependencies like SMTP servers and databases, or may be software dependencies that are non-trivial to setup and get into the correct state for testing.

Mock objects remove these dependencies and simplify unit test code. A mock object is a stand-in replacement for a real-world domain object. For more details about mock objects, see “Mock Objects to the Rescue!”.

When I first began reading about mock objects, I did not like what I was reading. In fact, I disliked the idea so much, I entered ….

Stage 1: Denial

I found my eyes leaping over any pages containing the four letter m word. I felt confident in my gut reaction that m*ck objects were a fad –

- the same gut feeling I had when I heard of a new language by the name of C#.

As time passed, I realized the m*ck object talk was still picking up steam, and I entered ….

Stage 2: Resentment

I decided ‘object mockery’ was no longer a fad, but a placebo in source code form. Software development teams relying on mock objects would develop overconfidence in the quality of their product. These teams could watch their house of mock playing cards crumble in the cruel hands of the real world.

“Fools!”, my inner voice would yell in a Gandalf like tone. My inner voice always sounds like Gandalf or Ed Norton Jr. when I’m agitated.

As time went on, I began to write unit tests, and watch others write unit tests. Slowly … gradually … I entered ….

Stage 3: Bargaining

Some methods cry out for a unit test. Perhaps the method has logic to react to an SMTP error message, or perhaps the method has an exception handler to recuperate from a network error. These error conditions are difficult to trigger at just the right time, but I have to know exactly how the code will react. Unit tests are addictive that way. I found myself thinking about writing mock objects just to force these error conditions.

Suddenly, I was an object mocker.

The days grew long, and grey. One rainy night while sitting in my car - I hit bottom. I found myself tuning the radio to a country music station, and singing along to an old George Jones tune. I had officially entered …

Stage 4: Depression

I thought about the burden faced by the universe of software development. Any object I can think of will need to be mocked somewhere, in some program. Forget databases and mail servers. We will mock water fountains and pizza ovens. We will mock robot arms and booster engines. We will mock the stars and the sun. Yes, even the moon. The moon must be mocked.

Mock me, will you?

I’ll mock you, too….

I thought about starting a web site (Mock The World) and selling t-shirts, but I figured only lunatics and government agents would be interested and I didn’t follow through. It took some time to work out of my funk, but eventually, I reached …

Stage 5: A Wary Acceptance

I accept mock objects for what they are – a technique to simplify the creation of effective unit tests. I’m always worried, however, about assumptions. Production code contains assumptions about how other objects will behave. Mock objects have a high probability of encoding those same assumptions, and we end up testing tautologies.

 
Assert.IsTrue( mockWeather.RainTommorow || !mockWeather.RainTommorow). 

In software development, we always find a better way to build a mousetrap…

So, anyone using Mock Objects or NMock?