How to initiate a Video call using lync sdk? - visual-studio

My Aim: I want to initiate a video call from the start.
My Problem: It is getting initiated into audio call and then it's turning into video after end user answers the call.
void ConversationManager_ConversationAdded_Video(object sender, ConversationManagerEventArgs e)
{
Console.WriteLine("Inside conversation added for Video");
if (e.Conversation.Modalities[ModalityTypes.AudioVideo].State != ModalityState.Notified)
{
if (e.Conversation.CanInvoke(ConversationAction.AddParticipant))
{
try
{
e.Conversation.ParticipantAdded += Conversation_ParticipantAdded_Video;
e.Conversation.AddParticipant(client.ContactManager.GetContactByUri(receipient));
}
catch (ItemAlreadyExistException ex)
{
}
}
}
}
void Conversation_ParticipantAdded_Video(object source, ParticipantCollectionChangedEventArgs data)
{
if (data.Participant.IsSelf != true)
{
if (((Conversation)source).Modalities[ModalityTypes.AudioVideo].CanInvoke(ModalityAction.Connect))
{
object[] asyncState = { ((Conversation)source).Modalities[ModalityTypes.AudioVideo], "CONNECT" };
try
{
((Conversation)source).Modalities[ModalityTypes.AudioVideo].ModalityStateChanged += _AVModality_ModalityStateChanged_Video;
Console.WriteLine("entered video Satheesh participant added");
// ((Conversation)source).Modalities[ModalityTypes.AudioVideo].BeginConnect(ModalityCallback, asyncState);
((Conversation)source).Modalities[ModalityTypes.AudioVideo].BeginConnect(ModalityCallback, asyncState);
//((Conversation)source).Modalities[ModalityTypes.AudioVideo].EndConnect(ModalityCallback, asyncState);
Thread.Sleep(6000);
Console.WriteLine(source);
Console.WriteLine("entered video participant added");
}
catch (LyncClientException lce)
{
throw new Exception("Lync Platform Exception on BeginConnect: " + lce.Message);
}
}
}
}
public void ModalityCallback(IAsyncResult ar)
{
Object[] asyncState = (Object[])ar.AsyncState;
try
{
if (ar.IsCompleted == true)
{
if (asyncState[1].ToString() == "RETRIEVE")
{
((AVModality)asyncState[0]).EndRetrieve(ar);
}
if (asyncState[1].ToString() == "HOLD")
{
((AVModality)asyncState[0]).EndHold(ar);
}
if (asyncState[1].ToString() == "CONNECT")
{
Console.WriteLine("inside connect method CONNECT");
((AVModality)asyncState[0]).EndConnect(ar);
}
if (asyncState[1].ToString() == "FORWARD")
{
((AVModality)asyncState[0]).EndForward(ar);
}
if (asyncState[1].ToString() == "ACCEPT")
{
((AVModality)asyncState[0]).Accept();
}
}
}
catch (LyncClientException)
{ }
}
public void _AVModality_ModalityStateChanged_Video(object sender, ModalityStateChangedEventArgs e)
{
Console.WriteLine(sender);
Console.WriteLine("entered video modality changed");
switch (e.NewState)
{
case ModalityState.Connected:
if (_VideoChannel == null)
{
_VideoChannel = ((AVModality)sender).VideoChannel;
_VideoChannel.StateChanged += new EventHandler<ChannelStateChangedEventArgs>(_VideoChannel_StateChanged);
}
if (_VideoChannel.CanInvoke(ChannelAction.Start))
{
Console.WriteLine("entered video modality changed123");
_VideoChannel.BeginStart(MediaChannelCallback, _VideoChannel);
}
break;
case ModalityState.OnHold:
break;
case ModalityState.Connecting:
case ModalityState.Forwarding:
break;
case ModalityState.Transferring:
break;
}
}
private void MediaChannelCallback(IAsyncResult ar)
{
((VideoChannel)ar.AsyncState).EndStart(ar);
}

I Think it is because you call _AVModality_ModalityStateChanged_Video in ParticipantAdded event.
that means that you start your video when the person you call (the new participant) joins the conversation. thats why it is getting initiated into audio call and then it's turning into video after end user answers the call.
The solution is to fire a new event : ConversationStateChangedEvent
this is where I did it and works fine :
/// <summary>
/// Handles event raised when New meetNow window change it's state
/// </summary>
private void _NewMeetNowConversation_StateChanged(object sender, ConversationStateChangedEventArgs e)
{
Conversation conference = (Conversation)sender;
switch(e.NewState)
{
case ConversationState.Active:
conference.Modalities[ModalityTypes.AudioVideo].ModalityStateChanged += AVConferenceModalityStateChanged;
conference.ParticipantAdded += ConfParticipantAdded;
break;
case ConversationState.Terminated: //conversation window completely closed
break;
case ConversationState.Inactive:
break;
case ConversationState.Parked:
break;
case ConversationState.Invalid:
break;
}
}

Related

ZKEmkeeper: Events not triggering on Windows Service

