Connecting to NAV Web Services from Silverlight 3

Please read this post to get a brief explanation of the scenario I will implement in Silverlight. Yes, yes – I know it isn’t a fancy graphical whatever as Silverlight should be, but to be honest – I would rather do something crappy on purpose than trying to do something fancy and everybody would find it crappy anyway:-)

Getting started with Silverlight – is your friend. Go to the web site and click this button:


Or click the image above directly.

Within a few seconds you will find yourself installing all the free tools you need to start developing Silverlight applications.

On the getstarted web site you will also find videos and walkthroughs on how to develop in Silverlight.

Silverlight is .net and c# so really guys… – how hard can it be?

That was what I thought!

So I just downloaded the Silverlight development platform and started coding and as soon as I tried to connect to NAV Web Services I ran into the showstopper:


Meaning that for a Silverlight application to be able to communicate with NAV Web Services – it needs to be deployed in the same location as NAV Web Services – http://localhost:7047 – that doesn’t really sound like a good idea.

On MSDN i found this article explaining about this in detail:

Silverlight needs permission by the Web Services host to access the Web Service – it kind of seems like overkill due to the fact that our web services are authenticated with Windows Authentication but I guess there are other services where this makes sense.

To make a long story short – if connecting to http://localhost:7047/DynamicsNAV/WS/SystemService – then Silverlight will first try to download http://localhost:7047/clientaccesspolicy.xml and check whether this is OK, but as you can imagine – NAV doesn’t do that:-(


So if NAV doesn’t support that – how do we get around this obstacle? (of course you know that there is a way – else you wouldn’t be reading this and I wouldn’t be writing it)

The trick is just to create a small windows service that does nothing but host this file. We are lucky that the endpoint of NAV Web Services is http://localhost:7047/DynamicsNAV – and everything underneath that – so I should be able to create a WCF Service hosting just the xml file on http://localhost:7047

NAV Policy Server

I have created a small project called the NAV Policy Server. It is a Windows Service, hosting a WCF Service that will service a “allow all” version of clientaccesspolicy.xml, making Silverlight 3 able to connect to NAV Web Services.

You can read here about how to create a Windows Service (including how to create Setup functionality in the Service). The main program of the Windows Service is here:

using System;
using System.ComponentModel;
using System.ServiceProcess;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Xml;
using System.Reflection;
using System.IO;

namespace NAVPolicyServer
    public partial class NAVPolicyService : ServiceBase
        ServiceHost host;

        public NAVPolicyService()

            string WebServicePort = "7047";
            bool WebServiceSSLEnabled = false;

            // Read configuration file
            XmlDocument doc = new XmlDocument();
            doc.Load(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase), "CustomSettings.config"));
            XmlNode webServicePortNode = doc.SelectSingleNode("/appSettings/add[@key=’WebServicePort’]");
            WebServicePort = webServicePortNode.Attributes["value"].Value;
            XmlNode webServiceSSLEnabledNode = doc.SelectSingleNode("/appSettings/add[@key=’WebServiceSSLEnabled’]");
            WebServiceSSLEnabled = webServiceSSLEnabledNode.Attributes["value"].Value.Equals("true", StringComparison.InvariantCultureIgnoreCase);

            // Base listening address
            string BaseURL = (WebServiceSSLEnabled ? Uri.UriSchemeHttps : Uri.UriSchemeHttp) + Uri.SchemeDelimiter + System.Environment.MachineName + ":" + WebServicePort;

            // Initialize host
   = new ServiceHost(new PolicyRetriever(), new Uri(BaseURL));
  , new WebHttpBinding(false ? WebHttpSecurityMode.Transport : WebHttpSecurityMode.None), "").Behaviors.Add(new WebHttpBehavior());

        protected override void OnStart(string[] args)
            if (host.State != CommunicationState.Opened && host.State != CommunicationState.Opening)

        protected override void OnStop()
            if (host.State != CommunicationState.Closed && host.State != CommunicationState.Closing)

As you can see, the Service needs to be installed in the Service Tier directory of the Web Service listener you want to enable for Silverlight as it reads the CustomSettings.config file to find the port number and whether or not it uses SSL.

After this it creates a ServiceHost bases on the PolicyRetriever class with a WebHttpBinding endpoint at the base URL, here http://machine:7047. In the endpoint you specify the interface (IPolicyRetriever) this endpoint services and this interface is implemented by the PolicyRetriever class.

The actual code is something I found on Carlos’ blog –

The IPolicyRetriever interface is the contract and it looks like:

public interface IPolicyRetriever
    [OperationContract, WebGet(UriTemplate = "/clientaccesspolicy.xml")]
    Stream GetSilverlightPolicy();
    [OperationContract, WebGet(UriTemplate = "/crossdomain.xml")]
    Stream GetFlashPolicy();

