Jun 232011
 

 While it all makes sense now, it didn’t make sense when I first saw this warning message:

Warning 304 The version of the .NET Framework launch condition ‘.NET Framework 4 Client Profile’ does not match the selected .NET Framework bootstrapper package. Update the .NET Framework launch condition to match the version of the .NET Framework selected in the Prerequisites Dialog Box.

 While building a Setup project, which hosts a Windows Service that requires the full .NET Framework 4 profile, this warning message appears. I do not accept warnings or error messages in my code, so naturally I must seek and destroy the cause of this message. Before you do the following, make sure that the client profile selected matches between your project properties and the .NET framework profile on the prerequisites screen from the setup project’s properties screen.

After the setup project’s prerequisites match your project’s client profile, change the profile for your setup project’s installer Launch Conditions.

  1. Right-click on the setup project, select View and then Launch Conditions.
  2. Click on .NET Framework under Launch Conditions.
  3. Change the Version in the properties window to match the client profile selected in the project properties and setup project prerequisites.
Launch Conditions in Visual Studio

Launch Conditions Settings in Visual Studio

May 082010
 

Despite its pitiful adoption in the developer community, I am implementing Transactional NTFS (TxF) transactions using the Microsoft.KtmIntegration.TransactedFile class. This allows me to reap the benefits of TransactionScope and distributed transactions for file operations (e.g. creates, updates, deletes). This is the only missing piece for typical transactional business applications. With the “KTM” and “KtmRm for Distributed Transactions” services, available only on Vista, Windows 7, and Windows Server 2008, file operations will roll back if the TransactionScope is not completed.

There’s just one problem. Transactional NTFS does not work with file shares. I can?t remember the last time I put a “C:FileStore” reference in a config file. A friendly share like \serverFileStore is always preferred, especially since DFS came about. Attempting to use a share results in the following error message:

The remote server or share does not support transacted file operations

Don’t read this as “your remote server” or “your remote share”, but rather “all remote servers and shares”. As mentioned in this MSDN article, TxF is not supported by the CIFS/SMB protocols. The error was probably written with the expectation that one day some remote servers and shares would support TxF. I emailed Microsoft about it and received a response fairly quickly. The response was simply:

“We understand the need and have plans to eventually support TxF over SMB2, but we?re not there yet and are not ready to announce if or when this will be supported. When it is the documentation will be updated.”

I’m not getting my hopes up, but Windows Server 2011 looks to be our only hope before .NET changes beyond recognition and TxF is a distant memory. Until then, I wrapped up all of my TxF code in a WCF service and install that service on the server with the FileStore folder.

MSDN article – When to Use Transactional NTFS

      http://msdn.microsoft.com/en-us/library/aa365738(v=VS.85).aspx

TxF Sandbox – Sample Projects (including Microsoft.KtmIntegration.TransactedFile)

      TxFSandbox.zip

Apr 222010
 

The sole 2010 offering in the USA of IDesign‘s Architect’s Master Class conducted by the man himself, Juval Lowy, is only a few weeks away. I checked in at the IDesign web site, and found some updates the world needs to see.

If you want to learn something new every day, start at the top of the IDesign Code Library and step through one example each day. Be careful, you might need to re-write every line of code you’ve ever written.

Nov 272009
 

I’ve been talking about Geneva for a long time. I got the basics down earlier in the year. I tried to come up with my own set of sample apps, but failed to get anywhere. With the official release, and renaming to Windows Identity Foundation (WIF), I have renewed inspiration.

I read Michele Leroux Bustamante’s MSDN magazine article, Claim-Based Authorization with WIF, last night. After reading the article, I was confident that I could get a claims-aware WCF service stood up with a custom STS in a matter of hours. Today I downloaded and installed WIF. I also installed the WIF SDK and all of the prerequisite hotfixes. I perused the readme files and looked through some of the samples code. Everything is layed out sensibly, the samples are commented sufficiently, and the samples include setup and cleanup batch scripts when necessary.