I'm stucked for a while trying to use zkemkeeper sdk to use on a Windows Service that uses a InBios(Controller) for fingerprint.
i first connect to the device and then i add the event OnAttTransactionEx, someone can point me what i'm doing wrong.
Here is the code snippet
`
protected override void OnStart(string[] args)
{
Thread TT = new Thread(new ThreadStart(WorkedThread));
TT.IsBackground = true;
TT.SetApartmentState(ApartmentState.STA);
this.isServiceStarted = true;
TT.Start();
}
private void WorkedThread()
{
WriteToFile("Worker Thread Started.");
ZKemClient objZkeeper = new ZKemClient(filepath);
this.isDeviceConnected = objZkeeper.Connect_Net("19x.x.x.24x", 4370);
if (this.isDeviceConnected)
{
WriteToFile("Device connected.");
WriteToFile("While loop execution starting.");
while (true)
{
WriteToFile(filepath, "While loop execution started.");
}
}
else
{
WriteToFile("Failed to connect to Device.");
}
}
// ZMClient class
public bool Connect_Net(string IPAdd, int Port)
{
bool bResult = false;
try
{
// Actual SDK class
CZKEM objCZKEM = new CZKEM();
if (objCZKEM.Connect_Net(IPAdd, Port))
{
if (objCZKEM.RegEvent(1, 32767))
{
// [ Register your events here ]
objCZKEM.OnAttTransactionEx += new _IZKEMEvents_OnAttTransactionExEventHandler(zkemClient_OnAttTransactionEx);
}
bResult = true;
}
}
catch (Exception ex)
{
WriteToFile("Connect_Net() Exception->" + ex.Message);
}
return bResult;
}
`
After playing a lot with threading, found a solution.
For windows service - Add reference to System.Windows.Forms
Thread TT1 = new Thread(() =>
{
this.objCZKEM = new CZKEM();
Application.Run();
});
TT1.IsBackground = true;
TT1.SetApartmentState(ApartmentState.STA);
TT1.Start();
Simply continue with current thread
if (this.objCZKEM.Connect_Net(IP, 4370))
{
this.WriteToFile("ZKEM device connected");
if (this.objCZKEM.RegEvent(1, 32767))
{
this.WriteToFile("ZKEM device events registration started");
// [ Register your events here ]
this.objCZKEM.OnAttTransactionEx += new _IZKEMEvents_OnAttTransactionExEventHandler(zkemClient_OnAttTransactionEx);
this.WriteToFile("Done with ZKEM device events registration.");
}
You should not able to receive finger events from device.

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

MVVMCross ZXing back button

I have got a problem with back button in MVVMCross when using zxing barcode scanner. Unfortunetly, when I press back button, there is an error: Java.Lang.NullPointerException: Attempt to invoke virtual method 'long android.graphics.Paint.getNativeInstance()' on a null object reference
When I comment metohs scan() weverything is ok.
Someone know what's going wrong?
This is my fragment scann view class:
public class ScannView : MvxFragmentActivity, IBarcodeFragmentOptions
{
protected ScannViewModel MainViewModel
{
get { return ViewModel as ScannViewModel; }
}
public static ZXingScannerFragment scanFragment;
protected override void OnResume()
{
base.OnResume();
try
{
if (scanFragment == null)
{
scanFragment = new ZXingScannerFragment();
SupportFragmentManager.BeginTransaction()
.Replace(Resource.Id.frameScanner, scanFragment)
.Commit();
}
scan();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
protected override void OnPause()
{
try
{
scanFragment?.StopScanning();
base.OnPause();
}catch(Exception ex)
{
Console.WriteLine(ex);
}
}
protected override void OnRestart()
{
base.OnRestart();
}
public void ToogleFlashLight(bool on)
{
if (scanFragment != null)
scanFragment.SetTorch(on);
}
public void scan()
{
try
{
// var results = await CrossPermissions.Current.RequestPermissionsAsync(Plugin.Permissions.Abstractions.Permission.Camera);
// var status = results[Plugin.Permissions.Abstractions.Permission.Camera];
// if (status == Plugin.Permissions.Abstractions.PermissionStatus.Granted)
// {
var opts = new MobileBarcodeScanningOptions
{
PossibleFormats = new List<ZXing.BarcodeFormat> {
ZXing.BarcodeFormat.QR_CODE
},
CameraResolutionSelector = availableResolutions => {
foreach (var ar in availableResolutions)
{
Console.WriteLine("Resolution: " + ar.Width + "x" + ar.Height);
}
return null;
}
};
scanFragment?.StartScanning(opts,result =>
{
if (result == null || string.IsNullOrEmpty(result.Text))
{
RunOnUiThread(() => Toast.MakeText(this, "Anulowanie skanowanie", ToastLength.Long).Show());
return;
}
MainViewModel.ScannedCode = result.Text; //ChangePropertyToEmpty();
RunOnUiThread(() => Toast.MakeText(this, "Zeskanowano: " + result.Text, ToastLength.Short).Show());
});
// }
}catch(Exception ex)
{
Debug.WriteLine(ex);
}
}
protected override void OnViewModelSet()
{
MobileBarcodeScanner.Initialize(Application);
base.OnViewModelSet();
SetContentView(Resource.Layout.layout_scann);
}
}
And here in my viewmdoel I have simple method to close current viewmodel:
public void ButtonBackClick()
{
Close(this);
}

How to persist IsolatedStorageSettings after terminate the application

How to retain the saved isolatedstoragesettings while at application launch
I used exception for termination on backevents :
protected void _BackKeyPress(object sender, CancelEventArgs e)
{
if (MessageBox.Show("Do you want to close the application?", "Q", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
{
e.Cancel = true;
System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Add("key2", "33r4 ");
}
else
{
if (IsolatedStorageSettings.ApplicationSettings.Contains("Key"))
{
IsolatedStorageSettings.ApplicationSettings["Key"] = App.Current.ViewModel;
}
else
{
IsolatedStorageSettings.ApplicationSettings.Add("Key", App.Current.ViewModel);
}
throw new Exception("ExitApplication");
}
}
I try to save the viewmodel which declares in app.xaml.cs, but cant able to get the isolatedstorage settings value in it, at launch. But It compiles and run successfully.
You need to call the IsolatedStorageSettings.Save method:
protected void _BackKeyPress(object sender, CancelEventArgs e)
{
if (MessageBox.Show("Do you want to close the application?", "Q", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
{
e.Cancel = true;
System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Add("key2", "33r4 ");
IsolatedStorageSettings.Save();
}
else
{
if (IsolatedStorageSettings.ApplicationSettings.Contains("Key"))
{
IsolatedStorageSettings.ApplicationSettings["Key"] = App.Current.ViewModel;
}
else
{
IsolatedStorageSettings.ApplicationSettings.Add("Key", App.Current.ViewModel);
}
IsolatedStorageSettings.Save();
throw new Exception("ExitApplication");
}
}

Code to execute if a navigation fails

Hello I have no idea where I should start looking. I add few prop (before that my code run fine), then I get
System.Diagnostics.Debugger.Break();
so then I comment that changes, but that didn't help.
Could you suggest me where I should start looking for solution?
MyCode:
namespace SkydriveContent
{
public partial class MainPage : PhoneApplicationPage
{
private LiveConnectClient client;
FilesManager fileManager = new FilesManager();
// Constructor
public MainPage()
{
InitializeComponent();
}
private void signInButton1_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
client = new LiveConnectClient(e.Session);
infoTextBlock.Text = "Signed in.";
client.GetCompleted +=
new EventHandler<LiveOperationCompletedEventArgs>(OnGetCompleted);
client.GetAsync("/me/skydrive/files/");
fileManager.CurrentFolderId = "/me/skydrive/files/";
}
else
{
infoTextBlock.Text = "Not signed in.";
client = null;
}
}
void OnGetCompleted(object sender, LiveOperationCompletedEventArgs e)
{
//Gdy uda nam się podłaczyc do konta skydrive
if (e.Error == null)
{
signInButton1.Visibility = System.Windows.Visibility.Collapsed;
infoTextBlock.Text = "Hello, signed-in user!";
List<object> data = (List<object>)e.Result["data"];
fileManager.FilesNames.Clear();
filemanager.filesnames.add("..");
foreach (IDictionary<string,object> item in data)
{
File file = new File();
file.fName = item["name"].ToString();
file.Type = item["type"].ToString();
file.Url = item["link"].ToString();
file.ParentId = item["parent_id"].ToString();
file.Id = item["id"].ToString();
fileManager.Files.Add(file);
fileManager.FilesNames.Add(file.fName);
}
FileList.ItemsSource = fileManager.FilesNames;
}
else
{
infoTextBlock.Text = "Error calling API: " +
e.Error.ToString();
}
}
private void FileList_Tap(object sender, GestureEventArgs e)
{
foreach (File item in fileManager.Files)
{
if (item.fName == FileList.SelectedItem.ToString() )
{
switch (item.Type)
{
case "file":
MessageBox.Show("Still in progress");
break;
case "folder":
fileManager.CurrentFolderId = item.ParentId.ToString();
client.GetAsync(item.Id.ToString() + "/files");
break;
default:
MessageBox.Show("Coś nie działa");
break;
}
}
else if (FileList.SelectedItem.ToString() == "..")
{
client.GetAsync(fileManager.CurrentFolderId + "/files");
}
}
}
}
}
Running stop at that line.
// Code to execute if a navigation fails
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
You should check all of the URLs you have both in the XAML and code. When you get to the NavigationFailed function, it means that the phone tried to navigate to some page that did not existed. We would be able to help more if you could tell what were you doing when the app threw the exception.
System.Diagnostics.Debugger.Break();
usually happens because of an Uncaught Exception.
Either post the code which started giving problems, or the stack trace when you encounter this problem.
No one can tell anything without actually seeing what you are doing.

Resources