Setting Custom AIF Headers When Using WCF

I do a fair bit of work integrating Microsoft Dynamics AX with other
enterprise applications for my clients. Most of this work has been done
using the AX BizTalk adapter to communicate with the
AIF.
Recently I have been experimenting with using the
WCF services
generated by the AIF instead of the BizTalk adapter to communicate with
Dynamics AX 2009. AX uses the “Default Endpoint” as the destination
endpoint and the local endpoint of the user calling the service for
processing WCF requests. I wanted to be able to specify which endpoints
my requests were using in order to take advantage of the security and
processing features in the AIF. Unfortunately, the MSDN
documentation
for AIF does not contain any information on how to do
this with WCF. I managed to find a Channel 9 video that had a code
example that showed how to use SOAP headers to set these values. Since I
am not getting any younger, I am documenting how to set these values
here for future reference.

Note: Using these SOAP headers assumes that the AIF WCF services
have been configured with a binding that supports WS-Addressing. By
default AIF is configured to use the BasicHttpBinding which does not
support WS-Addressing.

Set a custom destination endpoint

Create a new custom header element called “DestinationEndpoint” with the
default AIF namespace and a configured AIF local endpoint name and add
it to the message context.

1
2
3
4
5
6
 
using (new OperationContextScope(client.InnerChannel)
{
OperationContext.Current.OutgoingMessageHeaders.Add(
MessageHeader.CreateHeader("DestinationEndpoint", "http://schemas.microsoft.com/dynamics/2008/01/services", “CEU”));
}

Set a custom source endpoint and user

Create a new address endpoint and use it to populate the
OperationContext.Current.OutgoingMessageHeaders.From property. The user
needs be in the form of Domain\Username.

1
2
3
4
5
6
7
8
var addressHeader = AddressHeader.CreateAddressHeader("SourceEndpointUser", http://schemas.microsoft.com/dynamics/2008/01/services", @”DOMAIN\user”);
var addressBuilder = new EndpointAddressBuilder(new EndpointAddress(new Uri("urn:" + endpointName), addressHeader));
var endpointAddress = addressBuilder.ToEndpointAddress();

using (new OperationContextScope(client.InnerChannel)
{
OperationContext.Current.OutgoingMessageHeaders.From = endpointAddress;
}

Set a custom message ID value

Create a new GUID and use it to populate the value of the
OperationContext.Current.OutgoingMessageHeaders.MessageId property.

1
2
3
4
using (new OperationContextScope(client.InnerChannel)
{
OperationContext.Current.OutgoingMessageHeaders.MessageId = new UniqueId(new System.Guid.NewGuid());
}