private async Task EstablishCollaborationPlatform() { string userAgent = "IFTTT/Email Lync Instant Message Sender"; var platformSettings = new ClientPlatformSettings(userAgent, Microsoft.Rtc.Signaling.SipTransportType.Tls); try { Console.WriteLine("Trying to start collab platform"); _collabPlatform = new CollaborationPlatform(platformSettings); _collabPlatform.ProvisioningFailed += _collabPlatform_ProvisioningFailed; _collabPlatform.AllowedAuthenticationProtocol = Microsoft.Rtc.Signaling.SipAuthenticationProtocols.Ntlm; await _collabPlatform.StartupAsync(); _endpointStarted = true; Console.WriteLine("Collab Platform Started."); } catch (Exception ex) { Console.WriteLine("Error starting collab platform"); Console.WriteLine(ex.ToString()); if (ex.InnerException != null) { Console.WriteLine(ex.InnerException.ToString()); } else { Console.WriteLine("Inner exception is empty"); } } }
public async void TestSetup() { m_loggingContext = new LoggingContext(Guid.NewGuid()); var data = TestHelper.CreateApplicationEndpoint(); m_mockEventChannel = data.EventChannel; m_restfulClient = data.RestfulClient; m_clientPlatformSettings = data.ClientPlatformSettings; m_applicationEndpoint = data.ApplicationEndpoint; await m_applicationEndpoint.InitializeAsync(m_loggingContext).ConfigureAwait(false); await m_applicationEndpoint.InitializeApplicationAsync(m_loggingContext).ConfigureAwait(false); ICommunication communication = m_applicationEndpoint.Application.Communication; m_restfulClient.HandleRequestProcessed += (sender, args) => { TestHelper.RaiseEventsOnHttpRequest(args, DataUrls.MessagingInvitations, HttpMethod.Post, "Event_MessagingInvitationStarted.json", m_mockEventChannel); TestHelper.RaiseEventsOnHttpRequest(args, DataUrls.EstablishMessagingCall, HttpMethod.Post, "Event_MessagingInvitationStarted.json", m_mockEventChannel); }; // Start a messaging invitation m_messagingInvitation = await communication.StartMessagingAsync( "Test subject", new SipUri("sip:[email protected]"), "https://example.com/callback", m_loggingContext).ConfigureAwait(false); }
private async Task EstablishCollaborationPlatform() { string userAgent = "IFTTT/Email Lync Instant Message Sender"; var platformSettings = new ClientPlatformSettings(userAgent, Microsoft.Rtc.Signaling.SipTransportType.Tls); try { Console.WriteLine("Trying to start collab platform"); _collabPlatform = new CollaborationPlatform(platformSettings); _collabPlatform.ProvisioningFailed += _collabPlatform_ProvisioningFailed; _collabPlatform.AllowedAuthenticationProtocol = Microsoft.Rtc.Signaling.SipAuthenticationProtocols.Ntlm; await _collabPlatform.StartupAsync(); _endpointStarted = true; Console.WriteLine("Collab Platform Started."); } catch (Exception ex) { Console.WriteLine("Error starting collab platform"); Console.WriteLine(ex.ToString()); if (ex.InnerException != null) { Console.WriteLine(ex.InnerException.ToString()); } else { Console.WriteLine("Inner exception is empty"); } } }
public static MockApplicationEndpointData CreateApplicationEndpoint() { Logger.RegisterLogger(new ConsoleLogger()); var platformSettings = new ClientPlatformSettings( DiscoverUri, AADClientId, AppTokenCertThumbprint, null, TestHelper.IsInternalApp); var restfulClient = new MockRestfulClient(); var restfulClientFactory = new Mock <IRestfulClientFactory>(); restfulClientFactory .Setup(foo => foo.GetRestfulClient(It.IsAny <OAuthTokenIdentifier>(), It.IsAny <ITokenProvider>())) .Returns(restfulClient); var platform = new ClientPlatform(platformSettings, new ConsoleLogger()); platform.RestfulClientFactory = restfulClientFactory.Object; var endpointSettings = new ApplicationEndpointSettings(ApplicationEndpointUri); var mockEventChannel = new Mock <IEventChannel>(); return(new MockApplicationEndpointData() { EventChannel = mockEventChannel, RestfulClientFactory = restfulClientFactory, RestfulClient = restfulClient, ClientPlatform = platform, ApplicationEndpoint = new ApplicationEndpoint(platform, endpointSettings, mockEventChannel.Object) }); }
public async Task RunAsync() { var skypeId = ConfigurationManager.AppSettings["Trouter_SkypeId"]; var password = ConfigurationManager.AppSettings["Trouter_Password"]; var applicationName = ConfigurationManager.AppSettings["Trouter_ApplicationName"]; var userAgent = ConfigurationManager.AppSettings["Trouter_UserAgent"]; var token = SkypeTokenClient.ConstructSkypeToken( skypeId: skypeId, password: password, useTestEnvironment: false, scope: string.Empty, applicationName: applicationName).Result; m_logger = new ConsoleLogger(); // Uncomment for debugging // m_logger.HttpRequestResponseNeedsToBeLogged = true; EventChannel = new TrouterBasedEventChannel(m_logger, token, userAgent); // Prepare platform var platformSettings = new ClientPlatformSettings(QuickSamplesConfig.AAD_ClientSecret, new Guid(QuickSamplesConfig.AAD_ClientId)); var platform = new ClientPlatform(platformSettings, m_logger); // Prepare endpoint var endpointSettings = new ApplicationEndpointSettings(new SipUri(QuickSamplesConfig.ApplicationEndpointId)); var applicationEndpoint = new ApplicationEndpoint(platform, endpointSettings, EventChannel); var loggingContext = new LoggingContext(Guid.NewGuid()); await applicationEndpoint.InitializeAsync(loggingContext).ConfigureAwait(false); await applicationEndpoint.InitializeApplicationAsync(loggingContext).ConfigureAwait(false); // Meeting configuration var meetingConfiguration = new AdhocMeetingCreationInput(Guid.NewGuid().ToString("N") + " test meeting"); // Schedule meeting var adhocMeeting = await applicationEndpoint.Application.CreateAdhocMeetingAsync(loggingContext, meetingConfiguration).ConfigureAwait(false); WriteToConsoleInColor("ad hoc meeting uri : " + adhocMeeting.OnlineMeetingUri); WriteToConsoleInColor("ad hoc meeting join url : " + adhocMeeting.JoinUrl); // Get all the events related to join meeting through Trouter's uri platformSettings.SetCustomizedCallbackurl(new Uri(EventChannel.CallbackUri)); // Start joining the meeting var invitation = await adhocMeeting.JoinAdhocMeeting(loggingContext, null).ConfigureAwait(false); // Wait for the join to complete await invitation.WaitForInviteCompleteAsync().ConfigureAwait(false); invitation.RelatedConversation.HandleParticipantChange += Conversation_HandleParticipantChange; WriteToConsoleInColor("Showing roaster udpates for 5 minutes for meeting : " + adhocMeeting.JoinUrl); // Wait 5 minutes before exiting. // Since we have registered Conversation_HandleParticipantChange, we will continue to show participant changes in the // meeting for this duration. await Task.Delay(TimeSpan.FromMinutes(5)).ConfigureAwait(false); }
public void Start(List <Uri> chatRoomsToJoin) { Console.WriteLine("正在登陆用户"); Console.ReadKey(); try { chatRooms = chatRoomsToJoin; // Connect to Lync Server ClientPlatformSettings platformSettings = new ClientPlatformSettings("PersistentChat.Test", SipTransportType.Tls); CollaborationPlatform collabPlatform = new CollaborationPlatform(platformSettings); collabPlatform.EndStartup(collabPlatform.BeginStartup(null, null)); UserEndpointSettings userEndpointSettings = new UserEndpointSettings(UserUri.AbsoluteUri, SampleCommon.LyncServer); userEndpointSettings.Credential = new NetworkCredential(UserName, Password); userEndpoint = new UserEndpoint(collabPlatform, userEndpointSettings); Console.WriteLine("正在登陆用户----------->"); // Login to Lync Server currentOperation.Begin("Connect to Lync Server", () => userEndpoint.BeginEstablish(ar => LyncServerBeginEstablishFinished(ar), null)); } catch (Exception e) { Console.WriteLine("正在登陆用户"); } }
/// <summary> /// Sets up the OCS objects using the credentials provided /// </summary> /// <remarks> /// In this sample this is invoked when the user presses the "Apply Server Settings" button /// </remarks> /// <param name="applicationUri">SIP Uri of the OCS account</param> /// <param name="serverName">SIP server URI</param> /// <param name="serverPort">Port (usually 443)</param> /// <param name="credential">Credentials for establishing the user endpoint</param> private void InitializeMCSConnection(string applicationUri, string serverName, int serverPort, NetworkCredential credential) { //Initialize new client platform. //Note that this sample only supports TLS, and additionally that it uses ClientPlatform rather than ServerPlatform. //In a production application, ServerPlatform should be used; ClientPlatform is preferred here to demonstrate the platform without //requiring application provisioning. This is out of the scope of this sample, however. ClientPlatformSettings clientPlatformSettings; clientPlatformSettings = new ClientPlatformSettings("VoiceXMLTestApp", SipTransportType.Tls); collaborationPlatform = new CollaborationPlatform(clientPlatformSettings); collaborationPlatform.EndStartup(collaborationPlatform.BeginStartup(null, null)); //Create a new UserEndpoint based on the information provided through the UI. //As with Server/Client platform above, in production, this should be replaced with provisioned ApplicationEndpoint in most circumstances. UserEndpointSettings endpointSettings; endpointSettings = new UserEndpointSettings(applicationUri, serverName, serverPort); endpoint = new UserEndpoint(collaborationPlatform, endpointSettings); endpoint.Credential = credential; //Bind the event handler to handle incoming calls. Use of the strongly-typed AVCall dictates that calls not matching this type will not be raised. endpoint.RegisterForIncomingCall <AudioVideoCall>(AudioVideoCallReceived); endpoint.EndEstablish(endpoint.BeginEstablish(null, endpoint)); }
public async Task RunAsync(Uri callbackUri) { m_logger = new SampleAppLogger(); // Uncomment for debugging // m_logger.HttpRequestResponseNeedsToBeLogged = true; // Prepare platform var platformSettings = new ClientPlatformSettings(QuickSamplesConfig.AAD_ClientSecret, new Guid(QuickSamplesConfig.AAD_ClientId)); var platform = new ClientPlatform(platformSettings, m_logger); // You can hook up your own implementation of IEventChannel here IEventChannel eventChannel = WebEventChannel.WebEventChannel.Instance; // Prepare endpoint var endpointSettings = new ApplicationEndpointSettings(new SipUri(QuickSamplesConfig.ApplicationEndpointId)); var applicationEndpoint = new ApplicationEndpoint(platform, endpointSettings, eventChannel); var loggingContext = new LoggingContext(Guid.NewGuid()); await applicationEndpoint.InitializeAsync(loggingContext).ConfigureAwait(false); await applicationEndpoint.InitializeApplicationAsync(loggingContext).ConfigureAwait(false); // Meeting configuration var meetingConfiguration = new AdhocMeetingCreationInput(Guid.NewGuid().ToString("N") + " test meeting"); // Schedule meeting var adhocMeeting = await applicationEndpoint.Application.CreateAdhocMeetingAsync(meetingConfiguration, loggingContext).ConfigureAwait(false); WriteToConsoleInColor("ad hoc meeting uri : " + adhocMeeting.OnlineMeetingUri); WriteToConsoleInColor("ad hoc meeting join url : " + adhocMeeting.JoinUrl); // Get all the events related to join meeting through our custom callback uri platformSettings.SetCustomizedCallbackurl(callbackUri); // Start joining the meeting ICommunication communication = applicationEndpoint.Application.Communication; if (!communication.CanJoinAdhocMeeting(adhocMeeting)) { throw new Exception("Cannot join adhoc meeting"); } var invitation = await communication.JoinAdhocMeetingAsync(adhocMeeting, null, loggingContext).ConfigureAwait(false); // Wait for the join to complete await invitation.WaitForInviteCompleteAsync().ConfigureAwait(false); invitation.RelatedConversation.HandleParticipantChange += Conversation_HandleParticipantChange; WriteToConsoleInColor("Showing roaster udpates for 5 minutes for meeting : " + adhocMeeting.JoinUrl); // Wait 5 minutes before exiting. // Since we have registered Conversation_HandleParticipantChange, we will continue to show participant changes in the // meeting for this duration. await Task.Delay(TimeSpan.FromMinutes(5)).ConfigureAwait(false); await WebEventChannel.WebEventChannel.Instance.TryStopAsync().ConfigureAwait(false); }
/// <summary> /// Sets custom callback url where SfB should deliver events related to conversations. /// </summary> /// <param name="This"><see cref="ClientPlatformSettings"/> that needs to be updated</param> /// <param name="callbackUri">Uri to be used for callback</param> /// <remarks> /// Typically, you don't need to set this. It is stored in SfB's application store for your application. /// You should set it only if you want events to be delivered on a uri different than what you specified /// when you registered your application with SfB. This affects events related to a conversation only; /// othere events, which are not part of a conversation, are still delivered to the registered callback url. /// </remarks> public static void SetCustomizedCallbackurl(this ClientPlatformSettings This, Uri callbackUri) { if (!callbackUri.IsAbsoluteUri) { throw new ArgumentException("Absolute uri is needed.", nameof(callbackUri)); } This.CustomizedCallbackUrl = callbackUri.ToString(); }
/// <summary> /// The initialize application endpoint function /// </summary> public async Task InitializeApplicationEndpointAsync( string applicationEndpointUri, string callbackUriFormat, string resourcesUriFormat, string audienceUri, string aadClientId, string aadClientSecret, string appTokenCertThumbprint, string instanceId, bool isSandBoxEnvionment = false, bool logFullHttpRequestResponse = true) { this.InstanceId = instanceId; this.ResourceUriFormat = resourcesUriFormat; this.CallbackUriFormat = callbackUriFormat; var logger = IOCHelper.Resolve <IPlatformServiceLogger>(); logger.HttpRequestResponseNeedsToBeLogged = logFullHttpRequestResponse; ClientPlatformSettings platformSettings = null; if (!string.IsNullOrEmpty(appTokenCertThumbprint)) { platformSettings = new ClientPlatformSettings( Guid.Parse(aadClientId), appTokenCertThumbprint, isSandBoxEnvionment ); } else if (!string.IsNullOrEmpty(aadClientSecret)) { platformSettings = new ClientPlatformSettings( aadClientSecret, Guid.Parse(aadClientId), isSandBoxEnvionment ); } else { throw new InvalidOperationException("Should provide at least one prarameter in aadClientSecret and appTokenCertThumbprint"); } var platform = new ClientPlatform(platformSettings, logger); var endpointSettings = new ApplicationEndpointSettings(new SipUri(applicationEndpointUri)); ApplicationEndpoint = new ApplicationEndpoint(platform, endpointSettings, null); var loggingContext = new LoggingContext(Guid.NewGuid()); await ApplicationEndpoint.InitializeAsync(loggingContext).ConfigureAwait(false); await ApplicationEndpoint.InitializeApplicationAsync(loggingContext).ConfigureAwait(false); }
public async Task RunAsync(Uri callbackUri) { var targetUserId = ConfigurationManager.AppSettings["Skype_TargetUserId"]; m_logger = new SampleAppLogger(); // Uncomment for debugging // m_logger.HttpRequestResponseNeedsToBeLogged = true; // You can hook up your own implementation of IEventChannel here IEventChannel eventChannel = WebEventChannel.WebEventChannel.Instance; // Prepare platform var platformSettings = new ClientPlatformSettings(QuickSamplesConfig.AAD_ClientSecret, new Guid(QuickSamplesConfig.AAD_ClientId)); var platform = new ClientPlatform(platformSettings, m_logger); // Prepare endpoint var endpointSettings = new ApplicationEndpointSettings(new SipUri(QuickSamplesConfig.ApplicationEndpointId)); var applicationEndpoint = new ApplicationEndpoint(platform, endpointSettings, eventChannel); var loggingContext = new LoggingContext(Guid.NewGuid()); await applicationEndpoint.InitializeAsync(loggingContext).ConfigureAwait(false); await applicationEndpoint.InitializeApplicationAsync(loggingContext).ConfigureAwait(false); // Get all the events related to join meeting through our custom callback uri platformSettings.SetCustomizedCallbackurl(callbackUri); WriteToConsoleInColor("Start to send messaging invitation"); var invitation = await applicationEndpoint.Application.Communication.StartMessagingAsync( "Subject", new SipUri(targetUserId), null, loggingContext).ConfigureAwait(false); // Wait for user to accept the invitation var conversation = await invitation.WaitForInviteCompleteAsync().ConfigureAwait(false); conversation.HandleParticipantChange += Conversation_HandleParticipantChange; conversation.MessagingCall.IncomingMessageReceived += Handle_IncomingMessage; // Send the initial message await conversation.MessagingCall.SendMessageAsync("Hello World!", loggingContext).ConfigureAwait(false); WriteToConsoleInColor("Staying in the conversation for 5 minutes"); // Wait 5 minutes before exiting // Since we registered callbacks, we will continue to show message logs await Task.Delay(TimeSpan.FromMinutes(5)).ConfigureAwait(false); await WebEventChannel.WebEventChannel.Instance.TryStopAsync().ConfigureAwait(false); }
public UserEndpoint CreateUserEndpoint(UserEndpointSettings userEndpointSettings) { if (_collabPlatform == null) { // Initalize and startup the platform. ClientPlatformSettings clientPlatformSettings = new ClientPlatformSettings(_applicationName, _transportType); _collabPlatform = new CollaborationPlatform(clientPlatformSettings); } _userEndpoint = new UserEndpoint(_collabPlatform, userEndpointSettings); return(_userEndpoint); }
public async Task Run() { ConsoleLogger logger = new ConsoleLogger(); logger.HttpRequestResponseNeedsToBeLogged = true; //Set to true if you want to log all http request and responses //Prepare platform //For all public developers ClientPlatformSettings platformSettings = new ClientPlatformSettings( QuickSamplesConfig.AAD_ClientSecret, Guid.Parse(QuickSamplesConfig.AAD_ClientId), false ); var platform = new ClientPlatform(platformSettings, logger); //Prepare endpoint var eventChannel = new FakeEventChannel(); var endpointSettings = new ApplicationEndpointSettings(new SipUri(QuickSamplesConfig.ApplicationEndpointId)); ApplicationEndpoint applicationEndpoint = new ApplicationEndpoint(platform, endpointSettings, eventChannel); var loggingContext = new LoggingContext(Guid.NewGuid()); await applicationEndpoint.InitializeAsync(loggingContext).ConfigureAwait(false); await applicationEndpoint.InitializeApplicationAsync(loggingContext).ConfigureAwait(false); //Schedule meeting var adhocMeeting = await applicationEndpoint.Application.GetAdhocMeetingResourceAsync(loggingContext, new AdhocMeetingInput { AccessLevel = AccessLevel.Everyone, Subject = Guid.NewGuid().ToString("N") + "testMeeting" }); logger.Information("ad hoc meeting uri : " + adhocMeeting.OnlineMeetingUri); logger.Information("ad hoc meeting join url : " + adhocMeeting.JoinUrl); //Get anon join token AnonymousApplicationTokenResource anonToken = await applicationEndpoint.Application.GetAnonApplicationTokenAsync(loggingContext, new AnonymousApplicationTokenInput { ApplicationSessionId = Guid.NewGuid().ToString(), //Should be unique everytime AllowedOrigins = "https://contoso.com;https://litware.com;http://www.microsoftstore.com/store/msusa/en_US/home", //Fill your own web site, For allow cross domain using MeetingUrl = adhocMeeting.JoinUrl } ); logger.Information("Get anon token : " + anonToken.AuthToken); logger.Information("Get discover url for web SDK : " + anonToken.AnonymousApplicationsDiscover.Href); }
/// <summary> /// The initialize application endpoint function /// </summary> public async Task InitializeApplicationEndpointAsync( string discoverUri, string applicationEndpointUri, string callbackUriFormat, string resourcesUriFormat, string aadClientId, string aadClientSecret, string aadAuthorityUri, string aadCertThumbprint, string instanceId, bool logFullHttpRequestResponse) { this.InstanceId = instanceId; this.ResourceUriFormat = resourcesUriFormat; this.CallbackUriFormat = callbackUriFormat; var logger = IOCHelper.Resolve <IPlatformServiceLogger>(); logger.HttpRequestResponseNeedsToBeLogged = logFullHttpRequestResponse; ClientPlatformSettings platformSettings; if (aadClientSecret.Length > 0) { // AAD auth to app using client secret platformSettings = new ClientPlatformSettings( new System.Uri(discoverUri), Guid.Parse(aadClientId), null, aadClientSecret ); } else { // AAD auth to app using cert platformSettings = new ClientPlatformSettings( new System.Uri(discoverUri), Guid.Parse(aadClientId), aadCertThumbprint ); } var platform = new ClientPlatform(platformSettings, logger); var endpointSettings = new ApplicationEndpointSettings(new SipUri(applicationEndpointUri)); ApplicationEndpoint = new ApplicationEndpoint(platform, endpointSettings, null); var loggingContext = new LoggingContext(Guid.NewGuid()); await ApplicationEndpoint.InitializeAsync(loggingContext).ConfigureAwait(false); await ApplicationEndpoint.InitializeApplicationAsync(loggingContext).ConfigureAwait(false); }
// Method to create an endpoint given a UserEndpointSettings object. // This method returns a UserEndpoint object so that you can wire up Endpoint-specific event handlers. // If you do not want to get endpoint specific event information at the time the endpoint is established, you may // want to call the CreateEstablishedUserEndpoint method directly. Otherwise, you may call ReadUserSettings // followed by CreateUserEndpoint, followed by EstablishUserEndpoint methods. public UserEndpoint CreateUserEndpoint(UserEndpointSettings userEndpointSettings) { // Reuse platform instance so that all endpoints share the same platform. if (_collabPlatform == null) { // Initialize and start the platform. ClientPlatformSettings clientPlatformSettings = new ClientPlatformSettings(_applicationName, _transportType); _collabPlatform = new CollaborationPlatform(clientPlatformSettings); } _userEndpoint = new UserEndpoint(_collabPlatform, userEndpointSettings); return(_userEndpoint); }
static void Main(string[] args) { Dictionary <string, string> skypeAuthSettings = new Dictionary <string, string>() { { "AAD_ClientId", "" }, { "AAD_ClientSecret", "" }, { "ApplicationEndpointId", "" }, { "DiscoverUri", "https://api.skypeforbusiness.com/platformservice/discover?Region=northamerica" } }; var logger = new StringLogger(); try { ClientPlatformSettings platformSettings = new ClientPlatformSettings(new Uri(skypeAuthSettings["DiscoverUri"]), new Guid(skypeAuthSettings["AAD_ClientId"]), null, skypeAuthSettings["AAD_ClientSecret"], false); var platform = new ClientPlatform(platformSettings, logger); //Prepare endpoint var endpointSettings = new ApplicationEndpointSettings(new SipUri(skypeAuthSettings["ApplicationEndpointId"])); ApplicationEndpoint applicationEndpoint = new ApplicationEndpoint(platform, endpointSettings, null); var loggingContext = new LoggingContext(Guid.NewGuid()); applicationEndpoint.InitializeAsync().GetAwaiter().GetResult(); applicationEndpoint.InitializeApplicationAsync().GetAwaiter().GetResult(); //Schedule meeting var input = new AdhocMeetingCreationInput(Guid.NewGuid().ToString("N") + "testMeeting"); var adhocMeeting = applicationEndpoint.Application.CreateAdhocMeetingAsync(input, loggingContext).Result; Console.WriteLine("ad hoc meeting uri : " + adhocMeeting.OnlineMeetingUri); Console.WriteLine("ad hoc meeting join url : " + adhocMeeting.JoinUrl); //Get anon join token IAnonymousApplicationToken anonToken = applicationEndpoint.Application.GetAnonApplicationTokenForMeetingAsync(adhocMeeting.JoinUrl, "https://contoso.com;https://litware.com;http://www.microsoftstore.com/store/msusa/en_US/home<https://urldefense.proofpoint.com/v2/url?u=https-3A__contoso.com-3Bhttps-3A_litware.com-3Bhttp-3A_www.microsoftstore.com_store_msusa_en-5FUS_home&d=DwMGaQ&c=Bi8ZWNNcZUBhi-AHLorvrkVH0ArnzxTAZ7C8kNcJoZo&r=uycUjr279qo0kuj5jNiyFqi9adZMUkMtmsdo99NlvRQ&m=7jet88f1Tbswi73IIaQYzhITPDlxR_mzF2flXNxdbwQ&s=ozm8LVnKFoAyQtSX8KWnm56u950cmjrR5fvfEpP1SfM&e=>", Guid.NewGuid().ToString(), loggingContext).Result; Console.WriteLine("Get anon token : " + anonToken.AuthToken); Console.WriteLine("Get discover url for web SDK : " + anonToken.AnonymousApplicationsDiscoverUri); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.Read(); }
private void InitializeEndpoint() { _platformSettings = new ClientPlatformSettings(null, _aadClientId, null, _aadClientSecret, true); var platform = new ClientPlatform(_platformSettings, Logger); _eventChannel = new FakeEventChannel(); var endpointSettings = new ApplicationEndpointSettings(_applicationEndpointId); _applicationEndpoint = new ApplicationEndpoint(platform, endpointSettings, _eventChannel); _applicationEndpoint.InitializeAsync(null).GetAwaiter().GetResult(); _applicationEndpoint.InitializeApplicationAsync(null).GetAwaiter().GetResult(); if (_applicationEndpoint.Application != null) { _isInitialized = true; } }
public async Task Run() { var logger = new SampleAppLogger(); logger.HttpRequestResponseNeedsToBeLogged = true; //Set to true if you want to log all http request and responses //Prepare platform ClientPlatformSettings platformSettings = new ClientPlatformSettings(QuickSamplesConfig.AAD_ClientSecret, Guid.Parse(QuickSamplesConfig.AAD_ClientId)); var platform = new ClientPlatform(platformSettings, logger); //Prepare endpoint var eventChannel = new FakeEventChannel(); var endpointSettings = new ApplicationEndpointSettings(new SipUri(QuickSamplesConfig.ApplicationEndpointId)); ApplicationEndpoint applicationEndpoint = new ApplicationEndpoint(platform, endpointSettings, eventChannel); var loggingContext = new LoggingContext(Guid.NewGuid()); await applicationEndpoint.InitializeAsync(loggingContext).ConfigureAwait(false); await applicationEndpoint.InitializeApplicationAsync(loggingContext).ConfigureAwait(false); //Schedule meeting var input = new AdhocMeetingCreationInput(Guid.NewGuid().ToString("N") + "testMeeting"); var adhocMeeting = await applicationEndpoint.Application.CreateAdhocMeetingAsync(loggingContext, input).ConfigureAwait(false); logger.Information("ad hoc meeting uri : " + adhocMeeting.OnlineMeetingUri); logger.Information("ad hoc meeting join url : " + adhocMeeting.JoinUrl); //Get anon join token IAnonymousApplicationToken anonToken = await applicationEndpoint.Application.GetAnonApplicationTokenForMeetingAsync( loggingContext, adhocMeeting.JoinUrl, "https://contoso.com;https://litware.com;http://www.microsoftstore.com/store/msusa/en_US/home", //Fill your own web site, For allow cross domain using Guid.NewGuid().ToString() //Should be unique everytime ).ConfigureAwait(false); logger.Information("Get anon token : " + anonToken.AuthToken); logger.Information("Get discover url for web SDK : " + anonToken.AnonymousApplicationsDiscoverUri.ToString()); Console.ForegroundColor = ConsoleColor.Green; logger.Information("RemoteAdvisor sample completed successfully!"); Console.ResetColor(); }
protected override async void OnStart(string[] args) { if (!Directory.Exists(Path.Combine(ZMachineSettings.AppDataFolder, "Saves"))) { Directory.CreateDirectory(Path.Combine(ZMachineSettings.AppDataFolder, "Saves")); } if (!Directory.Exists(Path.Combine(ZMachineSettings.AppDataFolder, "Games"))) { Log.Warn("No Z-Machine games included"); Directory.CreateDirectory(Path.Combine(ZMachineSettings.AppDataFolder, "Games")); } else { if (!Directory.GetFiles(Path.Combine(ZMachineSettings.AppDataFolder, "Games")).Any()) { Log.Warn("No Z-Machine games included"); } } var clientPlatformSettings = new ClientPlatformSettings("LyncZMachine", SipTransportType.Tls); _collabPlatform = new CollaborationPlatform(clientPlatformSettings); await _collabPlatform.StartupAsync(); _settings = new UserEndpointSettings( ZMachineSettings.Settings.Sip, ZMachineSettings.Settings.LyncServer //ConfigurationManager.AppSettings["sip"], //ConfigurationManager.AppSettings["LyncServer"] ) { Credential = new NetworkCredential( ZMachineSettings.Settings.Username, ZMachineSettings.Settings.Password, ZMachineSettings.Settings.Domain //ConfigurationManager.AppSettings["username"], //ConfigurationManager.AppSettings["pw"], //ConfigurationManager.AppSettings["domain"] ), AutomaticPresencePublicationEnabled = true }; _settings.Presence.UserPresenceState = PresenceState.UserAvailable; _endpoint = new UserEndpoint(_collabPlatform, _settings); await _endpoint.EstablishAsync(); _endpoint.RegisterForIncomingCall<InstantMessagingCall>(GameStarted); _webServer = WebApp.Start<Startup>(string.Format("http://+:{0}/ZMachine", ZMachineSettings.Settings.Port)); }
public async void TestSetup() { TestHelper.InitializeTokenMapper(); m_loggingContext = new LoggingContext(Guid.NewGuid()); var data = TestHelper.CreateApplicationEndpoint(); m_restfulClient = data.RestfulClient; m_clientPlatformSettings = data.ClientPlatformSettings; m_mockEventChannel = data.EventChannel; await data.ApplicationEndpoint.InitializeAsync(m_loggingContext).ConfigureAwait(false); await data.ApplicationEndpoint.InitializeApplicationAsync(m_loggingContext).ConfigureAwait(false); m_application = data.ApplicationEndpoint.Application; m_adhocMeeting = await m_application.CreateAdhocMeetingAsync(new AdhocMeetingCreationInput("subject"), m_loggingContext).ConfigureAwait(false); }
public void Start(List <Uri> chatRoomsToJoin) { chatRooms = chatRoomsToJoin; Log(string.Format("Start Client: chatRooms.Count={0}", chatRooms.Count)); currentOperation.Reset(); // Connect to OCS ClientPlatformSettings platformSettings = new ClientPlatformSettings("PersistentChat.Test", SipTransportType.Tls); CollaborationPlatform collabPlatform = new CollaborationPlatform(platformSettings); collabPlatform.EndStartup(collabPlatform.BeginStartup(null, null)); UserEndpointSettings userEndpointSettings = new UserEndpointSettings(UserUri.AbsoluteUri, SampleCommon.OcsServer); userEndpointSettings.Credential = new NetworkCredential(UserName, Password); userEndpoint = new UserEndpoint(collabPlatform, userEndpointSettings); // Login to OCS currentOperation.Begin("Connect to OCS", () => userEndpoint.BeginEstablish(OcsBeginEstablishFinished, null)); }
public static UserEndpoint ConnectLyncServer(string userSipUri, string lyncServer, bool usingSso, string username, string password) { // Create the Lync Server UserEndpoint and attempt to connect to Lync Server Console.WriteLine("{0} Connecting to Lync Server... [{1}]", username, lyncServer); // Use the appropriate SipTransportType depending on current Lync Server deployment ClientPlatformSettings platformSettings = new ClientPlatformSettings("PersistentChat.Test", SipTransportType.Tls); CollaborationPlatform collabPlatform = new CollaborationPlatform(platformSettings); collabPlatform.AllowedAuthenticationProtocol = SipAuthenticationProtocols.Ntlm; // Initialize the platform collabPlatform.EndStartup(collabPlatform.BeginStartup(null, null)); // You can also pass in the server's port # here. UserEndpointSettings userEndpointSettings = new UserEndpointSettings(userSipUri, lyncServer); // When usingSso is true use the current users credentials, otherwise use username and password userEndpointSettings.Credential = usingSso ? SipCredentialCache.DefaultCredential : new NetworkCredential(username, password); UserEndpoint userEndpoint = new UserEndpoint(collabPlatform, userEndpointSettings); // Login to Lync Server. userEndpoint.EndEstablish(userEndpoint.BeginEstablish(null, null)); if (PersistentChatServerUri == null) { // Extract default Persistent Chat pool uri from inband ProvisioningData provisioningData = userEndpoint.EndGetProvisioningData(userEndpoint.BeginGetProvisioningData(null, null)); PersistentChatServerUri = new Uri(provisioningData.PersistentChatConfiguration.DefaultPersistentChatUri); Console.WriteLine("\t-- {0}PersistentChatServerUri:{1}", username, PersistentChatServerUri); } Console.WriteLine("\t{0} Connecting>>>>Success", username); return(userEndpoint); }
private async Task InitializeApplicationEndpointAsync() { //Read application auth settings var applicationEndpointUri = ConfigurationManager.AppSettings["ApplicationEndpointId"]; var aadClientId = ConfigurationManager.AppSettings["AAD_ClientId"]; var aadClientSecret = ConfigurationManager.AppSettings["AAD_ClientSecret"]; //Get singleton logger var logger = UnityHelper.Resolve <IPlatformServiceLogger>(); logger.HttpRequestResponseNeedsToBeLogged = true; //Get singleton event channel var eventChannel = UnityHelper.Resolve <SimpleEventChannel>(); //Initialize platform var platformSettings = new ClientPlatformSettings ( aadClientSecret, Guid.Parse(aadClientId) ); var platform = new ClientPlatform(platformSettings, logger); //Initialize application and application endpoint var endpointSettings = new ApplicationEndpointSettings(new SipUri(applicationEndpointUri)); var ApplicationEndpoint = new ApplicationEndpoint(platform, endpointSettings, eventChannel); var loggingContext = new LoggingContext(Guid.NewGuid()); await ApplicationEndpoint.InitializeAsync(loggingContext).ConfigureAwait(false); await ApplicationEndpoint.InitializeApplicationAsync(loggingContext).ConfigureAwait(false); //Hook up listener for incoming call ApplicationEndpoint.HandleIncomingAudioVideoCall += HandleIncomingAVCall; }
//TODO: Open this method once sandbox Env is ready internal static void SetIsSandboxEnv(this ClientPlatformSettings This, bool isSandboxEnv) { This.IsSandBoxEnv = isSandboxEnv; }
// Method to create an endpoint given a UserEndpointSettings object. // This method returns a UserEndpoint object so that you can wire up Endpoint-specific event handlers. // If you do not want to get endpoint specific event information at the time the endpoint is established, you may // want to call the CreateEstablishedUserEndpoint method directly. Otherwise, you may call ReadUserSettings // followed by CreateUserEndpoint, followed by EstablishUserEndpoint methods. public UserEndpoint CreateUserEndpoint(UserEndpointSettings userEndpointSettings) { // Reuse platform instance so that all endpoints share the same platform. if (_collabPlatform == null) { // Initialize and start the platform. ClientPlatformSettings clientPlatformSettings = new ClientPlatformSettings(_applicationName, _transportType); _collabPlatform = new CollaborationPlatform(clientPlatformSettings); } _userEndpoint = new UserEndpoint(_collabPlatform, userEndpointSettings); return _userEndpoint; }
public async Task RunAsync(Uri callbackUri) { m_logger = new SampleAppLogger(); // Uncomment for debugging // m_logger.HttpRequestResponseNeedsToBeLogged = true; // You can hook up your own implementation of IEventChannel here IEventChannel eventChannel = WebEventChannel.WebEventChannel.Instance; // Prepare platform var platformSettings = new ClientPlatformSettings(QuickSamplesConfig.AAD_ClientSecret, new Guid(QuickSamplesConfig.AAD_ClientId)); var platform = new ClientPlatform(platformSettings, m_logger); // Prepare endpoint var endpointSettings = new ApplicationEndpointSettings(new SipUri(QuickSamplesConfig.ApplicationEndpointId)); var applicationEndpoint = new ApplicationEndpoint(platform, endpointSettings, eventChannel); var loggingContext = new LoggingContext(Guid.NewGuid()); await applicationEndpoint.InitializeAsync(loggingContext).ConfigureAwait(false); await applicationEndpoint.InitializeApplicationAsync(loggingContext).ConfigureAwait(false); // Meeting configuration var meetingConfiguration = new AdhocMeetingCreationInput(Guid.NewGuid().ToString("N") + " test meeting"); // Schedule meeting var adhocMeeting = await applicationEndpoint.Application.CreateAdhocMeetingAsync(meetingConfiguration, loggingContext).ConfigureAwait(false); WriteToConsoleInColor("ad hoc meeting uri : " + adhocMeeting.OnlineMeetingUri); WriteToConsoleInColor("ad hoc meeting join url : " + adhocMeeting.JoinUrl); // Get all the events related to join meeting through our custom callback uri platformSettings.SetCustomizedCallbackurl(callbackUri); // Start joining the meeting ICommunication communication = applicationEndpoint.Application.Communication; if (!communication.CanJoinAdhocMeeting(adhocMeeting)) { throw new Exception("Cannot join adhoc meeting"); } var invitation = await communication.JoinAdhocMeetingAsync(adhocMeeting, null, loggingContext).ConfigureAwait(false); // Wait for the join to complete await invitation.WaitForInviteCompleteAsync().ConfigureAwait(false); WriteToConsoleInColor("Please use this url to join the meeting : " + adhocMeeting.JoinUrl); WriteToConsoleInColor("Giving 30 seconds for the user to join the meeting..."); await Task.Delay(TimeSpan.FromSeconds(30)).ConfigureAwait(false); var conversation = invitation.RelatedConversation; var imCall = invitation.RelatedConversation.MessagingCall; if (imCall == null) { WriteToConsoleInColor("No messaging call link found in conversation of the conference."); return; } var messagingInvitation = await imCall.EstablishAsync(loggingContext).ConfigureAwait(false); messagingInvitation.HandleResourceCompleted += OnMessagingInvitationCompleted; await messagingInvitation.WaitForInviteCompleteAsync().ConfigureAwait(false); if (imCall.State != CallState.Connected) { WriteToConsoleInColor("Messaging call is not connected."); return; } var modalities = invitation.RelatedConversation.ActiveModalities; WriteToConsoleInColor("Active modalities : "); bool hasMessagingModality = false; foreach (var modality in modalities) { WriteToConsoleInColor(" " + modality.ToString()); if (modality == ConversationModalityType.Messaging) { hasMessagingModality = true; } } if (!hasMessagingModality) { WriteToConsoleInColor("Failed to connect messaging call.", ConsoleColor.Red); return; } WriteToConsoleInColor("Adding messaging to meeting completed successfully."); WriteToConsoleInColor("Sending Hellow World!"); await imCall.SendMessageAsync("Hello World!", loggingContext).ConfigureAwait(false); WriteToConsoleInColor("Sent Hello World!"); await WebEventChannel.WebEventChannel.Instance.TryStopAsync().ConfigureAwait(false); }
private async void btnTest_Click(object sender, EventArgs e) { try { Cursor = Cursors.WaitCursor; var clientPlatformSettings = new ClientPlatformSettings("LyncZMachine", SipTransportType.Tls); var collabPlatform = new CollaborationPlatform(clientPlatformSettings); await collabPlatform.StartupAsync(); var settings = new UserEndpointSettings(txtSip.Text, txtServer.Text) { Credential = new NetworkCredential(txtUsername.Text, txtPassword.Text, txtDomain.Text), AutomaticPresencePublicationEnabled = true }; var endpoint = new UserEndpoint(collabPlatform, settings); await endpoint.EstablishAsync(); btnSave.Enabled = true; MessageBox.Show("Connected successfully to " + txtServer.Text + " as " + txtSip.Text); try { await endpoint.TerminateAsync(); await collabPlatform.ShutdownAsync(); } catch (Exception ex) { MessageBox.Show(ex.Message, "An Error Occurred", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } catch (Exception ex) { MessageBox.Show(ex.Message, "An Error Occurred", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); btnSave.Enabled = false; } finally { Cursor = Cursors.Default; } }
public void Run() { //Initalize and startup the platform. ClientPlatformSettings clientPlatformSettings = new ClientPlatformSettings(_applicationName, _transportType); _collabPlatform = new CollaborationPlatform(clientPlatformSettings); _collabPlatform.BeginStartup(EndPlatformStartup, _collabPlatform); // Get port range NetworkPortRange portRange = CollaborationPlatform.AudioVideoSettings.GetPortRange(); Console.WriteLine("Port range is from " + portRange.LocalNetworkPortMin + " to " + portRange.LocalNetworkPortMax); // Modifying port range portRange.SetRange(1500, 2000); CollaborationPlatform.AudioVideoSettings.SetPortRange(portRange); Console.WriteLine("Port range now is from " + portRange.LocalNetworkPortMin + " to " + portRange.LocalNetworkPortMax); //Sync; wait for the startup to complete. _autoResetEvent.WaitOne(); //Initalize and register the endpoint, using the credentials of the user the application will be acting as. UserEndpointSettings userEndpointSettings = new UserEndpointSettings(_userURI, _userServer); userEndpointSettings.Credential = _credential; _userEndpoint = new UserEndpoint(_collabPlatform, userEndpointSettings); _userEndpoint.BeginEstablish(EndEndpointEstablish, _userEndpoint); //Sync; wait for the registration to complete. _autoResetEvent.WaitOne(); //Setup the conversation and place the call. ConversationSettings convSettings = new ConversationSettings(); convSettings.Priority = _conversationPriority; convSettings.Subject = _conversationSubject; //Conversation represents a collection of modalities in the context of a dialog with one or multiple callees. Conversation conversation = new Conversation(_userEndpoint, convSettings); _audioVideoCall = new AudioVideoCall(conversation); //Call: StateChanged: Only hooked up for logging. _audioVideoCall.StateChanged += new EventHandler <CallStateChangedEventArgs>(audioVideoCall_StateChanged); //Subscribe for the flow configuration requested event; the flow will be used to send the media. //Ultimately, as a part of the callback, the media will be sent/recieved. _audioVideoCall.AudioVideoFlowConfigurationRequested += this.audioVideoCall_FlowConfigurationRequested; //Place the call to the remote party; _audioVideoCall.BeginEstablish(_calledParty, null, EndCallEstablish, _audioVideoCall); //Sync; wait for the call to complete. _autoResetEvent.WaitOne(); // Shutdown the platform _collabPlatform.BeginShutdown(EndPlatformShutdown, _collabPlatform); //Wait for shutdown to occur. _autoResetShutdownEvent.WaitOne(); }
public async Task RunAsync() { var skypeId = ConfigurationManager.AppSettings["Trouter_SkypeId"]; var password = ConfigurationManager.AppSettings["Trouter_Password"]; var applicationName = ConfigurationManager.AppSettings["Trouter_ApplicationName"]; var userAgent = ConfigurationManager.AppSettings["Trouter_UserAgent"]; var token = SkypeTokenClient.ConstructSkypeToken( skypeId: skypeId, password: password, useTestEnvironment: false, scope: string.Empty, applicationName: applicationName).Result; m_logger = new SampleAppLogger(); // Uncomment for debugging // m_logger.HttpRequestResponseNeedsToBeLogged = true; EventChannel = new TrouterBasedEventChannel(m_logger, token, userAgent); // Prepare platform var platformSettings = new ClientPlatformSettings(QuickSamplesConfig.AAD_ClientSecret, new Guid(QuickSamplesConfig.AAD_ClientId)); var platform = new ClientPlatform(platformSettings, m_logger); // Prepare endpoint var endpointSettings = new ApplicationEndpointSettings(new SipUri(QuickSamplesConfig.ApplicationEndpointId)); var applicationEndpoint = new ApplicationEndpoint(platform, endpointSettings, EventChannel); var loggingContext = new LoggingContext(Guid.NewGuid()); await applicationEndpoint.InitializeAsync(loggingContext).ConfigureAwait(false); await applicationEndpoint.InitializeApplicationAsync(loggingContext).ConfigureAwait(false); // Meeting configuration var meetingConfiguration = new AdhocMeetingCreationInput(Guid.NewGuid().ToString("N") + " test meeting"); // Schedule meeting var adhocMeeting = await applicationEndpoint.Application.CreateAdhocMeetingAsync(loggingContext, meetingConfiguration).ConfigureAwait(false); WriteToConsoleInColor("ad hoc meeting uri : " + adhocMeeting.OnlineMeetingUri); WriteToConsoleInColor("ad hoc meeting join url : " + adhocMeeting.JoinUrl); // Get all the events related to join meeting through Trouter's uri platformSettings.SetCustomizedCallbackurl(new Uri(EventChannel.CallbackUri)); // Start joining the meeting var invitation = await adhocMeeting.JoinAdhocMeeting(loggingContext, null).ConfigureAwait(false); // Wait for the join to complete await invitation.WaitForInviteCompleteAsync().ConfigureAwait(false); WriteToConsoleInColor("Please use this url to join the meeting : " + adhocMeeting.JoinUrl); WriteToConsoleInColor("Giving 30 seconds for the user to join the meeting..."); await Task.Delay(TimeSpan.FromSeconds(30)).ConfigureAwait(false); var conversation = invitation.RelatedConversation; var imCall = invitation.RelatedConversation.MessagingCall; if (imCall == null) { WriteToConsoleInColor("No messaging call link found in conversation of the conference."); return; } var messagingInvitation = await imCall.EstablishAsync(loggingContext).ConfigureAwait(false); messagingInvitation.HandleResourceCompleted += OnMessagingResourceCompletedReceived; await messagingInvitation.WaitForInviteCompleteAsync().ConfigureAwait(false); if (imCall.State != CallState.Connected) { WriteToConsoleInColor("Messaging call is not connected."); return; } var modalities = invitation.RelatedConversation.ActiveModalities; WriteToConsoleInColor("Active modalities : "); bool hasMessagingModality = false; foreach (var modality in modalities) { WriteToConsoleInColor(" " + modality.ToString()); if (modality == ConversationModalityType.Messaging) { hasMessagingModality = true; } } await imCall.SendMessageAsync("Hello World.", loggingContext).ConfigureAwait(false); if (!hasMessagingModality) { WriteToConsoleInColor("Failed to connect messaging call.", ConsoleColor.Red); return; } WriteToConsoleInColor("Adding messaging to meeting completed successfully."); }
public static void SetIsInternalPartner(this ClientPlatformSettings This, bool isInternalPartner) { This.IsInternalPartner = isInternalPartner; }
/// <summary> /// Setup Collaboration Platform /// </summary> private void StartPlatform() { try { if (!useUserEndPoint) { string localhost = Dns.GetHostEntry("localhost").HostName; // Config change: for conditional Auto Provisioning. if (this.useApplicationAutoProvisioning) { ProvisionedApplicationPlatformSettings appSettings = new ProvisionedApplicationPlatformSettings("fasthelp", this.applicationId); this.collabPlatform = new CollaborationPlatform(appSettings); this.collabPlatform.RegisterForApplicationEndpointSettings( this.Platform_ApplicationEndpointOwnerDiscovered); } else { ServerPlatformSettings platform = new ServerPlatformSettings(this.applicationName, localhost, this.port, this.gruu, CertificateHelper.GetLocalCertificate(this.certificateName)); platform.TrustedDomains.Add(new TrustedDomain(".fabrikam.com")); this.collabPlatform = new CollaborationPlatform(platform); } Console.WriteLine("Publishing Presence"); } else { // Initalize and startup the platform. ClientPlatformSettings clientPlatformSettings = new ClientPlatformSettings(this.applicationName, this.transportType); this.collabPlatform = new CollaborationPlatform(clientPlatformSettings); } this.logger.Log("Starting the platform."); Console.WriteLine("Starting the platform."); this.collabPlatform.EndStartup(this.collabPlatform.BeginStartup(null, null)); Console.WriteLine("Starting the platform complete."); // Config change: for conditional Auto Provisioning. if (!this.useApplicationAutoProvisioning) { this.StartEndpoint(); } } catch (InvalidOperationException ioe) { Console.WriteLine(ioe.ToString()); } catch (ConnectionFailureException connFailEx) { // ConnectionFailureException will be thrown when the platform cannot connect Console.WriteLine(connFailEx.ToString()); this.logger.Log("Connection Failure Exception {0}", connFailEx); } catch (ProvisioningFailureException provFailEx) { // ProvisioningFailureException will be thrown when the platform cannot find the trusted application // entry per the application ID passed in ProvisionedApplicationPlatformSettings. Console.WriteLine(provFailEx.ToString()); this.logger.Log("Provisioning Failure Exception {0}", provFailEx); } catch (RealTimeException rte) { Console.WriteLine(rte); this.logger.Log("Platform failed to start {0}", rte); } }
public void SendMessage(string[] targets, string subject, string message, InstantMessagePriority priority) { var cps = new ClientPlatformSettings(null, SipTransportType.Tls); var cp = new CollaborationPlatform(cps); var us = new UserEndpointSettings(string.Format("sip:{0}", _username)) { Credential = new NetworkCredential(_username, _password) }; log.DebugFormat("OwnerUri: {0}", us.OwnerUri); var ue = new UserEndpoint(cp, us); // start up the platform Task.Factory.FromAsync(ue.Platform.BeginStartup, ue.Platform.EndStartup, null).Wait(); Task.Factory.FromAsync <SipResponseData>(ue.BeginEstablish, ue.EndEstablish, null).Wait(); // send the messages var tasks = targets.Select(t => { var cts = new CancellationTokenSource(TimeSpan.FromMinutes(2)); var tsc = new TaskCompletionSource <SendInstantMessageResult>(); cts.Token.Register(() => tsc.TrySetCanceled()); var sent = false; var doSend = new Action <InstantMessagingFlow>(flow => { if (sent || flow.State != MediaFlowState.Active) { return; } sent = true; Task.Factory.FromAsync <string, SendInstantMessageResult>( flow.BeginSendInstantMessage, flow.EndSendInstantMessage, message, null) .ContinueWith( r => { if (r.IsCanceled) { tsc.TrySetCanceled(); } else if (r.IsFaulted) { tsc.TrySetException(r.Exception); } else { tsc.TrySetResult(r.Result); } }); }); var p = priority == InstantMessagePriority.Emergency ? ConversationPriority.Emergency : priority == InstantMessagePriority.Urgent ? ConversationPriority.Urgent : priority == InstantMessagePriority.NonUrgent ? ConversationPriority.NonUrgent : ConversationPriority.Normal; var c = new Conversation(ue, new ConversationSettings() { Priority = p }); var im = new InstantMessagingCall(c); im.InstantMessagingFlowConfigurationRequested += (sender, args) => { doSend(im.Flow); im.Flow.StateChanged += (o, eventArgs) => { doSend(im.Flow); }; }; Task.Factory.FromAsync <string, ToastMessage, CallEstablishOptions, CallMessageData>(im.BeginEstablish, im.EndEstablish, "sip:" + t, new ToastMessage(subject), null, null).ContinueWith(r => { if (r.IsCanceled) { tsc.TrySetCanceled(); } else if (r.IsFaulted) { tsc.TrySetException(r.Exception); } }); return(tsc.Task); }).ToArray(); // wait for the messages to go Task.WhenAll(tasks).ContinueWith(r => { if (r.IsCanceled) { log.DebugFormat("Message send was cancelled"); } else if (r.IsFaulted) { log.WarnFormat("Message send failed: {0}", r.Exception); } Task.Factory.FromAsync(ue.Platform.BeginShutdown, ue.Platform.EndShutdown, null).Wait(); }); }