Consume NAV Webservices using C#

Leave a comment

February 26, 2020 by Moiz Ahmed

Realized that quite a lot of NAV Developers aren’t very good at C# programming so when it comes to consuming a NAV web services quite a lot of them don’t have a clear idea. Microsoft has given an example using the OAuth, which I would prefer over Basic authentication.

https://docs.microsoft.com/en-us/dynamics365/business-central/dev-itpro/webservices/authenticate-web-services-using-oauth

I’ve provided the other method just in case if people may be wondering what is the Service Authentication Key for and how to use it.

The method is using Connected Service. Follow the link below to generate the objects.

https://medium.com/@unchase/how-to-generate-c-or-visual-basic-client-code-for-odata-protocol-versions-1-0-4-0-a3a4f9402ea1

I’ve called the Service as NAV for this example.

 

static void Main(string[] args)
{
String username = “ABCD”; //Case sensitive
String password = “xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx” // Service Authentication Key;

AuthenticationHeaderValue a = new AuthenticationHeaderValue(“Authorization”, Convert.ToBase64String(Encoding.Default.GetBytes(username + “:” + password)));
var nav = new NAV.NAV(new Uri(“https://api.businesscentral.dynamics.com/v2.0/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/Sandbox/ODataV4/Company(‘CompanyName’)”));
nav.BuildingRequest += (sender, eventArgs) => eventArgs.Headers.Add(“Authorization”, “Basic ” + a.Parameter);
var abc = Chart_of_Accounts.CreateChart_of_Accounts(“Test123”);
abc.Name = “testing .net”;
nav.AddToChart_of_Accounts(abc);
nav.SaveChanges();

// Retrieve and return a list of the Chart of accounts
foreach (var comp in nav.Chart_of_Accounts)
{
Console.WriteLine(“Found Job No: {0} : Job Name : {1} ” ,arg0:comp.No, arg1:comp.Name);
}
Console.ReadLine();
}

Leave a comment