As you can see we host two files – clientaccesspolicy.xml for Silverlight and crossdomain.xml for flash.

The PolicyRetriever class (the Service) itself is implemented as a singleton and looks like:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class PolicyRetriever : IPolicyRetriever
    public PolicyRetriever()

    /// <summary>
    /// Create a UTF-8 encoded Stream based on a string
    /// </summary>
    /// <param name="result"></param>
    /// <returns></returns>
    private Stream StringToStream(string result)
        WebOperationContext.Current.OutgoingResponse.ContentType = "application/xml";
        return new MemoryStream(Encoding.UTF8.GetBytes(result));

    /// <summary>
    /// Fetch policy file for Silverlight access
    /// </summary>
    /// <returns>Silverlight policy access xml</returns>
    public Stream GetSilverlightPolicy()
        string result = @"<?xml version=""1.0"" encoding=""utf-8""?>
            <allow-from http-request-headers=""*"">
                <domain uri=""*""/>
                <resource path=""/"" include-subpaths=""true""/>
        return StringToStream(result);

    /// <summary>
    /// Fetch policy file for Flash access
    /// </summary>
    /// <returns>Flash policy access xml</returns>
    public Stream GetFlashPolicy()
        string result = @"<?xml version=""1.0""?>
<!DOCTYPE cross-domain-policy SYSTEM """">
    <allow-access-from domain=""*"" />
        return StringToStream(result);

The way you make a WCF service a singleton is by specifying an instance of the class to the ServiceHost and set InstanceContextMode to single in the ServiceBehavior Attribute.

That is actually all it takes, installing and starting this service will overcome the connection issue.

The NAVPolicyServer solution can be downloaded here and the compiled .msi (installable) can be downloaded here.

Now… – Connecting to NAV Web Services from Silverlight

Having overcome the connection issue – it is really just to write our Silverlight application.

Create a Silverlight application, insert a StackPanel and a ListBox named output in the .xaml file, add service references and write code.

You will quickly notice, that there is nothing called Add Web Reference – only Add Service Reference – and when you have done do, you will notice that all the functions that you normally invoke are missing…

This is because Silverlight only supports Asynchronous Service access – so much for just creating my standard flow of my app.

Another thing that has changed significantly is what you need to do in order to make a Service Reference work. If you look at my earlier posts with C# and Service References, you can see that I need to setup the binding manually and add endpoints etc. Even if I wanted to do it in a config file (like here), you needed to make a lot of changes to the config file (adding behaviors etc.)

In Silverlight you just add the Service Reference and start partying like:

SystemService_PortClient systemService = new SystemService_PortClient();

works right away, no changes needed – THAT’s nice. In my sample I do however build the URL up dynamically, meaning that my construction of the systemService looks like:

SystemService_PortClient systemService = new SystemService_PortClient("SystemService_Port", new EndpointAddress(baseURL + "SystemService"));

Which basically just tells it to read the configuration section and overwrite the endpoint address – still pretty simple.


Whenever you call CompaniesAsync – it returns immediately and after a while the event connected to CompaniesCompleted is triggered. The way I like to do this is to do a inline delegate as an event trigger and just specify my code right there.

My scenario should first list the companies, calculate a customer page URL, read customer 10000 and then read customers with location code BLUE or RED in GB.

public partial class MainPage : UserControl
    private string baseURL = "
    private string customerPageURL;

    public MainPage()

        SystemService_PortClient systemService = new SystemService_PortClient("SystemService_Port", new EndpointAddress(baseURL + "SystemService"));
        systemService.CompaniesCompleted += delegate(object sender, CompaniesCompletedEventArgs e)
            for (int i = 0; i < e.Result.Length; i++)
            string cur = e.Result[0];

            this.customerPageURL = baseURL + Uri.EscapeDataString(cur) + "/Page/Customer";
            display(" ");
            display("URL of Customer Page:");


    void display(string s)


As you can see, I do not call the FindCustomer10000 before I am done with step 1.

I could have inserted that call after the call to CompaniesAsync – but then the customerPageURL variable would not be initialized when starting to connect to the customer page.

FindCustomer10000 looks like:

private void FindCustomer10000()
    Customer_PortClient readCustomerService = new Customer_PortClient("Customer_Port", new EndpointAddress(customerPageURL));
    readCustomerService.ReadCompleted += delegate(object sender, ReadCompletedEventArgs e)
        display(" ");
        display("Name of Customer 10000: " + e.Result.Name);


Again – when we have data and we are done – call FindCustomers, which looks like:

private void FindCustomers()
    Customer_PortClient readMultipleCustomerService = new Customer_PortClient("Customer_Port", new EndpointAddress(customerPageURL));
    readMultipleCustomerService.ReadMultipleCompleted += delegate(object sender, ReadMultipleCompletedEventArgs e)
        display(" ");
        display("Customers in GB served by RED or BLUE warehouse:");
        foreach (Customer customer in e.Result)

        display(" ");
        display("THE END");

    Customer_Filter filter1 = new Customer_Filter();
    filter1.Field = Customer_Fields.Country_Region_Code;
    filter1.Criteria = "GB";
    Customer_Filter filter2 = new Customer_Filter();
    filter2.Field = Customer_Fields.Location_Code;
    filter2.Criteria = "RED|BLUE";
    Customer_Filter[] filters = new Customer_Filter[] { filter1, filter2 };
    readMultipleCustomerService.ReadMultipleAsync(filters, null, 0);

If you try to move the call to FindCustomers up after the call to FindCustomer10000 then you will see that it isn’t always determined which of the two methods complete first, meaning that the order of things in the listbox will be “random”.

As you can see, the NAVPolicyServer is really the thing that makes this easy and possible – I will send a mail to my colleague who is the Program Manager for Web Services and ask him to include a way of serving policies from NAV automatically – until then, you will need the policy server (which is free and available right here).

Running the Silverlight application will perform the following output:


BTW – the Silverlight application can be downloaded here.

Hopefully this can be used to create some cool visual Silverlight applications:-)

Good luck

Freddy Kristiansen
PM Architect
Microsoft Dynamics NAV

Comments (10)

  1. brucemcmillan says:

    Hi Freddy.

    Have you tried using WCF services from windows mobile 7 (SDK )

    I am getting a communication type error as per the silver light scenario.

    However if i use a WPF / WCF application i do not get the errors.

    Looks like the communication on mobile 7 is silver light based too ?


  2. brucemcmillan says:

    Hi Freddy,

    BTW did you use the visual web developer tool or VS 2010 for the project as the zip file when unzipped does not seem to like to be opened using vs 2008 or visaul web dev 2008, but will work when loaded into expression  ?

    Rgdsblend 3


  3. Zoltero says:

    Hi, Freddy,

    Have you tried to connect Nav from Silverlight 4?

  4. Taddeo says:

    Anyone had any luck in calling it from Windows Phone 7???? Freddy Any help please??? 🙁 🙁

  5. Teresa says:

    I have a working version with MVVM Light which will work both for Windows Phone 7 and Silverlight 4/ Blend 4.  I will try to get a blog post up about it soon but in the mean time if you want to send Taddeo my way, I can help.  I can be reached via twitter @t_burger and we can go from there.

    Thank you very much for this post.  It was extremely helpful in getting all of this working!!

  6. Chris Wilson says:


    In you post you mention that you will talk to the web services program manager about developing a way of utilising NAV business web services directly in Silverlight. Now we have NAV 2009 R2 have there been any significant changes that we can use in this instance?

  7. Hi.

    (Sorry if this is a double posting)

    I currently building a program where I try to use MVVM and Silverlight 4, and here I struck a problem I hope you already know the solution for. When Navision returns an error (ex. "The maximum length..") to the WCF-generated client in my Silverlight project, I get a "the remote server returned an error notfound" exception. I see in the log captured with Fiddler that the correct error is returned, but the WCF-client raises the exception before I can catch it. Does anybody know how to get around this problem?

  8. Phil says:

    To get the REAL nav exception, in you startup routine add this

    'Make WCF send the real Error message back to us.

    Dim registerResult As Boolean = WebRequest.RegisterPrefix("http://&quot;, WebRequestCreator.ClientHttp)

    sorry its VB but translate it online for C#



  9. Nikolai L'Estrange says:

    FYI – to make the Policy Server work with NAV2013 I changed the following:

    1) now looks for the port at "/appSettings/add[@key='SOAPServicesPort']"  (was "/appSettings/add[@key='WebServicePort']" above)

    2) commented out the lines looking for WebServiceSSLEnabled – that key doesn't exist, but I'm not using it anyway.

    3) changed the setup project TargetPlatform to x64 and the Application Folder Default Location to [ProgramFiles64Folder]Microsoft Dynamics NAV70Service. If you have multiple instances then you need to install it to the Instances[Instance Name] folder

    I hadn't managed to get "Service References" working with NAV2013 yet – all MS examples use "Web Reference" – but this seems to work for Service Reference and Silverlight.

  10. Karl Rhodes says:

    Excellent article and very helpful, but how would I set my credentials?

    I see there is a read only property called ClientCredentials, but I don't see where I can set this?