The samples include:

Quick Start

  1. Simple Claims Aware Web Application
  2. Simple Claims Aware Web Service
  3. Simple Web Application With Information Card SignIn
  4. Simple Web Application With Managed STS
  5. Claims Aware Web Application in a Web Farm
  6. Using Claims In IsInRole

End-to-end Scenario

  1. Authentication Assurance
  2. Federation For Web Services
  3. Federation For Web Applications
  4. Identity Delegation
  5. Web Application With Multiple SignIn Methods
  6. Federation Metadata

Extensibility

  1. Claims Aware AJAX Application
  2. Convert Claims To NT Token
  3. Customizing Request Security Token
  4. Customizing Token
  5. WSTrustChannel
  6. Claims-based Authorization

All of the samples I’ve run through so far are great. The only thing that I’m not in love with is all the XML required to wire this stuff up. Maybe some Juval-style extensions would make it less painful.

One more thing – it looks like all of the XP users will finally have to upgrade. WIF only works with Vista, Win7, and Win2008. I heard that Win2003 compatibility will arrive in December.

Download Windows Identity Foundation

Download Windows Identity Foundation SDK

Oct 292009
 

Using the NetTcpBinding on a WCF service is secure by default. Unless you override the default settings, you will enjoy Transport Security using Windows authentication and the EncrpytAndSign protection level. When you create a new WCF service library, Visual Studio creates a config file with the following identity block:

   24           <identity>

   25             <dns value=”localhost“/>

   26           </identity>

 

If you wipe this config file clean like me to write a much cleaner and shorter config file, this identity block is the first thing to go. Sadly, most people also add a binding configuration with <security mode=”None”/>. I have done this too in an Intranet environment. The samples and book examples out there don’t show how to write an actual production environment service that cares for different machines in the same domain. While the default settings work when testing on your local machine, they don?t work in a simple Intranet environment.

Most of the difficulty I experienced when starting to work with WCF was getting security to work with the TCP binding. Everything worked so easily during development, but everything broke down once deployed to the development server. It didn’t help that the only errors I saw were timeout exceptions. If I had known about the Service Trace Viewer, I could have easily determine the cause and Googled (Bing wasn’t around then) for a solution. Instead, I chose the easier (and much less secure) way out; rely on my firewall and turn security off.

As mentioned before, the NetTcpBinding is secure by default with transport security using Windows authentication. The problem most experience when moving the service to a different machine is caused by NT authentication failing. If you use svcutil to generate your client config file and your host doesn’t have the identity block mentioned above, svcutil will not add a key piece of information to the client config file. The missing element is, you guessed it, the identity block. Without it, you will likely get an exception and see a stack trace similar to this:

[System.ServiceModel.Security.SecurityNegotiationException: A call to SSPI failed, see inner exception.]

[System.Security.Authentication.AuthenticationException: A call to SSPI failed, see inner exception.]

[System.ComponentModel.Win32Exception: The target principal name is incorrect.]

If you add tracing to your client, you will see that without specifying an identity block WCF will make the call with a DNS identity set to the name of the host. Notice the blue arrows.

image

You can see that the EndpointReference does not have an <Identity> block. Without that identity block, WCF cannot create a valid ServicePrincipalName. You can find this in Reflector, following this path:

  • System.ServiceModel.Channels.WindowsStreamSecurityUpgradeProvider+WindowsStreamSecurityUpgradeInitiator.OnInitiateUpgrade() – This is where the SecurityNegociationException is being thrown.
  • System.ServiceModel.Channels.WindowsStreamSecurityUpgradeProvider+WindowsStreamSecurityUpgradeInitiator.InitiateUpgradePrepare() – This method populates an EndpointIdentity and ServicePrincipalName to be used immediately after for NT authentication.

image

When the identity is not specified, it falls back to trying to create an SPN from the host address. I have seen this work on a machine that has two DNS names, using the DNS name that does not match the NETBIOS or AD name for the machine. I’m not exactly sure why that works.

