Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Finance | Project Operations, Human Resources, ...
Unanswered

Websocket connection from D365 for integration

(2) ShareShare
ReportReport
Posted on by 30
Hi experts ! 
 
im trying to connect to websocket from D365 , I have tried to connect to it using .NET library and using that DLL into my project but , the websocket close before ReciveAsync() and i don’t get any response , u can’t even find out wats the status , not able to get the response back by x++ , I’m able to get maximum no connection  exceed error at times in response by RecievAsync() but at times WB closes and there’s no response i have been banging my head round this issue for a while buy can’t find a solution , can anyone provide me sample code for doing this in x++ , doing it via .NET is quite complex
 
 
 
 
Hi Martin
I have edited this thread and added my code here and from here on  ill be continuing this thread for futher clarifications 
Adding my C# code as you asked , pls find it also Im not using reflection anymore to load the assemble I have my referenced  the  dll into my project .
 
ASP_NetWBsocket::ConnectAsync(uri , _authToken)  --- calling C# code  from x++
 
 
 
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.WebSockets;
using System.Threading;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using Newtonsoft.Json;
using System.Net.Sockets;
using System.Net.NetworkInformation;

namespace ASP_NetWBsocket
{
    public class Socket
    {
        private static string receivedMessage;
        private static string sharedData = null; // Shared variable to store received data
 
 
        public static async Task ConnectAsync(System.String uri, string _authToken)
        {
            var handler = new HttpClientHandler();
            handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
            {
                return true;
            };
            var httpClient = new HttpClient(handler);
            using (ClientWebSocket webSocket = new ClientWebSocket())
            {
                try
                {
                    // Connect to the WebSocket server
                    Console.WriteLine("Connecting to WebSocket server...");
                    webSocket.Options.SetRequestHeader("Authorization", "Bearer" + _authToken);
                    webSocket.Options.KeepAliveInterval = TimeSpan.FromMinutes(40);
                    await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
                    Console.WriteLine("Connected!");
                    await ReceiveMessagesAsync(webSocket);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error: {ex.Message}");
                }
            }
        }
 
 
 
 
        private static async Task ReceiveMessagesAsync(ClientWebSocket webSocket)
        {
            var message = new StringBuilder();
            byte[] buffer = new byte[4096 * 4];
            while (webSocket.State == WebSocketState.Open)
            {
                WebSocketReceiveResult result;
                do
                {
                    result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);       /*   comments - The process doesnt halt here its                                                                                                                                                                                                                          just that my dubugger comes out and im                                                                                                                                                                                                       not able to see the message is next line wat is the                                                                                                                                                                                                        reason , possibly connections is established or not I                                                                                                                                                                                                      dont know cus i dont wat happened  also the 2 time                                                                                                                                                                                                  when i run the same process result variable populates                                                                                                                                                                                                   and gives me the error for maximum connections and i                                                                                                                                                                                              if i dont abort the process if the message type is text                                                                                                                                                                                                     when  the the code iterates  again through while it                throws exception  " System.Net.WebSockets.WebSocketException (0x83760002): Invalid data format for the specific protocol" */
 

                    var messageChunk = Encoding.UTF8.GetString(buffer, 0, result.Count);
                    message.Append(messageChunk);
                } while (!result.EndOfMessage);
                Console.WriteLine("Received: " + message.ToString());
                if (result.MessageType == WebSocketMessageType.Close)
                {
                    await
                        webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Close response received",
                            CancellationToken.None);
                }

                else if (result.MessageType == WebSocketMessageType.Text && result.Count == 147)
                {
                    webSocket.Abort();
                }
                receivedMessage = message.ToString();
                sharedData = receivedMessage; // Store the received data in the shared variable
            }
        }
        public string GetSharedData()
        {
            return sharedData; // Method to retrieve the shared data
        }

    }
}
  • Martin Dráb Profile Picture
    231,923 Most Valuable Professional on at
    Websocket connection from D365 for integration
    Please show us your C# code. Currenty I have no idea how you're dealing with async, for instance.
     
    You're making a mistake by using reflection to load the assembly and calling the method. You're making everything much more complicated and fragile and you won't be able to deploy your code.
     
    As you already know, X++ allows you to use .NET types (such as WebSocket) in X++, which gives you get compile-type control, IntelliSense and so on. This works with custom classes as well. You just need add a reference from your X++ project to the assembly. You can either refer to the DLL file, or - which is even better - you can put both your X++ project and your C# project to the same solution and add a project reference. Then you can even step from X++ code to C# code in the debugger.
     
    Please change that before anything else; it'll make your code and debugging easier, which is surely what you want.
     
    I think that "the process is stopped" means that you got an unhandled exception. Your next step finding out what exception it was. There is no univeral solution for all types of exceptions.
  • MB-14021109-0 Profile Picture
    30 on at
    Websocket connection from D365 for integration
    Hi Martin ! 
     
    I really appreciate your help following is the code I have implemented in .NET and trying to call it x++ .
    I'm able to connect to WebSocket  , post Connect sync() call the  connection state property is set to Open which signifies HTTP 
    handshake has been completed . Following are my queries
    1)RecieveAsync () the debugger comes out and the process is stopped after following line of code , I can find out if the connection is established and the response from WB Sever as debugger doesnt navigate to next line .
     
     result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
     
     
    2 ) Not able to get the response from .Net and return it in x++ as result Im not able to figure out wats the status .
     
    3) I tried exectuting the same process via post Man.
    * First I generateToken
    *Second I establish connection with WB
    *I do a post request which results in output 200K acknowledged .
    *Response JSON is shown as out on WEBSOCKET 
     
    My only question is where should call the logic for post() after calling the logic for establishing WebSocket Connection? would that be right place to put it? Also I cannot see the output cus unfortunately i havent been able to get the response from .Net into x++.
     
    Have attached code snippets pls let me know wat possibly could I do , have been stuck on this issue for a while and its very bothersome now 



    HI Martin!

    Could you suggest something pls!!!
  • Martin Dráb Profile Picture
    231,923 Most Valuable Professional on at
    Websocket connection from D365 for integration
    This is surely related to your other thread Connecting to a web socket for Integration.
     
    Please show us your current code and give us more information about the problem(s).
     
    One of the bugs in your previous thread was that you weren't waiting for asynchronous operations to complete. Have you already fixed that?
     
    You also fogot to close the connection (ideally by a 'using' block), which is likely the cause of the "maximum no connection exceed error".

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Daivat Vartak – Community Spotlight

We are honored to recognize Daivat Vartak as our March 2025 Community…

Announcing Our 2025 Season 1 Super Users!

A new season of Super Users has arrived, and we are so grateful for the daily…

Kudos to the February Top 10 Community Stars!

Thanks for all your good work in the Community!

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 293,245 Super User 2025 Season 1

#2
Martin Dráb Profile Picture

Martin Dráb 231,923 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156 Moderator

Leaderboard

Product updates

Dynamics 365 release plans