Configuring Skype for Business delegates using UCMA - delegates

I have been struggling to programatically add a delegate to a user (boss/admin scenario).
After running my test code in the boss sfb client the admin appears as a delegate however, in the admin's sfb client the boss does not appear under the section "people I manage calls for". I verified in the rtc frontend database that the delegation is configured, however the admin subscription record does not list the boss. Below is the code I used to achieve this.
Any ideas why the admin sfb client is not being notified of the new delegation?
Thanks,
Simon
1) add delegate-management
public void SendAddDelegate()
{
string body = string.Format($"<setDelegates xmlns=\"http://schemas.microsoft.com/2007/09/sip/delegate-management\" version=\"1\"><delegate uri=\"sip:admin#example.com\" action=\"add\"/></setDelegates>");
byte[] encBody = Encoding.UTF8.GetBytes(body);
RealTimeAddress rta = new RealTimeAddress("sip:boss#example.com");
System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType("application/msrtc-setdelegate+xml")
endpoint.InnerEndpoint.BeginSendMessage(MessageType.Service, rta, contentType, encBody, SendAddDelegateManagementMessageComplete, null);
}
private void SendAddDelegateManagementMessageComplete(IAsyncResult result)
{
try
{
SipResponseData srd = endpoint.InnerEndpoint.EndSendMessage(result);
logger.Debug($"srd.ResponseCode - {srd.ResponseCode}");
}
catch (Exception exc)
{
logger.Error("Exception SendMessageComplete with message - {0}", exc.Message);
}
}
2) Publish presence
public void PublishRoutingCategory(string delegateUri)
{
//routes not created here for sample brevity
routes.DelegateRingEnabled = true;
routes.Delegates.Add(delegateUri);
routes.SimultaneousRingEnabled = true;
routes.SimultaneousRing.Add(delegateUri);
routes.SkipPrimaryEnabled = true;
routes.ForwardAudioAppInvitesEnabled = true;
try
{
userEndpoint.LocalOwnerPresence.BeginPublishPresence(new PresenceCategory[] { routes }, PublishComplete, null);
}
catch (Exception exc)
{
logger.Error("Unknown error - {0}", exc.Message);
}
}
private void PublishComplete(IAsyncResult result)
{
try
{
endpoint.LocalOwnerPresence.EndPublishPresence(result);
}
catch (Exception exc)
{
logger.Error("Error Publish Complete- {0}", exc.Message);
}
}

Related

Can't see BlueetoothLE devices