Having any of the following identity blocks in your client config file will cause WCF to take the first path that successfully creates an SPN needed to perform NT authentication in the AuthenticateAsClient method called from OnInitiateUpgrade():

  • <dns value=”serviceHostName”/>
  • <dns/>
  • <servicePrincipalName value=”domainhostServiceUserAccount”/>
  • <servicePrincipalName/>

Having these <Identity> settings in your client config file adds the appropriate <Identity> settings in the <EndpointReference> used when opening the channel.

image

Security seems more mysterious when going rogue and writing your own config files. If you go rogue, make sure you use the appropriate <Identity> blocks. With this mystery solved, <security mode=?None?/> is a thing of the past. Now we can keep our services secure in an Intranet environment.

Oct 142009
 

Web services are just the tip of the iceberg in WCFI was privileged to attend the IDesign WCF Master Class last week. It only comes to the USA one time each year, and is presented by the one and only Juval Lowy. The class is held at the training center on the Microsoft Silicon Valley campus in Mountain View, CA. Five very intense days of WCF covering all aspects of WCF from essentials like the ABCs to the most intricate details about advanced topics like concurrency, security, transactions, and the service bus.

What we’ve been told sold about WCF from Microsoft is truly just the tip of the iceberg. Juval presents countless examples that prove WCF is not just about web services. WCF is the evolution of .NET, providing world-class features that no class should ever be without.

Demos, samples, and labs are presented using .NET 3.5 and 4.0 with an emphasis on the new features and functionality in 4.0. Discovery and announcements are the most underrated and unknown new features of WCF 4.0. After seeing Juval’s demos on discovery and announcement, I can’t imagine creating services without them.

More than all of the WCF content, the class gives you a lot to think about regarding architecture, the framework, and engineering principles. Juval’s mastery of .NET is evident in his ServiceModelEx library that extends almost all aspects of WCF and the service bus. His “one line of code” motto makes it possible for all of us to configure our WCF services with ease. The ServiceModelEx library is a good example for all developers to know and understand how to “do .NET” the right way. It exemplifies the best of what .NET and WCF have to offer.

Check out the IDesign website to get the WCF Resource CD (containing many of the examples and demos from the class). Also note the next class dates and sign up for the IDesign newsletter.

Sep 032009
 

The 2009 Jacksonville Code Camp was a great success. Many thanks to Bayer, Brandy, and everyone else that made it happen. The bar has been set really high for future Jacksonville code camps, and for the rest of Florida too.

My session on Transactional WCF Services went well. Many great questions and compliments after the session. If you attended and have any unanswered questions, please email me.

You can download the session files below. It contains staged versions of all of the transaction modes we discussed. It also contains a tracing solution and tracing result files to view the client and host tracing files in Client/Service mode. Also see my previous post on using the Service Trace Viewer. It also contains a few demo projects that we didn’t get to in the one-hour session.

Files/Solutions included in Session Archive:

  • PowerPoint slides
  • Transaction Promotion Code Snippet
  • Testing database backup
  • Testing SQL script (query and cleanup between tests)
  • IDesign ServiceModelEx Project (used by all included Solutions)
  • Code Demo Solutions

Code Demos include:

