How to check connection to Milestone server and auto reconnect if connection is disconnected when using Mobile.SDK.dll

I am using Mobile.SDK.dll to integrate into a WPF app. Currently I’m having trouble knowing how to handle connection loss and automatic reconnection.

Example of a test case I need to handle:

- After logging in, there is a successful connection.

- Then the connection is lost => How do I know if the connection is lost?

- There is a reconnection => How do I know if there is a reconnection, and how to automatically reconnect.

I need to monitor the connection here, so how can I do it?

Best regards,

Khoa

Hi Khoa,

Generally speaking, a connection is killed by the server if it’s not used for more than 30 seconds (value is configurable in server config file).

To prevent timeouts, .NET SDK’s Connection has a property called RunHeartBeat, which can be set to true, to auto-send LiveMessage commands more often, to prevent the connection from being killed by the server during normal operation.

There is no such thing as restoring a previously killed connection.

To achieve something similar, you should have some logic in your client code that checks the state of your current Connection object after a command has failed.

State will be updated when sending a new command (e.g. GetBookmarks or GetActions, or whatever).

Sample code:

ConnectionStates currentState;
Func<Connection> getFreshConnection = () =>
{
    var result = new Connection(ChannelTypes.HTTPSecure, "my.mobile.server", 8082u)
    {
        RunHeartBeat = true,
    };
    result.Connect(null, TimeSpan.FromSeconds(5));
    result.LogIn("user", "pass", ClientTypes.WebClient, TimeSpan.FromSeconds(5), UserType.Basic);
    result.StateChange.OnStateChange += (sender, e) => currentState = ((ConnectionEventArgs)e).State;
    return result;
};
 
var connection = getFreshConnection();
currentState = ConnectionStates.Connected;
 
// suppose your program is freezed at this point, which will cause server-side connection timeout
 
var actions = connection.Actions.GetActions(new OutputsEventsParams { CameraId = Guid.Empty }, TimeSpan.FromSeconds(5)); // calling any command will fire OnStateChange if connection was meanwhile killed
 
// if command has failed, check whether connection is dropped and create a new connection
if(actions.Result != Command.CommandResultTypes.ResultOk)
{
    if(currentState != ConnectionStates.Connected)
    {
        connection = getFreshConnection();
    }
}

Br,

Nikolay