I'm working on BluetoothLE, I want to see the devices around me in a list with their names, and I want to see the properties, services and characters of a device, but I can't see these devices even though the bluetooth of my phone and headset is turned on, the list always comes up empty.
Here is my sample code:
private GattCharacteristic gattCharacteristic;
private BluetoothLEDevice bluetoothLeDevice;
public List<DeviceInformation> bluetoothLeDevicesList = new List<DeviceInformation>();
public DeviceInformation selectedBluetoothLeDevice = null;
public bool IsScannerActiwe { get; set; }
public bool ButtonPressed { get; set; }
public bool IsConnected { get; set; }
public static string StopStatus = null;
public BluetoothLEAdvertisementWatcher watcher;
private DeviceWatcher deviceWatcher;
public void StartWatcher()
{
try
{
string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected", "System.Devices.Aep.IsPresent", "System.Devices.Aep.ContainerId", "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.Manufacturer", "System.Devices.Aep.ModelId", "System.Devices.Aep.ProtocolId", "System.Devices.Aep.SignalStrength" };
deviceWatcher =
DeviceInformation.CreateWatcher(
BluetoothLEDevice.GetDeviceSelectorFromPairingState(false),
requestedProperties,
DeviceInformationKind.AssociationEndpoint);
// Register event handlers before starting the watcher.
// Added, Updated and Removed are required to get all nearby devices
deviceWatcher.Added += DeviceWatcher_Added;
deviceWatcher.Updated += DeviceWatcher_Updated;
deviceWatcher.Removed += DeviceWatcher_Removed;
// EnumerationCompleted and Stopped are optional to implement.
deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted;
deviceWatcher.Stopped += DeviceWatcher_Stopped;
// Start the watcher.
deviceWatcher.Start();
}
catch (Exception ex)
{
Console.WriteLine("Exception -> ", ex.Message);
}
}
public List<DeviceInformation> GetBluetoothLEDevicesList()
{
try
{
return bluetoothLeDevicesList;
}
catch (Exception ex)
{
Console.WriteLine("Exception Handled -> GetBluetoothLEDevices: " + ex);
throw ex;
}
}
public List<string> GetBluetoothLEDevices()
{
try
{
return bluetoothLeDevicesList.Select(x => x.Name).ToList();
}
catch (System.Exception ex)
{
Trace.WriteLine("Exception Handled -> GetBluetoothLEDevices: " + ex);
throw ex;
}
}
I started a few new advertisements with my iphone via the nrF Connect application and I can see it on my pc, but I want to put them all in a list and navigate through that list.
This is Test.cs:
class Test
{
static void Main(string[] args)
{
// Since the StartWatcher method is called from within the constructor method,
that method will always run whenever an instance is created.
BLEControllers bLEControllers = new BLEControllers();
var devices = bLEControllers.GetBluetoothLEDevicesList();
foreach (var device in devices)
{
if (device != null)
{
Console.WriteLine(device.Name);
}
Console.WriteLine("empty");
}
//bLEControllers.ConnectDevice(device);
//bLEControllers.ConnectDevice();
Console.Read();
}
}
Whenever I run this code, neither device names nor empty text appears on the console, only the startWatcher function works and ends. Is there any function to list all the devices? And how can I see the supported service and characteristic uuids? is there a way to do this?

Xamarin: multiple request network pop ups in android 10, when try to connect to wifi in IOT module

I am working on an IOT module with wifi connection,I am testing using a samsung with android 10.
The chip is a ESP8266.The Wi-Fi signal, does not have an internet connection.
the project is developed in xamarin.
The problem, is when I try to connect to the device's signal. When I'm making the connection request, multiple pop ups appear in the device, requesting the connection, and it does not wait until it is connected, immediately the device launches the connection requests again and again, finally crash.
when i'm debugging, the NetworkAvailable runs, but even the phone does not finish connecting to the signal, the phone lunch a new request network again, don't wait until you are actually connected, and I don't know why multiple requests are launched.
Here is my code.
public async Task<bool> Connect(string WiFiName, string WifiPassword)
{
bool result = false;
var formattedSsid = $"\"{WiFiName}\"";
var formattedPassword = $"\"{WifiPassword}\"";
try
{
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
var wifiNetworkSpecifier = new WifiNetworkSpecifier.Builder()
.SetSsid(WiFiName)
.SetWpa2Passphrase(WifiPassword)
.Build();
var networkRequest = new NetworkRequest.Builder()
.AddTransportType(TransportType.Wifi) // we want WiFi
.SetNetworkSpecifier(wifiNetworkSpecifier) // we want _our_ network
.Build();
UnregisterNetworkCallback(_networkCallback);
_networkCallback = new NetworkCallback()
{
NetworkAvailable = network =>
{
result = true;
autoResetEvent.Set(); //signal
},
NetworkUnavailable = () =>
{
result = false;
autoResetEvent.Set(); //signal
},
};
connectivityManager.RequestNetwork(networkRequest, _networkCallback);
autoResetEvent.WaitOne();
}
catch (Exception e)
{
Crashes.TrackError(e);
}
finally
{
}
return result;
}
private void UnregisterNetworkCallback(NetworkCallback _networkCallback)
{
if (_networkCallback != null)
{
try
{
_connectivityManager.UnregisterNetworkCallback(_networkCallback);
}
catch (Exception) {
} finally
{
_networkCallback = null;
}
}
}
public class NetworkCallback : ConnectivityManager.NetworkCallback
{
public Action<Network> NetworkAvailable { get; set; }
public Action NetworkUnavailable { get; set; }
public NetworkCallback()
{
}
public override void OnAvailable(Network network)
{
try
{
WiFiAndroid.connectivityManager.BindProcessToNetwork(null);
WiFiAndroid.connectivityManager.BindProcessToNetwork(network);
}
catch (Exception ex)
{
var error = ex;
}
}
public override void OnUnavailable()
{
base.OnUnavailable();
NetworkUnavailable?.Invoke();
}
}
the image, is the request that is throw over and over again.