1. TransactionScope – Shows how single/multiple resource managers affect which Transaction Manager is chosen to handle the scoped transaction. Also gives first look at transaction promotion detection.
2a. Mode None – WCF transaction mode with which no transactions are created or flowed from the calling client.
2b. Mode Service – WCF transaction mode with which no transactions are flowed from the calling client, but a transaction is created for your service operation.
2c. Mode Client – WCF transaction mode with which a transaction is required to be flowed, and the service will only use the client transaction.
2d. Mode Client/Service – WCF transaction mode with which a client transaction will be flowed and used by the service, if available. If no client transaction is flowed, a transaction will be provided automatically for the service operation.
3. Explicit Voting – Shows how explicit voting with a session-mode service is performed using OperationContext.Current.SetTransactionComplete().
4a. Testing Various Resource Managers – Shows how a client can use a single TransactionScope to call several services (some transactional, some non-transactional), a database stored procedure, and an IDesign volatile resource manager Transactional<int>.
4b. Testing Services – Provides a host project for a transactional service and a non-transactional service used in 4a.
5a. Tracing – Same as 2d. modified with the additional app.config settings in the client and host projects to allow for service tracing to .svclog files.
5b. Tracing Results – Stored results from executing 5a. in case you don’t want to load the database and actually run the projects. The .stvproj file can be opened directly in the Service Trace Viewer. On the “Activity” table, click on the activity “Process action ‘http://services/gotjeep.net/GpsTrackServiceContract/SubmitTrack'” then click on the “Graph” tab. You will see that the client and host activities where the arrow moves from client to host (send and receive message, respectively) show the OleTxTransaction in “Headers.” The next activity in the host reads “The transaction ‘5bd25b08-848c-409d-9163-6303b9138382:1’ was flowed to operation ‘SubmitTrack’.”

 

Download the session files:
TransactionalWCF.zip (854 KB)

Apr 112009
 

Important, proven, and universally-useful technologies like WCF and Mobile are still not well-known in the development community. Many believe there is another boom, similar to the 1992 Internet boom, on the horizon that will require skilled and knowledgeable developers to engineer the framework and associated connecting systems. Staying tech-current and adapting to our new world is an absolute necessity. Don’t become the COBOL programmer of the future. Knowing these great system-connecting technologies (WCF, Mobile, Cloud, etc.) will quickly become a requirement to compete in the software industry.

Check out the following interview with Richard Campbell (DotNetRocks, RunAs Radio) and Juval Lowy (IDesign) talking about the EnergyNet at the DevConnections conference. The growing hype about alternative energy and the EnergyNet is stunning. Technology has progressed far enough where we can start to tie together disparate systems to benefit producers and consumers alike.

http://video.google.com/videoplay?docid=4831440850220717845

Jan 292009
 

“Do not anticipate trouble, or worry about what may never happen. Keep in the sunlight.” 

– Benjamin Franklin

 

It’s obvious that Mr. Franklin didn’t have to deal with bad data, bad code, or even the occasional hiccup. In the real world, there is “trouble” and we need to not only anticipate that trouble, but also worry about what may never happen. Simply “keeping in the sunlight” won’t maintain data or application state integrity. In the real world we need transactions!

Since .NET 2.0, we’ve had the privilege of using System.Transactions.TransactionScope to manage our transactions with very few headaches. One of the headaches that almost everyone experiences is MSDTC. One of the oldest and most elusive topics on the web. There are tons of blog and forum posts directing our fellow developers to check their firewall settings for every MSDTC problem. The latest MSDTC hiccup I have seen comes in the beautifully packaged error message:

The flowed transaction could not be unmarshaled. The following exception occurred: Communication with the underlying transaction manager has failed.

The what could not be what? You can read some MSDN documentation on the topic which will probably cause you more pain. If you are seeing this error message, there’s only a few things that may be wrong.

  1. MSDTC Settings
    • Check the MSDTC settings on the machine that is initiating the transaction. If “Allow Outbound” is not checked, then it won’t allow the transaction in progress to be flowed to the next machine in the transaction chain. Check the box and restart MSDTC… it should work.
  2. Un-Trusted Domains
    • I have seen this error when you are trying to flow transactions between machines that are in un-trusted domains. Machines in different domains that do not trust each other block the antiquated, yet necessary, WINS resolution between the two machines. MSDTC relies on WINS resolution. I have fixed this problem before by adding host file entries on both machines pointing to the other machine. I can’t guarantee that this will work in all cases. Both of those machines are no longer under my control.
  3. Imaged Servers
    • The most recent, and most blogged about problem is surprisingly caused by two machines created from the same image. Cloning or imaging servers is quite common. Building a server from scratch is not a fun activity, so we build one, create an image, and put that image on every server we want to build after that. Once again, MSDTC is standing in our way because of the way it detects the sending and receiving application’s unique identifier. Each machine has a GUID in the registry that identifies it uniquely as a participant in an MSDTC transaction. Imaged machines have the same GUID. I’ll talk about the detection and resolution of this for the remainder of this post.