Can I catch specific exceptions globally in a Razor Page (all handler methods) and include them in ModelState?

I'd like to allow all handler methods in a Razor Page to be wrapped by some sort of logic to handle specific exceptions that are more or less validation exceptions.
I've tried the following, but still get the developer exception page:
public override async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
{
try
{
await next();
}
catch(NotImplementedException ex)
{
_logger.LogWarning(ex, ex.Message);
ModelState.AddModelError(string.Empty, "Oops... this isn't all done yet.");
context.Result = Page();
}
catch (DomainValidationException ex)
{
ModelState.Include(ex.Results);
context.Result = Page();
}
}
The exception does not appear to bubble up from the await next() call and is handled in aspnetcore somehow.
It turns out that the next returns a result that needs to be inspected to get the exception and return the result.
The final implementation looks something like this:
public override async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
{
var result = await next();
if (result.Exception != null)
{
if (result.Exception is NotImplementedException nex)
{
result.ExceptionHandled = true;
_logger.LogWarning(nex, nex.Message);
ModelState.AddModelError(string.Empty, "Oops... this isn't all done yet.");
}
else if (result.Exception is DomainValidationException dex)
{
result.ExceptionHandled = true;
ModelState.Include(dex.Results);
}
if (result.ExceptionHandled)
{
result.Result = Page();
}
}
}

Xamarin(PCL) - Signal R - System.InvalidOperationExceptionConnection started reconnecting before invocation result was received

I am getting System.InvalidOperationExceptionConnection started reconnecting before invocation result was received exception sometimes with Signal R chat, i am using Signal R client in PCL of Xamarin Project
Here is Chat service class-
public class ChatService : IChatService
{
private IHubProxy _hubProxy;
private HubConnection _hubConnection;
private readonly IMobileServiceClient _mobileClient;
private readonly IInsightsService _insightsService;
private readonly IChatMessageRepository _chatRepository;
public ChatService(IMobileServiceClient mobileClient, IInsightsService insightsService, IChatMessageRepository chatRepository)
{
_insightsService = insightsService;
_mobileClient = mobileClient;
_chatRepository = chatRepository;
}
public event EventHandler<ChatMessage> MessageReceived;
public async Task Connect(bool dismissCurrentConnection = false)
{
try
{
if (!CrossConnectivity.Current.IsConnected)
{
return;
}
// Always create a new connection to avoid SignalR close event delays
if (_hubConnection != null)
{
if (!dismissCurrentConnection)
{
return;
}
_hubConnection.StateChanged -= OnConnectionStateChangedHandler;
_hubConnection.Reconnected -= OnReconnectedHandler;
// DON´T call connection.Dispose() or it may block for 20 seconds
_hubConnection = null;
_hubProxy = null;
}
_hubConnection = new HubConnection(Identifiers.Environment.ChatUrl);
// connection.TransportConnectTimeout = TimeSpan.FromSeconds(5);
_hubConnection.TraceWriter = new DebugTextWriter("SignalR");
_hubConnection.TraceLevel = TraceLevels.All;
_hubConnection.StateChanged += OnConnectionStateChangedHandler;
_hubConnection.Reconnected += OnReconnectedHandler;
if (_mobileClient.CurrentUser == null)
throw new Exception("MobileClient.CurrentUser null. You have to login to Azure Mobile Service first.");
_hubConnection.Headers[HttpHeaders.XZumoAuth] = _mobileClient.CurrentUser.MobileServiceAuthenticationToken;
_hubProxy = _hubConnection.CreateHubProxy(Identifiers.ChatHubName);
_hubProxy.On<ChatMessage>("addMessage", message =>
{
MessageReceived?.Invoke(this, message);
});
if (_hubConnection.State == ConnectionState.Disconnected)
{
await _hubConnection.Start();
}
}
catch (Exception ex)
{
_insightsService.ReportException(ex);
}
}
private async void OnConnectionStateChangedHandler(StateChange change)
{
if (_mobileClient?.CurrentUser != null && change.NewState == ConnectionState.Disconnected && CrossConnectivity.Current.IsConnected)
{
// SignalR doesn´t do anything after disconnected state, so we need to manually reconnect
await Connect(true);
}
}
private void OnReconnectedHandler()
{
Debug.WriteLine("[SignalR] SignalR Reconnected to Hub: {0}", Identifiers.ChatHubName);
}
public async Task SendMessage(ChatMessage message)
{
try
{
if (_hubConnection.State == ConnectionState.Disconnected)
{
await Connect(true);
}
await _hubProxy.Invoke("Send", message);
}
catch (Exception ex)
{
try
{
await _chatRepository.InsertAsync(message);
}
catch (Exception ex2)
{
_insightsService.ReportException(ex);
_insightsService.ReportException(ex2);
throw ex;
}
}
}
public async Task JoinChatRoom(string chatRoomId)
{
try
{
if (_hubConnection.State == ConnectionState.Disconnected)
{
await Connect(true);
}
await _hubProxy.Invoke("JoinChatRoom", chatRoomId);
}
catch (Exception ex)
{
_insightsService.ReportException(ex);
}
}
public async Task LeaveChatRoom(string chatRoomId)
{
try
{
if (_hubConnection.State == ConnectionState.Disconnected)
{
await Connect(true);
}
await _hubProxy.Invoke("LeaveChatRoom", chatRoomId);
}
catch (Exception ex)
{
_insightsService.ReportException(ex);
}
}
public void Disconnect()
{
try
{
if (_hubConnection != null && _hubConnection.State != ConnectionState.Disconnected)
_hubConnection.Stop();
}
catch (Exception ex)
{
_insightsService.ReportException(ex);
}
}
}
How can i prevent and catch this exception? this is not always though

Spring Scheduled Task, strange behavior

I have a Scheduled task which runs every 800 seconds from a server towards its clients to see if they are online. If they are not, it will send me an email, and will send an email when they are back online.
So, this is the scheduled task
#Scheduled(fixedDelay = 800000)
public void pingAllClients() {
logger.debug("Schedule pingClients");
List<Client> clients = clientService.findAllClients();
Iterator<Client> it = clients.iterator();
while (it.hasNext()) {
Client client = it.next();
String ip = client.getCurrentIp();
int idClient = client.getIdClient();
boolean isOnline = client.isOnline();
try {
boolean reachable = reachClient.isReachable(ip);
if (reachable) {
if (!isOnline) {
logger.debug("Client " + idClient + " back online");
client.setOnline(true);
clientService.updateClient(client);
smtp.sendEmail(serverName, ip, true);
}
} else {
logger.debug("Client " + idClient + " not available");
if (isOnline) {
client.setOnline(false);
clientService.updateClient(client);
smtp.sendEmail(serverName, ip, false);
}
}
} catch (Exception e) {
logger.error("Errore", e);
}
}
}
}
reachClient.isReachable(ip) is this method:
public boolean isReachable(String ip){
Socket socket = new Socket();
try {
socket.connect(new InetSocketAddress(ip, 22), 50*1000);
return true;
} catch (IOException e) {
return false;
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
So, it should be: every 800 seconds i loop my clients, see if the are reachable or not, and if they change status, i will receive an email. In the email i print the date/time of the request.
It always happens that i get an email from an offline client and soon after (2-10 seconds) an email it is back online, as, for the same client, i'm getting 2 emails in a single iteration, how is it possibile? Each client should be reachable or not for every loop, not both...
The last 2 emails I got are (6 seconds delay)
Client 192.168.42.13 is offline - Date: 11-12-2016 17:14:30
Client 192.168.42.13 back online - Date: 11-12-2016 17:14:36

Resources