Running DtcPing.exe between the two machines will actually tell you that the machines are using the same GUID. Output window text from DtcPing shown below.

DTCping log file: C:DTC PingTHRESHER4160.log
Firewall Port Settings:
Port:5150-5250
RPC server is ready
Please Start Partner DTCping before pinging
WARNING:the CID values for both test machines are the same
Please send following LOG to Microsoft for analysis:
Partner LOG: SCORPION6128.log
My LOG: THRESHER4160.log

Tucked away in the last step of a Microsoft Knowledge Base article titled “How to troubleshoot MS DTC firewall issues” is a reference to this problem. Use regedit.exe to look at the registry on both machines. Locate the HKEY_CLASSES_ROOTCID key in the registry.

Find your MSDTC CID in the registry

Find the CID key that has a description value of “MSDTC”. If they are the same, the transaction cannot flow.

WARNING: Back up your registry before making any changes!

Solution 1 – Replace the offending CID keys/values on one of the machines: In this case, you will need to find all keys/values with GUID 28b81f1c-2afb-4ee2-ad85-5bc62dad1647 in your registry and replace it with a new GUID (using GuidGen). There is likely to be 3 places this GUID appears. It is also important to note that the offending GUID appears in the DtcPing log file generated during the ping test.

Solution 2 – Use msdtc command line tool to re-install MSDTC: The commands are simply:

msdtc -uninstall
msdtc -install

After making the registry changes or running the msdtc command line tool, you must restart your server for the changes to take effect.

Oct 302008
 

Don’t be so quick to blame the service or MSDTC when you see the error “Communication with the underlying transaction manager has failed.”

Symptom:

An error message that reads something like:

System.Transactions.TransactionManagerCommunicationException: Communication with the underlying transaction manager has failed. —> System.Runtime.InteropServices.COMException (0x80004005): Error HRESULT E_FAIL has been returned from a call to a COM component.

Solutions:

 

“Check your firewall settings” is what you will find in almost all forum posts and on MSDN. You need port 135 open bi-directionally for RPC’s end point mapper (EPM). You also need ports 1024-5000 open bi-directionally if you have not specified your own port settings for RPC in the registry. If you have your own ports specified in the registry, then those need to be open bi-directionally.

 

WHAT ?!? It may also be your code causing the issue. If you are using TransactionScope, you have to be mindful of every method called within the using braces. Looking at the code below, you will see two service calls and a seemingly innocuous ShouldContinue() method checking to see if the second operation should be called.

using (TransactionScope scope = new TransactionScope())

using (MyServiceClient proxy = new MyServiceClient())

{

       proxy.DoOperationOne(someID);

      

       if (ShouldContinue()) // uh, oh! What if this has an ADO.NET connection that is opened and closed inside it?

       {

               proxy.DoOperationTwo(someOtherID);

       }

}

If ShouldContinue() opens and closes an SqlConnection, the TransactionScope object has no means by which to commit or rollback this part of the transaction. This will cause the error “Communication with the underlying transaction manager has failed.”

 

1. If you do not need to results of DoOperationOne() to feed ShouldContinue(), then do that logic before the TransactionScope using block.

2. If you do need the result of DoOperationOne() to feed ShouldContinue(), then you can wrap the internals of ShouldContinue() with a TransactionScope using block specifying TransactionScopeOption.Suppress. This will not add the resource access contained within the block to the ambient transaction.

3. Use an intelligent data access library like Enterprise Library that manages your connections for you. It won’t close the connection if enlisted in a transaction.

 

Look at your code before you involve your network dudes. This is more common when integrating legacy code with new service calls.