public void Run()
        {
            // Create and establish the endpoint, using the credentials of the user the application will be acting as.
            _helper       = new UCMASampleHelper();
            _userEndpoint = _helper.CreateEstablishedUserEndpoint("VoiceXML Sample User" /*endpointFriendlyName*/);
            _userEndpoint.RegisterForIncomingCall <AudioVideoCall>(inboundAVCall_CallReceived);

            // Pause the main thread until a call is received and then accepted.
            _waitForCallReceived.WaitOne();
            _waitForCallAccepted.WaitOne();

            InitializeVoiceXmlBrowser();
            _voiceXmlBrowser.SetAudioVideoCall(_audioVideoCall);
            Uri startPageURI = new Uri(startPageURL);

            Console.WriteLine("Browser state: " + _voiceXmlBrowser.State.ToString());
            _voiceXmlBrowser.RunAsync(startPageURI, null);
            _waitForSessionCompleted.WaitOne();

            _collabPlatform = _conversation.Endpoint.Platform;
            // Terminate the call.
            _audioVideoCall.BeginTerminate(CallTerminateCB, _audioVideoCall);

            _waitForPlatformShutdownCompleted.WaitOne();

            // Pause the console to allow the user to view logs.
            Console.WriteLine("Press any key to end the sample.");
            Console.ReadKey();
        }
Example #2
0
        private void Run()
        {
            // A helper class to take care of platform and endpoint setup and
            // cleanup. This has been abstracted from this sample to focus on
            // Call Control.
            _helper = new UCMASampleHelper();

            // Create a user endpoint, using the network credential object
            // defined above.
            _userEndpoint = _helper.CreateEstablishedUserEndpoint("DeclineCall Sample User" /*endpointFriendlyName*/);


            // Here, we are Declining an Instant Messaging call only. If the
            // incoming call is not an Instant Messaging call (for example, an
            // AudioVideo call, or a custom (Foo) Call, then it will not get
            // raised to the application. UCMA 3.0 handles this silently by
            // having the call types register for various modalities (as part of
            // the extensibility framework). The appropriate action (here,
            // declining the call) will be handled in the handler assigned to the
            // method call below.
            _userEndpoint.RegisterForIncomingCall <InstantMessagingCall>(On_InstantMessagingCall_Received);

            // Wait for the call to complete Decline, then shutdown the platform.
            Console.WriteLine("Waiting for incoming call...");
            _autoResetEvent.WaitOne();

            UCMASampleHelper.PauseBeforeContinuing("Press ENTER to shutdown and exit.");

            // Shut down the sample.
            _helper.ShutdownPlatform();
        }
Example #3
0
        public void Run()
        {
            // Initialize and register the endpoint, using the credentials of the user the application will be acting as.
            _helper       = new UCMASampleHelper();
            _userEndpoint = _helper.CreateEstablishedUserEndpoint("B2BCall Sample User" /*endpointFriendlyName*/);
            _userEndpoint.RegisterForIncomingCall <AudioVideoCall>(inboundAVCall_CallReceived);

            // Conversation settings for the outbound call (to the agent).
            ConversationSettings outConvSettings = new ConversationSettings();

            outConvSettings.Priority = _conversationPriority;
            outConvSettings.Subject  = _outConversationSubject;

            // Create the Conversation instance between UCMA and the agent.
            _outboundConversation = new Conversation(_userEndpoint, outConvSettings);

            // Create the outbound call between UCMA and the agent.
            _outboundAVCall = new AudioVideoCall(_outboundConversation);

            // Register for notification of the StateChanged event on the outbound call.
            _outboundAVCall.StateChanged += new EventHandler <CallStateChangedEventArgs>(outboundAVCall_StateChanged);

            // Prompt for called party - the agent.
            _calledParty = UCMASampleHelper.PromptUser("Enter the URI of the called party, in sip:User@Host form or tel:+1XXXYYYZZZZ form => ", "RemoteUserURI1");

            _outboundCallLeg = new BackToBackCallSettings(_outboundAVCall, _calledParty);

            // Pause the main thread until both calls, the BackToBackCall, both conversations,
            // and the platform are shut down.
            _waitUntilOneUserHangsUp.WaitOne();

            // Pause the console to allow for easier viewing of logs.
            Console.WriteLine("Press any key to end the sample.");
            Console.ReadKey();
        }
        //Launches an instant message. Text of the message depends on the parameter value.
        public void UcmaIM(Int32 choice)
        {
            helper       = new UCMASampleHelper();
            userEndpoint = helper.CreateEstablishedUserEndpoint("SampleUser");
            Console.WriteLine("endpoint owned by " + userEndpoint.OwnerUri + " is established/registered");

            ConversationSettings conversationSettings = new ConversationSettings();

            conversationSettings.Subject = conversationSubject;
            Conversation conversation = new Conversation(userEndpoint, conversationSettings);

            ImCall = new InstantMessagingCall(conversation);
            ImCall.InstantMessagingFlowConfigurationRequested += new EventHandler <InstantMessagingFlowConfigurationRequestedEventArgs>(ImCall_InstantMessagingFlowConfigurationRequested);

            Int32 helloChoice   = 1;
            Int32 goodbyeChoice = 2;

            if (choice == helloChoice)
            {
                messageText = "hello";
            }
            else if (choice == goodbyeChoice)
            {
                messageText = "goodbye";
            }
            else
            {
                messageText = "press 1 or press 2";
            }

            string targetURI = ConfigurationManager.AppSettings["UserURI1"];

            ImCall.BeginEstablish(targetURI, null, CallEstablishCompleted, null);
            completedEvent.WaitOne();
        }
Example #5
0
        public void Run()
        {
            // A helper class to take care of platform and endpoint setup and cleanup.
            _helper = new UCMASampleHelper();

            // Create a user endpoint using the network credential object.
            _userEndpoint = _helper.CreateEstablishedUserEndpoint("Broadcast User");

            // Register a delegate to be called when an incoming audio-video call arrives.
            _userEndpoint.RegisterForIncomingCall <AudioVideoCall>(AudioVideoCall_Received);

            // Wait for the incoming call to be accepted.
            Console.WriteLine("Waiting for incoming call...");
            _waitForCallToBeAccepted.WaitOne();

            // Create a speech recognition connector and attach an AudioVideoFlow to it.
            SpeechRecognitionConnector speechRecognitionConnector = new SpeechRecognitionConnector();

            speechRecognitionConnector.AttachFlow(_audioVideoFlow);

            // Start the speech recognition connector.
            SpeechRecognitionStream stream = speechRecognitionConnector.Start();

            // Create a speech recognition engine.
            SpeechRecognitionEngine speechRecognitionEngine = new SpeechRecognitionEngine();

            speechRecognitionEngine.SpeechRecognized += new EventHandler <SpeechRecognizedEventArgs>(SpeechRecognitionEngine_SpeechRecognized);

            //Add a grammar.
            string[] recoString = { "buy", "sell", "Fabrikam", "Contoso", "maximum", "minimum", "one", "ten", "twenty", "send" };
            Choices  choices    = new Choices(recoString);

            speechRecognitionEngine.LoadGrammar(new Grammar(new GrammarBuilder(choices)));

            //Attach to audio stream to the SR engine.
            SpeechAudioFormatInfo speechAudioFormatInfo = new SpeechAudioFormatInfo(8000, AudioBitsPerSample.Sixteen, Microsoft.Speech.AudioFormat.AudioChannel.Mono);

            speechRecognitionEngine.SetInputToAudioStream(stream, speechAudioFormatInfo);
            Console.WriteLine("\r\nGrammar loaded, say send to send IM.");

            //Prepare the SR engine to perform multiple asynchronous recognitions.
            speechRecognitionEngine.RecognizeAsync(RecognizeMode.Multiple);

            //Pause the main thread until recognition completes.
            _waitForConnectorToStop.WaitOne();
            speechRecognitionConnector.Stop();
            Console.WriteLine("connector stopped");

            // Detach the flow from the speech recognition connector, to prevent the flow from being kept in memory.
            speechRecognitionConnector.DetachFlow();

            // Terminate the call, the conversation, and then unregister the
            // endpoint from receiving an incoming call.
            _audioVideoCall.BeginTerminate(CallTerminateCB, _audioVideoCall);
            _waitForConversationToBeTerminated.WaitOne();

            // Shut down the platform.
            _helper.ShutdownPlatform();
        }
Example #6
0
        /// <summary>
        /// Record the endpoint state transitions to the console.
        /// </summary>
        /// <param name="sender">Endpoint that saw its state change.</param>
        /// <param name="e">Data about the endpoint state change event.</param>
        private void _endpoint_StateChanged(object sender, LocalEndpointStateChangedEventArgs e)
        {
            // Extract the endpoint that sent the state change event.
            ApplicationEndpoint endpoint = sender as ApplicationEndpoint;

            UCMASampleHelper.WriteLine("Endpoint (" + endpoint.OwnerUri
                                       + ") has changed state. The previous endpoint state was '"
                                       + e.PreviousState + "' and the current state is '" + e.State + "'.");
        }
Example #7
0
        /// <summary>
        /// Retrieves the application configuration and begins running the
        /// sample.
        /// </summary>
        void Run()
        {
            _appID = null;
            try
            {
                // Attempt to retrieve the application ID of the provisioned
                // application from the config file.
                _appID = System.Configuration.ConfigurationManager.AppSettings["ApplicationID"];
                if (string.IsNullOrEmpty(_appID))
                {
                    // The application ID wasn't retrieved from the config file
                    // so prompt for the application ID for the application that
                    // has been provisioned.
                    string prompt = "Please enter the unique ID of the application that is provisioned in "
                                    + "the topology => ";
                    _appID = UCMASampleHelper.PromptUser(prompt, null);
                }
                if (!string.IsNullOrEmpty(_appID))
                {
                    Console.WriteLine("Creating CollaborationPlatform for the provisioned application with "
                                      + "ID \'{0}\' using ProvisionedApplicationPlatformSettings.", _appID);
                    ProvisionedApplicationPlatformSettings settings
                                    = new ProvisionedApplicationPlatformSettings("UCMASampleApp", _appID);
                    _collabPlatform = new CollaborationPlatform(settings);

                    // Wire up a handler for the
                    // ApplicationEndpointOwnerDiscovered event.
                    _collabPlatform.RegisterForApplicationEndpointSettings(
                        this.Platform_ApplicationEndpointOwnerDiscovered);

                    // Initialize and startup the platform.
                    _collabPlatform.BeginStartup(EndPlatformStartup, _collabPlatform);
                }
                else
                {
                    Console.WriteLine("No application ID was specified by the user.");
                }
                UCMASampleHelper.PauseBeforeContinuing("Press ENTER to shutdown and exit.");
            }
            catch (InvalidOperationException iOpEx)
            {
                // Invalid Operation Exception may be thrown if the data
                // provided to the BeginXXX methods was
                // invalid/malformed.
                // TODO (Left to the reader): Write actual handling code for the
                // occurrence.
                Console.WriteLine("Invalid Operation Exception: " + iOpEx.ToString());
            }
            finally
            {
                // Terminate the platform which would in turn terminate any
                // endpoints.
                Console.WriteLine("Shutting down the platform.");
                ShutdownPlatform();
            }
        }
Example #8
0
        public void Run()
        {
            //Initialize and register the endpoint, using the credentials of the user the application will be acting as.
            _helper       = new UCMASampleHelper();
            _userEndpoint = _helper.CreateEstablishedUserEndpoint("AVCall Sample User" /*endpointFriendlyName*/);

            //Set up 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/received.
            _audioVideoCall.AudioVideoFlowConfigurationRequested += this.audioVideoCall_FlowConfigurationRequested;

            // Prompt for called party
            _calledParty = UCMASampleHelper.PromptUser("Enter the URI for the user logged onto Microsoft Lync, in the sip:User@Host format or tel:+1XXXYYYZZZZ format => ", "RemoteUserURI");

            //Place the call to the remote party.
            _audioVideoCall.BeginEstablish(_calledParty, null, EndCallEstablish, _audioVideoCall);

            //Sync; wait for the call to complete.
            Console.WriteLine("Calling the remote user...");
            _waitForCallToEstablish.WaitOne();

            // Terminate the call, and then the conversation.
            // Terminating these additional objects individually is made redundant by shutting down the platform right after, but in the multiple call case,
            // this is needed for object hygene. Terminating a Conversation terminates all it's associated calls, and terminating an endpoint will terminate
            // all conversations on that endpoint.
            _audioVideoCall.BeginTerminate(EndTerminateCall, _audioVideoCall);
            Console.WriteLine("Waiting for the call to get terminated...");
            _waitForCallToTerminate.WaitOne();
            _audioVideoCall.Conversation.BeginTerminate(EndTerminateConversation, _audioVideoCall.Conversation);
            Console.WriteLine("Waiting for the conversation to get terminated...");
            _waitForConversationToTerminate.WaitOne();

            //Now, cleanup by shutting down the platform.
            Console.WriteLine("Shutting down the platform...");
            _helper.ShutdownPlatform();

            // Pause the console to allow for easier viewing of logs.
            Console.WriteLine("Please hit any key to end the sample.");
            Console.ReadKey();
        }
Example #9
0
        private void Run()
        {
            // A helper class to take care of platform and endpoint setup and
            // cleanup. This has been abstracted from this sample to focus on
            // Call Control.
            _helper = new UCMASampleHelper();

            // Create a user endpoint, using the network credential object
            // defined above.
            UserEndpoint callerEndpoint = _helper.CreateEstablishedUserEndpoint(
                "Caller" /*endpointFriendlyName*/);

            // Create a second user endpoint, using the network credential object
            // defined above.
            UserEndpoint calleeEndpoint = _helper.CreateEstablishedUserEndpoint(
                "Callee" /*endpointFriendlyName*/);

            // Here, we are accepting an Instant Messaging call only. If the
            // incoming call is not an Instant Messaging call (for example, an
            // AudioVideo call or a custom Call, then it will not get raised to
            // the application. UCMA 3.0 handles this silently by having the call
            // types register for various modalities (as part of the extensibility
            // framework). The appropriate action (here, accepting the call) will
            // be handled in the handler assigned to the method call below.
            calleeEndpoint.RegisterForIncomingCall <InstantMessagingCall>(On_InstantMessagingCall_Received);

            // Setup the call and conversation objects for the initial call (IM)
            // and place the call (synchronously).
            _conversation = new Conversation(callerEndpoint);
            InstantMessagingCall instantMessagingCall = new InstantMessagingCall(_conversation);


            // Add registration for the AudioVideo modality, before placing the
            // second call. This could have been done at any time before placing
            // the audio video call. This handler could choose to accept, deflect
            // or drop this portion of the call entirely.
            calleeEndpoint.RegisterForIncomingCall <AudioVideoCall>(On_AudioVideoCall_Received);

            // Place the call to the remote party, without specifying any custom
            // options.
            instantMessagingCall.BeginEstablish(calleeEndpoint.OwnerUri, new ToastMessage("Sample Toast Message"),
                                                null, CallEstablishCompleted, instantMessagingCall);

            // Force synchronization to ensure that the both AVCall and IMCall
            // are now complete.
            _sampleCompleted.WaitOne();

            UCMASampleHelper.PauseBeforeContinuing("Press ENTER to shutdown and exit.");

            //And shutdown (synchronously).
            Console.WriteLine("Shutting down the sample...");
            _helper.ShutdownPlatform();
        }
Example #10
0
        /// <summary>
        /// Retrieves the application configuration and begins running the
        /// sample.
        /// </summary>
        private void Run()
        {
            try
            {
                // Prepare and instantiate the platform.
                _helper = new UCMASampleHelper();
                UserEndpointSettings userEndpointSettings = _helper.ReadUserSettings(
                    "PublishPresence Sample User" /*friendly name of the sample's user endpoint*/);

                // Set auto subscription to LocalOwnerPresence.
                userEndpointSettings.AutomaticPresencePublicationEnabled = true;
                _userEndpoint = _helper.CreateUserEndpoint(userEndpointSettings);

                // LocalOwnerPresence is the main class to manage the
                // sample user's presence data.
                _localOwnerPresence = _userEndpoint.LocalOwnerPresence;

                // Wire up handlers to receive presence notifications to self.
                _localOwnerPresence.PresenceNotificationReceived
                    += LocalOwnerPresence_PresenceNotificationReceived;

                // Establish the endpoint.
                _helper.EstablishUserEndpoint(_userEndpoint);

                // Publish presence categories with the new values that
                // are outlined in the sample.
                PublishPresenceCategories(true /* publish presence categories */);
                Console.WriteLine("Note, AggregateState, and ContactCard published.");

                // Wait for user to continue.
                UCMASampleHelper.PauseBeforeContinuing(
                    "Press ENTER to continue and delete the published presence.");

                // Delete presence categories, returning them to the original
                // values before the sample was run.
                PublishPresenceCategories(false /* delete presence categories */);

                // Wait for user to continue.
                UCMASampleHelper.PauseBeforeContinuing("Press ENTER to shutdown and exit.");

                // Un-wire the presence notification event handler.
                _localOwnerPresence.PresenceNotificationReceived
                    -= LocalOwnerPresence_PresenceNotificationReceived;
            }
            finally
            {
                // Shut down platform before exiting the sample.
                _helper.ShutdownPlatform();
            }
        }
Example #11
0
        private void Run()
        {
            // A helper class to take care of platform and endpoint setup and
            // cleanup. This has been abstracted from this sample to focus on
            // Call Control.
            _helper = new UCMASampleHelper();

            // Create a user endpoint, using the network credential object
            // defined above.
            _transferorEndpoint = _helper.CreateEstablishedUserEndpoint("Transferor" /*endpointFriendlyName*/);


            // Get the URI of the user to transfer the call to.
            // Prepend URI with "sip:" if not present.
            _transferTargetUri = UCMASampleHelper.PromptUser("Enter a URI of the user to transfer the call to: ", "TransferTargetUri");
            if (!(_transferTargetUri.ToLower().StartsWith("sip:") || _transferTargetUri.ToLower().StartsWith("tel:")))
            {
                _transferTargetUri = "sip:" + _transferTargetUri;
            }


            // Here, we are accepting an AudioVideo call only. If the incoming
            // call is not an AudioVideo call then it will not get raised to the
            // application. UCMA 3.0 handles this silently by having the call
            // types register for various modalities (as part of the extensibility
            // framework). The appropriate action (here, accepting the call)
            // will be handled in the handler assigned to the method call below.
            _transferorEndpoint.RegisterForIncomingCall <AudioVideoCall>(On_AudioVideoCall_Received);

            // Wait for the call to complete accept.
            Console.WriteLine(String.Empty);
            Console.WriteLine("Transferor waiting for incoming call...");
            _waitForCallAccept.WaitOne();
            Console.WriteLine("Initial call accepted by Transferor.");

            // Then transfer the call to another user, as designated above.
            _audioVideoCall.BeginTransfer(_transferTargetUri, EndTransferCall, _audioVideoCall);
            Console.WriteLine("Waiting for transfer to complete...");

            // Wait for the call to complete the transfer.
            _waitForTransferComplete.WaitOne();
            Console.WriteLine("Transfer completed.");

            UCMASampleHelper.PauseBeforeContinuing("Press ENTER to shutdown and exit.");

            // Now that the call has completed, shutdown the platform.
            _helper.ShutdownPlatform();
        }
Example #12
0
        private void Run()
        {
            // A helper class to take care of platform and endpoint setup and
            // cleanup. This has been abstracted from this sample to focus on
            // Call Control.
            _helper = new UCMASampleHelper();

            // Create a user endpoint using the network credential object
            // defined above. Again, the credentials used must be for a user
            // enabled for Microsoft Lync Server, and capable of logging
            // in from the machine that is running this code.
            _userEndpoint = _helper.CreateEstablishedUserEndpoint(
                "BasicCall Sample User" /* endpointFriendlyName */);

            // Here, we are accepting an Instant Messaging call only.
            // If the incoming call is not an Instant Messaging call (for example,
            // an AudioVideo call, or a custom Call, then it will not get
            // raised to the application. UCMA 3.0 handles this silently by having
            // the call types register for various modalities (as part of the
            // extensibility framework). The appropriate action (here, accepting the
            // call) will be handled in the handler assigned to the method call below.
            _userEndpoint.RegisterForIncomingCall <InstantMessagingCall>(On_InstantMessagingCall_Received);

            // Wait for the call to complete accept, then terminate the conversation.
            Console.WriteLine("Waiting for incoming instant messaging call...");
            _autoResetEvent.WaitOne();

            UCMASampleHelper.PauseBeforeContinuing("Press ENTER to shutdown and exit.");

            // Terminate the call, the conversation, and then unregister the
            // endpoint from the receiving an incoming call. Terminating these
            // additional objects individually is made redundant by shutting down
            // the platform right after, but in the multiple call case, this is
            // needed for object hygiene. Terminating a Conversation terminates
            // all it's associated calls, and terminating an endpoint will
            // terminate all conversations on that endpoint.
            _instantMessagingCall.BeginTerminate(EndTerminateCall, _instantMessagingCall);
            _autoResetEvent.WaitOne();
            _instantMessagingCall.Conversation.BeginTerminate(EndTerminateConversation,
                                                              _instantMessagingCall.Conversation);
            _autoResetEvent.WaitOne();
            _userEndpoint.UnregisterForIncomingCall <InstantMessagingCall>(On_InstantMessagingCall_Received);

            //Now, cleanup by shutting down the platform.
            _helper.ShutdownPlatform();
        }
Example #13
0
        /// <summary>
        /// Callback from <code>BeginShutdown</code> method on platform.
        /// </summary>
        /// <param name="result">
        /// Status of the platform shutdown operation.
        /// </param>
        private void PlatformShutdownCompleted(IAsyncResult result)
        {
            // Extract the platform that was passed in as the state argument to
            // the BeginShutdown() method.
            CollaborationPlatform platform = result.AsyncState as CollaborationPlatform;

            if (platform == null)
            {
                UCMASampleHelper.WriteErrorLine(
                    "CollaborationPlatform not passed into BeginShutdown() method.");
                UCMASampleHelper.FinishSample();
                return;
            }

            // Determine whether the shutdown operation completed
            // successfully.
            platform.EndShutdown(result);

            UCMASampleHelper.WriteLine("The platform is now shut down.");
        }
Example #14
0
        private void OnConnect(object sender, EventArgs e)
        {
            try
            {
                if (object.ReferenceEquals(null, _helper))
                {
                    // Prepare and instantiate the platform with friendly name of the sample's user endpoint
                    _helper = new UCMASampleHelper();
                    UserEndpointSettings userEndpointSettings = _helper.ReadUserSettings(((AssemblyTitleAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyTitleAttribute), false)).Title);

                    // Set auto subscription to LocalOwnerPresence.
                    userEndpointSettings.AutomaticPresencePublicationEnabled = true;

                    // Set the capabilities
                    userEndpointSettings.Presence.PreferredServiceCapabilities.ApplicationSharingSupport = CapabilitySupport.Supported;
                    userEndpointSettings.Presence.PreferredServiceCapabilities.AudioSupport            = CapabilitySupport.Supported;
                    userEndpointSettings.Presence.PreferredServiceCapabilities.InstantMessagingSupport = CapabilitySupport.Supported;
                    userEndpointSettings.Presence.PreferredServiceCapabilities.VideoSupport            = CapabilitySupport.Supported;

                    // Set the status and create endpoint
                    userEndpointSettings.Presence.UserPresenceState = PresenceState.UserAway;
                    _userEndpoint = _helper.CreateUserEndpoint(userEndpointSettings);

                    // LocalOwnerPresence is the main class to manage the
                    // sample user's presence data.
                    _localOwnerPresence = _userEndpoint.LocalOwnerPresence;

                    // Wire up handlers to receive presence notifications to self.
                    _localOwnerPresence.PresenceNotificationReceived
                        += LocalOwnerPresence_PresenceNotificationReceived;

                    // Establish the endpoint.
                    _helper.EstablishUserEndpoint(_userEndpoint);

                    // Set 'Connected' text for the first menu item
                    _trayMenu.MenuItems[0].Text    = "Connected";
                    _trayMenu.MenuItems[0].Checked = true;
                }
            }
            catch (Exception) { throw; }
        }
Example #15
0
        private void Run()
        {
            // A helper class to take care of platform and endpoint setup and
            // cleanup. This has been abstracted from this sample to focus on Call Control.
            _helper = new UCMASampleHelper();

            // Create the user endpoints from the network credential objects
            // defined above.
            _transfereeEndpoint     = _helper.CreateEstablishedUserEndpoint("Transferee" /*endpointFriendlyName*/);
            _transferorUserEndpoint = _helper.CreateEstablishedUserEndpoint(
                "Transferor" /*endpointFriendlyName*/);
            _transferTargetEndpoint = _helper.CreateEstablishedUserEndpoint(
                "Transfer Target" /*endpointFriendlyName*/);
            _transfereeURI     = _transfereeEndpoint.OwnerUri;
            _transferTargetURI = _transferTargetEndpoint.OwnerUri;

            // Register for incoming audio calls on the initial and final endpoints.
            _transferTargetEndpoint.RegisterForIncomingCall <AudioVideoCall>(On_AudioVideoCall_Received);
            _transfereeEndpoint.RegisterForIncomingCall <AudioVideoCall>(On_AudioVideoCall_Received);

            // Setup the call objects for both the call from transferring
            // to initial and transferring to final
            Conversation convInitialandTransferring = new Conversation(_transferorUserEndpoint);

            _avCallTransferringtoInitial = new AudioVideoCall(convInitialandTransferring);

            // Perform the first call, from the transferor user to the initial
            // user, without specifying any custom options.
            _avCallTransferringtoInitial.BeginEstablish(_transfereeURI, null, InitialCallEstablishCompleted,
                                                        _avCallTransferringtoInitial);

            _sampleCompleted.WaitOne();

            UCMASampleHelper.PauseBeforeContinuing("Press ENTER to shutdown and exit.");

            // And shutdown.
            _helper.ShutdownPlatform();
        }
Example #16
0
        private void Run()
        {
            // A helper class to take care of platform and endpoint setup and
            // cleanup. This has been abstracted from this sample to focus on
            // Call Control.
            _helper = new UCMASampleHelper();

            // Create a user endpoint, using the network credential object
            // defined above.
            _userEndpoint = _helper.CreateEstablishedUserEndpoint("Forwarding User" /*endpointFriendlyName*/);

            // Enter the URI of the user to forward the call to.
            _forwardUserURI = UCMASampleHelper.PromptUser(
                "Enter the URI of the user to forward the incoming call to, in the User@Host format => ",
                "ForwardingTargetURI");
            if (!(_forwardUserURI.ToLower().StartsWith("sip:") || _forwardUserURI.ToLower().StartsWith("tel:")))
            {
                _forwardUserURI = "sip:" + _forwardUserURI;
            }

            // Here, we are dealing with an Audio Video call only. If the
            // incoming call is not of the media type expected, then it will not
            // get raised to the application. UCMA 3.0 handles this silently by
            // having the call types register for various modalities (as part of
            // the extensibility framework). The appropriate action (here,
            // forwarding the call) will be handled in the handler assigned to the
            // method call below.
            _userEndpoint.RegisterForIncomingCall <AudioVideoCall>(On_AudioVideoCall_Received);

            // Wait for the call to complete forward, then shutdown the platform.
            Console.WriteLine("Waiting for incoming call...");
            _autoResetEvent.WaitOne();

            UCMASampleHelper.PauseBeforeContinuing("Press ENTER to shutdown and exit.");

            // Shut down the sample.
            _helper.ShutdownPlatform();
        }
Example #17
0
        private void Run()
        {
            // A helper class to take care of platform and endpoint setup and
            // cleanup. This has been abstracted from this sample to focus on
            // Call Control.
            _helper = new UCMASampleHelper();

            // Create a user endpoint, using the network credential object
            // defined above.
            UserEndpoint callerEndpoint = _helper.CreateEstablishedUserEndpoint("Caller" /*endpointFriendlyName*/);

            // Create a second user endpoint, using the network credential object
            // defined above.
            UserEndpoint calleeEndpoint = _helper.CreateEstablishedUserEndpoint("Callee" /*endpointFriendlyName*/);

            // Here, we are accepting an InstantMessaging call only.
            // If the incoming call is not an InstantMessaging call (for example,
            // an AudioVideo call) then it will not get raised to the application.
            // UCMA 3.0 handles this silently by having the call types register
            // for various modalities (as part of the extensibility framework).
            // The appropriate action (here, accepting the call) will be handled
            // in the handler assigned to the method call below.
            calleeEndpoint.RegisterForIncomingCall <InstantMessagingCall>
                (On_InstantMessagingCall_Received_ByCallee);

            // Setup the call and conversation objects for the initial call (IM)
            // and place the call (synchronously).
            Conversation         callerConversation         = new Conversation(callerEndpoint);
            InstantMessagingCall callerInstantMessagingCall = new InstantMessagingCall(callerConversation);

            callerInstantMessagingCall.BeginEstablish(calleeEndpoint.OwnerUri, null, EndCallerCallEstablish,
                                                      callerInstantMessagingCall);

            // Force synchronization to ensure that the call is now complete.
            _waitForCallAcceptByCallee.WaitOne();
            _waitForCallerCallEstablish.WaitOne();

            // Now that the call is established, we can begin the escalation.
            // First, we bind the conference state changed event handler, largely
            // for logging reasons.
            callerConversation.ConferenceSession.StateChanged += new
                                                                 EventHandler <StateChangedEventArgs <ConferenceSessionState> >(ConferenceSession_StateChanged);

            Console.WriteLine("");
            Console.WriteLine(" Beginning conference creation and escalation...");
            Console.WriteLine("");

            // Next, the initiator of the escalation creates an ad-hoc conference
            // (using the current modalities present in the conversation) by calling
            // ConferenceSession.BeginJoin on a conversation, without providing
            // a conference URI. This prepares the calls for actual escalation by
            // binding the appropriate conference multipoint Control Unit (MCU)
            // sessions. When EndJoinConference is called, it will kick off the
            // subsequent escalation. As part of the escalation, the remote party
            // will receive an escalation request, via the event on the far end
            // conversation, EscalateToConferenceRequested. Also, the existing
            // calls will be shifted to the MCUs.
            callerConversation.ConferenceSession.BeginJoin(default(ConferenceJoinOptions),
                                                           EndCallerJoinConference, callerConversation.ConferenceSession);

            //Wait for both sides to fully escalate to the new conference.
            _waitForCallerConferenceEscalation.WaitOne();
            _waitForCalleeConferenceEscalation.WaitOne();

            Console.WriteLine("");
            Console.WriteLine(" Beginning conference command and control...");
            Console.WriteLine("");

            // Promote a participant to leader; Leaders can lock and unlock the
            // conference, as well as possessing the ability to eject and control
            // other participants, and mute participants (in an Audio conference).
            // For purposes of the demonstration, choose an arbitrary conference
            // participant here, the first.

            ConversationParticipant target = null;

            if (callerConversation.RemoteParticipants.Count >= 1)
            {
                target = callerConversation.RemoteParticipants[0];
            }
            else
            {
                // TODO (Left to the reader): Add error handling code.
            }

            Console.WriteLine("User " + target.UserAtHost + " is currently an " + target.Role + ".");

            // Note: This is the naive synch implementation, and is not generally
            // suitable for production code. It is only used here for brevity.
            callerConversation.ConferenceSession.BeginModifyRole(target, ConferencingRole.Leader,
                                                                 EndModifyRole, callerConversation.ConferenceSession);
            _waitForRoleModification.WaitOne();
            Console.WriteLine("User " + target.UserAtHost + " is now a " + target.Role + ".");

            Console.WriteLine("The conference access level is currently " +
                              callerConversation.ConferenceSession.AccessLevel + ".");
            // Locking the conference prevents new users from joining the
            // conference, unless explicitly called into the conference through
            // the dialout API.
            callerConversation.ConferenceSession.BeginLockConference(EndLockConference,
                                                                     callerConversation.ConferenceSession);
            _waitForConferenceLock.WaitOne();
            Console.WriteLine("The conference accesslevel is now " +
                              callerConversation.ConferenceSession.AccessLevel + ".");

            // Now, eject the participant, and then shut down the platform.

            Console.WriteLine("The conference currently has " +
                              callerConversation.ConferenceSession.GetRemoteParticipantEndpoints().Count + " attendees.");
            // Ejection can only be performed by leaders of the conference.
            callerConversation.ConferenceSession.BeginEject(target, EndEject, callerConversation.ConferenceSession);
            _waitForParticipantEject.WaitOne();
            Console.WriteLine("The conference now has " +
                              callerConversation.ConferenceSession.GetRemoteParticipantEndpoints().Count + " attendees.");

            _helper.ShutdownPlatform();

            Console.ReadLine();
        }
Example #18
0
        private void Run()
        {
            // Prepare and instantiate the platform.
            _helper = new UCMASampleHelper();
            UserEndpointSettings userEndpointSettings = _helper.ReadUserSettings(
                "PresenceContainerMembership Sample subscribee" /*endpointFriendlyName*/);

            // Set auto subscription to LocalOwnerPresence
            userEndpointSettings.AutomaticPresencePublicationEnabled = true;
            _subscribee = _helper.CreateUserEndpoint(userEndpointSettings);

            // Establish the endpoint
            _helper.EstablishUserEndpoint(_subscribee);

            _subscriberUri = UCMASampleHelper.PromptUser("Please Enter the subscriber's Uri in the form "
                                                         + "sip:User@Hostuser. Please ensure that the uri is in the same domain as "
                                                         + _subscriberUriKey,
                                                         _subscriberUriKey);

            if (!_subscriberUri.StartsWith(_sipPrefix, StringComparison.OrdinalIgnoreCase))
            {
                _subscriberUri = _sipPrefix + _subscriberUri;
            }

            Console.WriteLine("{0} will block {1}, then unblock him. Please login to Microsoft Lync as {1}.",
                              _subscribee.OwnerUri,
                              _subscriberUri);

            UCMASampleHelper.PauseBeforeContinuing("Press ENTER to continue.");

            // First publish MachineStateOnline using default grammar. UCMA SDK
            // will publish to the correct containers.
            _subscribee.LocalOwnerPresence.BeginPublishPresence(
                new PresenceCategory[] { PresenceState.EndpointOnline, PresenceState.UserAvailable },
                HandleEndPublishPresence,
                null);

            Console.WriteLine("{0} has published 'Available'. ", _subscribee.OwnerUri);
            Console.WriteLine("Using Microsoft Lync, please subscribe to {0} when logged in as {1}. ",
                              _subscribee.OwnerUri,
                              _subscriberUri);
            Console.WriteLine("You should see that {0} is online and Available. ", _subscribee.OwnerUri);

            UCMASampleHelper.PauseBeforeContinuing("Press ENTER to continue.");

            ContainerUpdateOperation operation = new ContainerUpdateOperation(_blockedContainer);

            operation.AddUri(_subscriberUri);
            _subscribee.LocalOwnerPresence.BeginUpdateContainerMembership(
                new ContainerUpdateOperation[] { operation },
                HandleEndUpdateContainerMembership, null);

            Console.WriteLine("{0} has added {1} to container {2} - the blocked container.",
                              _subscribee.OwnerUri,
                              _subscriberUri,
                              _blockedContainer);
            Console.WriteLine("Microsoft Lync should display 'Offline' for user {0} now. ",
                              _subscribee.OwnerUri);

            UCMASampleHelper.PauseBeforeContinuing("Press ENTER to continue.");

            operation = new ContainerUpdateOperation(_blockedContainer);
            operation.DeleteUri(_subscriberUri);
            _subscribee.LocalOwnerPresence.BeginUpdateContainerMembership(
                new ContainerUpdateOperation[] { operation },
                HandleEndUpdateContainerMembership, null);

            Console.WriteLine("{0} has removed {1} from the blocked container. Microsoft Lync should display "
                              + "'online' for user {0} now. ",
                              _subscribee.OwnerUri,
                              _subscriberUri);
            Console.WriteLine(" Sample complete. ");

            UCMASampleHelper.PauseBeforeContinuing("Press ENTER to shutdown and exit.");

            // Shutdown Platform
            _helper.ShutdownPlatform();
        }
Example #19
0
        /// <summary>
        /// Retrieves the application configuration and begins running the
        /// sample.
        /// </summary>
        public void Run()
        {
            try
            {
                _helper      = new UCMASampleHelper();
                _appEndpoint = _helper.CreateApplicationEndpoint("TrustedConferenceParticipant");

                if (_appEndpoint.State == LocalEndpointState.Established)
                {
                    Console.WriteLine("The Application Endpoint owned by URI {0}, is now established and "
                                      + "registered.", _appEndpoint.OwnerUri);
                }
                else
                {
                    Console.WriteLine("The Application endpoint is not currently in the Established state, "
                                      + "exiting...");
                    return;
                }

                // Impersonate a user and create an ad-hoc conference.
                ImpersonateAndCreateConference();

                // Have the application endpoint join the ad-hoc conference as a
                // trusted participant.
                JoinConferenceAsTrustedParticipant();

                // Start monitoring the AVMCU session for attendance changes.
                StartAVMCUSessionAttendanceMonitoring();

                int invitationCounter = 1;
                while (true)
                {
                    // Retrieve the uri of the user to be invited from the
                    // config file.
                    string prompt = "Please enter the uri of the user who should be sent an invitation to the"
                                    + "conference (Enter to Skip) => ";

                    string invitationTargetUri = UCMASampleHelper.PromptUser(prompt, "InvitationTargetURI"
                                                                             + invitationCounter);
                    if (!string.IsNullOrEmpty(invitationTargetUri))
                    {
                        InviteUserToConference(invitationTargetUri);
                        invitationCounter++;

                        if (_invitedParticipantAccepted)
                        {
                            // Wait for the invited participant to have the
                            // Trusted User establish an Av call and update the
                            // audio routes to communicate with them. This is
                            // purely so the logging for each invited user
                            // occurs in sequence for this sample.
                            Console.WriteLine("Waiting for the AudioRoute update on the Av Call for the new "
                                              + "participant to complete.");
                            _audioRouteUpdateForNewParticipantCallCompleted.WaitOne();
                        }
                    }
                    else
                    {
                        Console.WriteLine("No invitation uri provided, skipping conference invitation.");
                        break;
                    }
                }

                Console.WriteLine(RetrieveConversationParticipantsProperties(
                                      _impersonatingAvCall.Conversation));

                Console.Write("\n\n********************\n");
                Console.WriteLine("Press enter to exit.");
                Console.WriteLine("********************\n\n");
                Console.ReadLine();
            }
            finally
            {
                //Terminate the platform which would in turn terminate any
                // endpoints.
                Console.WriteLine("Shutting down the platform.");
                _helper.ShutdownPlatform();
            }
        }
Example #20
0
        /// <summary>
        /// Retrieves the application configuration and runs the sample.
        /// </summary>
        private void Run()
        {
            // Prepare and instantiate the platform.
            _helper       = new UCMASampleHelper();
            _userEndpoint = _helper.CreateEstablishedUserEndpoint(
                "SubscribePresence Sample User" /*endpointFriendlyName*/);

            // Get the URI of the remote user whose presence to subscribe to.
            _remoteUserUri = "sip:" + UCMASampleHelper.PromptUser(
                "Please enter the URI, in the format user@host, of the user whose Presence to subscribe to "
                + "=> ", "RemoteUserURI");

            // RemotePresenceView is the class to be used to subscribe to
            // another entity's presence.
            _remotePresenceView = new RemotePresenceView(_userEndpoint);

            // Wire up event handlers to receive the incoming notifications of
            // the remote user being subscribed to.
            _remotePresenceView.SubscriptionStateChanged += new EventHandler <
                RemoteSubscriptionStateChangedEventArgs>(
                RemotePresence_SubscriptionStateNotificationReceived);
            _remotePresenceView.PresenceNotificationReceived += new EventHandler <
                RemotePresentitiesNotificationEventArgs>(RemotePresence_PresenceNotificationReceived);

            try
            {
                // Subscribe to target user.
                _target = new RemotePresentitySubscriptionTarget(_remoteUserUri);
                _remotePresenceView.StartSubscribingToPresentities(
                    new RemotePresentitySubscriptionTarget[] { _target });

                // Subscribe to ContactGroupServices.
                // This is done so that the user can add/delete groups and
                // add/delete contacts, among other operations.
                _userEndpoint.ContactGroupServices.NotificationReceived += new EventHandler
                                                                           <Microsoft.Rtc.Collaboration.ContactsGroups.ContactGroupNotificationEventArgs>(
                    ContactGroupServices_NotificationReceived);
                _userEndpoint.ContactGroupServices.SubscriptionStateChange += new EventHandler
                                                                              <PresenceSubscriptionStateChangedEventArgs>(ContactGroupServices_SubscriptionStateChange);
                _userEndpoint.ContactGroupServices.BeginSubscribe(EndSubscribeCompleted,
                                                                  _userEndpoint.ContactGroupServices);

                // Wait for subscription to ContactsGroups to be completed.
                _waitForSubscribedToContactsGroupsCompleted.WaitOne();
                Console.WriteLine("Subscription to ContactsGroups completed.");

                // Create a new group.
                _userEndpoint.ContactGroupServices.BeginAddGroup(_groupName,
                                                                 null /* group data */,
                                                                 EndAddGroupCompleted,
                                                                 _userEndpoint.ContactGroupServices);

                // Wait for group to be created.
                _waitForGroupIdSet.WaitOne();

                // Add the remote user to the newly created group.
                ContactsGroups.ContactAddOptions addOptions
                    = new Microsoft.Rtc.Collaboration.ContactsGroups.ContactAddOptions();
                addOptions.GroupIds.Add(_groupId);
                _userEndpoint.ContactGroupServices.BeginAddContact(_remoteUserUri,
                                                                   addOptions,
                                                                   EndAddContactCompleted,
                                                                   _userEndpoint.ContactGroupServices);

                UCMASampleHelper.PauseBeforeContinuing("You are now subscribed to the presence of the remote "
                                                       + "user. \nPlease toggle the user state of the remote user to get the appropriate "
                                                       + "notifications. \nPress ENTER to delete the contact, delete the group, and unsubscribe"
                                                       + "to the presence of the remote user.");

                // Remove contact from group, and delete group.
                _userEndpoint.ContactGroupServices.BeginDeleteContact(_remoteUserUri,
                                                                      EndDeleteContactCompleted,
                                                                      _userEndpoint.ContactGroupServices);
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine("Could not subscribe to the presence of the remote user: "******"\n\n********************");
            Console.WriteLine("Press ENTER to shutdown and exit.");
            Console.WriteLine("********************\n\n");
            Console.ReadLine();


            // Shutdown Platform
            _helper.ShutdownPlatform();
        }
Example #21
0
        /// <summary>
        /// Callback from <code>BeginStartup</code> method on platform.
        /// </summary>
        /// <param name="result">
        /// Status of the platform startup operation.
        /// </param>
        private void PlatformStartupCompleted(IAsyncResult result)
        {
            // Extract the platform that was passed in as the state argument to
            // the BeginStartup() method.
            CollaborationPlatform platform = result.AsyncState as CollaborationPlatform;

            if (platform == null)
            {
                UCMASampleHelper.WriteErrorLine("CollaborationPlatform not passed into BeginStartup() method.");
                UCMASampleHelper.FinishSample();
                return;
            }

            try
            {
                // Determine whether the startup operation completed
                // successfully.
                platform.EndStartup(result);

                UCMASampleHelper.WriteLine("Platform has been started.");
            }
            catch (TlsFailureException tlsFailureException)
            {
                // TlsFailureException will be thrown if the certificate used to
                // startup the platform is invalid or otherwise unusable.
                // TODO (Left to the reader): Error handling code to either
                // retry the platform startup operation with a different
                // certificate, log the error for debugging, or gracefully exit
                // the program.
                UCMASampleHelper.WriteException(tlsFailureException);
                UCMASampleHelper.FinishSample();
            }
            catch (ConnectionFailureException connectionFailureException)
            {
                // ConnectionFailureException will be thrown when the platform
                // could not listen on any of the configured IP/port
                // combinations.
                // TODO (Left to the reader): Error handling code to notify user
                // the configured IP address cannot be used or some other
                // process is already using the port, log the error for
                // debugging, or gracefully exit the program.
                UCMASampleHelper.WriteException(connectionFailureException);
                UCMASampleHelper.FinishSample();
            }
            catch (RealTimeException realTimeException)
            {
                // RealTimeException will be thrown when the platform startup
                // operation failed for some other reason.
                // TODO (Left to the reader): Error handling code to notify user
                // the configured IP address cannot be used or some other
                // process is already using the port, log the error for
                // debugging, or gracefully exit the program.
                UCMASampleHelper.WriteException(realTimeException);
                UCMASampleHelper.FinishSample();
            }
            try
            {
                // Create the ApplicationEndpointSettings.
                _endpointSettings = new ApplicationEndpointSettings(_endpointOwnerURI,
                                                                    _registrarFQDN,
                                                                    _registrarPort);

                // Create the ApplicationEndpoint from the
                // ApplicationEndpointSettings and bind it to the platform.
                _endpoint = new ApplicationEndpoint(platform, _endpointSettings);

                // Bind an event handler to notify when the endpoint changes
                // state.
                _endpoint.StateChanged += new EventHandler <LocalEndpointStateChangedEventArgs>(
                    _endpoint_StateChanged);

                // Establish the endpoint so that it can receive incoming calls
                // and conference invitations. EndEndpointEstablish()  will be
                // called when the endpoint finishes establishment.
                _endpoint.BeginEstablish(EndpointEstablishmentCompleted, _endpoint);

                UCMASampleHelper.WriteLine("Endpoint has been established.");
            }
            catch (ArgumentNullException argumentNullException)
            {
                // ArgumentNullException will be thrown if the parameters used to
                // construct ApplicationEndpointSettings or ApplicationEndpoint
                // are null.
                // TODO (Left to the reader): Error handling code to either
                // retry creating the endpoint with non-null parameters, log the
                // error for debugging or gracefully exit the program.
                UCMASampleHelper.WriteException(argumentNullException);
                UCMASampleHelper.FinishSample();
            }
            catch (ArgumentException argumentException)
            {
                // ArgumentException will be thrown if the parameters used to
                // construct ApplicationEndpointSettings or ApplicationEndpoint
                // are invalid.
                // TODO (Left to the reader): Error handling code to either
                // retry creating the endpoint with corrected parameters, log
                // the error for debugging or gracefully exit the program.
                UCMASampleHelper.WriteException(argumentException);
                UCMASampleHelper.FinishSample();
            }
            catch (InvalidOperationException invalidOperationException)
            {
                // InvalidOperationException will be thrown if the platform is
                // already shutdown, an endpoint with the same SIP URI already
                // exists, or the endpoint has already been established or
                // terminated.
                // TODO (Left to the reader): Error handling code to log the
                // error for debugging.
                UCMASampleHelper.WriteException(invalidOperationException);
                UCMASampleHelper.FinishSample();
            }
        }
Example #22
0
        /// <summary>
        /// Retrieves the application configuration and begins starting up the
        /// platform.
        /// </summary>
        private void Run()
        {
            // Prompt for the settings necessary to initialize the
            // CollaborationPlatform and the ApplicationEndpoint if they are
            // not declared in App.config.
            // TODO (Left to the reader): Input sanitization on the
            // collected parameters.
            _applicationHostFQDN = UCMASampleHelper.PromptUser(
                "Please enter the FQDN assigned to this computer in the trusted application pool => ",
                "TrustedAppComputerFQDN");
            if (string.IsNullOrEmpty(_applicationHostFQDN))
            {
                UCMASampleHelper.WriteErrorLine(
                    "No FQDN was found in App.config or input by the user.");
            }
            string inputPort = UCMASampleHelper.PromptUser(
                "Please enter the port assigned to this trusted application => ",
                "TrustedAppPort");

            if (!int.TryParse(inputPort, out _applicationHostPort))
            {
                UCMASampleHelper.WriteErrorLine(
                    "Port could not be parsed from App.config or from input by the user.");
            }
            _computerGRUU = UCMASampleHelper.PromptUser(
                "Please enter the GRUU assigned to this computer for this trusted application => ",
                "TrustedAppComputerGRUU");
            if (string.IsNullOrEmpty(_computerGRUU))
            {
                UCMASampleHelper.WriteErrorLine("No GRUU was found in App.config or input by the user.");
            }
            _certificateFriendlyName = UCMASampleHelper.PromptUser(
                "Please enter the friendly name of the certificate identifying this computer => ",
                "CertificateFriendlyName");
            if (string.IsNullOrEmpty(_certificateFriendlyName))
            {
                UCMASampleHelper.WriteErrorLine(
                    "No certificate friendly name was found in App.config or input by the user.");
            }
            _certificate = UCMASampleHelper.GetLocalCertificate(_certificateFriendlyName);
            if (_certificate == null)
            {
                UCMASampleHelper.WriteErrorLine("Certificate with friendly name '" + _certificateFriendlyName
                                                + "' could not be found in computer account Personal certificate store.");
            }
            _endpointOwnerURI = UCMASampleHelper.PromptUser(
                "Please enter the SIP URI assigned to this trusted application endpoint => ",
                "TrustedAppEpOwnerURI");
            if (string.IsNullOrEmpty(_endpointOwnerURI))
            {
                UCMASampleHelper.WriteErrorLine("No SIP URI was found in App.config or input by the user.");
            }
            _registrarFQDN = UCMASampleHelper.PromptUser(
                "Please enter the FQDN of the registrar pool  to which this endpoint is assigned => ",
                "RegistrarFQDN");
            if (string.IsNullOrEmpty(_registrarFQDN))
            {
                UCMASampleHelper.WriteErrorLine(
                    "No registrar pool FQDN was found in App.config or input by the user.");
            }
            string inputRegistrarPort = UCMASampleHelper.PromptUser(
                "Please enter the port used by the registrar pool to which this endpoint is assigned => ",
                "RegistrarPort");

            if (!int.TryParse(inputRegistrarPort, out _registrarPort))
            {
                UCMASampleHelper.WriteErrorLine(
                    "Registrar port could not be parsed from App.config or from input by the user.");
            }

            try
            {
                // Create the CollaborationPlatform using the
                // ServerPlatformSettings.
                _platformSettings = new ServerPlatformSettings(_applicationUserAgent,
                                                               _applicationHostFQDN,
                                                               _applicationHostPort,
                                                               _computerGRUU,
                                                               _certificate);
                _platform = new CollaborationPlatform(_platformSettings);

                // Initialize and startup the platform. EndPlatformStartup()
                // will be called when the platform finishes starting up.
                UCMASampleHelper.WriteLine("Starting platform...");
                _platform.BeginStartup(PlatformStartupCompleted, _platform);
            }
            catch (ArgumentNullException argumentNullException)
            {
                // ArgumentNullException will be thrown if the parameters used
                // to construct ServerPlatformSettings or CollaborationPlatform
                // are null.
                // TODO (Left to the reader): Error handling code to either
                // retry creating the platform with non-null parameters, log the
                // error for debugging or gracefully exit the program.
                UCMASampleHelper.WriteException(argumentNullException);
                UCMASampleHelper.FinishSample();
            }
            catch (ArgumentOutOfRangeException argumentOutOfRangeException)
            {
                // ArgumentOutOfRangeException will be thrown if the port
                // parameter used to construct ServerPlatformSettings is greater
                // than 65536 or less than 0.
                // TODO (Left to the reader): Error handling code to either
                // retry creating the platform with a valid port, log the error
                // for debugging or gracefully exit the program.
                UCMASampleHelper.WriteException(argumentOutOfRangeException);
                UCMASampleHelper.FinishSample();
            }
            catch (ArgumentException argumentException)
            {
                // ArgumentException will be thrown if the parameters used to
                // construct ServerPlatformSettings or CollaborationPlatform are
                // invalid.
                // TODO (Left to the reader): Error handling code to either
                // retry creating the platform with corrected parameters, log
                // the error for debugging or gracefully exit the program.
                UCMASampleHelper.WriteException(argumentException);
                UCMASampleHelper.FinishSample();
            }
            catch (TlsFailureException tlsFailureException)
            {
                // TlsFailureException will be thrown if the certificate used to
                // construct CollaborationPlatform is invalid or otherwise
                // unusable.
                // TODO (Left to the reader): Error handling code to either
                // retry creating the platform with a valid certificate, log the
                // error for debugging or gracefully exit the program.
                UCMASampleHelper.WriteException(tlsFailureException);
                UCMASampleHelper.FinishSample();
            }
            catch (CryptographicException cryptographicException)
            {
                // CryptographicException will be thrown if the certificate used
                // to construct ServerPlatformSettings is invalid.
                // TODO (Left to the reader): Error handling code to either
                // retry creating the platform with a valid certificate, log the
                // error for debugging or gracefully exit the program.
                UCMASampleHelper.WriteException(cryptographicException);
                UCMASampleHelper.FinishSample();
            }
            catch (InvalidOperationException invalidOperationException)
            {
                // InvalidOperationException will be thrown if the platform has
                // already been started or shutdown.
                // TODO (Left to the reader): Error handling code to log the
                // error for debugging.
                UCMASampleHelper.WriteException(invalidOperationException);
                UCMASampleHelper.FinishSample();
            }
            finally
            {
                // Wait for the sample to finish before shutting down the
                // platform and returning from the main thread.
                UCMASampleHelper.WaitForSampleFinish();

                // It is possible the platform was never created due to issues
                // collecting configuration parameters.
                if (_platform != null)
                {
                    // Shutdown the platform, thereby terminating any attached
                    // endpoints.
                    UCMASampleHelper.WriteLine("Shutting down the platform...");
                    _platform.BeginShutdown(PlatformShutdownCompleted, _platform);
                }
            }
        }
Example #23
0
        // Publish note, state, contact card presence categories
        private void PublishPresenceCategories(bool publishFlag)
        {
            try
            {
                if (publishFlag == true)
                {
                    // The CustomPresenceCategory class enables creation of a
                    // category using XML. This allows precise crafting of a
                    // category, but it is also possible to create a category
                    // in other, more simple ways, shown below.
                    _note = new CustomPresenceCategory("note", String.Format(_noteXml, _noteValue));

                    // The PresenceState class has several static properties
                    // and methods which will provide standard states such as
                    // online, busy, and on-the-phone, for example.
                    _userState = PresenceState.UserBusy;

                    // It is possible to create and publish state with a
                    // custom availablity string, shown below. "In a call" will
                    // be shown in Microsoft Lync.
                    LocalizedString localizedCallString = new LocalizedString(
                        "In a call" /* The string to be displayed. */);

                    // Create a PresenceActivity indicating the
                    // "In a call" state.
                    PresenceActivity inACall = new PresenceActivity(
                        localizedCallString);

                    // Set the Availability of the "In a call" state to Busy.
                    inACall.SetAvailabilityRange((int)PresenceAvailability.Busy,
                                                 (int)PresenceAvailability.IdleBusy);

                    // Microsoft Lync will also show the Busy presence icon.
                    _phoneState = new PresenceState(
                        (int)PresenceAvailability.Busy,
                        inACall,
                        PhoneCallType.Voip,
                        "phone uri");

                    // Machine or Endpoint states must always be published to
                    // indicate the endpoint is actually online, otherwise it is
                    // assumed the endpoint is offline, and no presence
                    // published from that endpoint will be displayed.
                    _machineState = PresenceState.EndpointOnline;

                    // It is also possible to create presence categories such
                    // as ContactCard, Note, PresenceState, and Services with
                    // their constructors.
                    // Here we create a ContactCard and change the title.
                    _contactCard = new ContactCard(3);
                    LocalizedString localizedTitleString = new LocalizedString(
                        "The Boss" /* The title string to be displayed. */);
                    _contactCard.JobTitle = localizedTitleString.Value;

                    // Publish a photo
                    // If the supplied value for photo is null or empty, then set value of IsAllowedToShowPhoto to false
                    _contactCard.IsAllowedToShowPhoto = true;
                    string photoUri = UCMASampleHelper.PromptUser("Please enter a Photo Uri in the form of http://mysite/photo1.jpg", "PhotoURI1");
                    if (String.IsNullOrEmpty(photoUri))
                    {
                        photoUri = null;
                        _contactCard.IsAllowedToShowPhoto = false;
                    }
                    _contactCard.PhotoUri = photoUri;

                    // Publish all presence categories with new values.
                    _localOwnerPresence.BeginPublishPresence(
                        new PresenceCategory[]
                    {
                        _userState,
                        _phoneState,
                        _machineState,
                        _note,
                        _contactCard
                    },
                        PublishPresenceCompleted, /* async callback when publishing operation completes. */
                        publishFlag /* value TRUE indicates that presence to be published with new values. */);
                }
                else
                {
                    // Delete all presence categories.
                    _localOwnerPresence.BeginDeletePresence(
                        new PresenceCategory[]
                    {
                        _userState,
                        _phoneState,
                        _machineState,
                        _note,
                        _contactCard
                    },
                        PublishPresenceCompleted,
                        publishFlag /* value FALSE indicates that presence reverted to original values. */);
                }
            }
            catch (PublishSubscribeException pse)
            {
                // PublishSubscribeException is thrown when there were
                // exceptions during this presence operation such as badly
                // formed sip request, duplicate publications in the same
                // request etc.
                // TODO (Left to the reader): Include exception handling code
                // here.
                Console.WriteLine(pse.ToString());
            }
            catch (RealTimeException rte)
            {
                // RealTimeException is thrown when SIP Transport, SIP
                // Authentication, and credential-related errors are
                // encountered.
                // TODO (Left to the reader): Include exception handling code
                // here.
                Console.WriteLine(rte.ToString());
            }
        }
Example #24
0
        private void Run()
        {
            // A helper class to take care of platform and endpoint setup and
            // cleanup. This has been abstracted from this sample to focus on
            // Call Control.
            _helper = new UCMASampleHelper();

            // Create a user endpoint, using the network credential object
            // defined above.
            _callerEndpoint = _helper.CreateEstablishedUserEndpoint(
                "Conference Leader" /* friendly name for conference leader endpoint */);

            // Create a second user endpoint, using the network credential object
            // defined above.
            _calleeEndpoint = _helper.CreateEstablishedUserEndpoint(
                "Conference Attendee" /* friendly name for conference attendee endpoint */);

            // Get the URI for the user logged onto Microsoft Lync
            String _ocUserURI = "sip:" + UCMASampleHelper.PromptUser(
                "Enter the URI for the user logged onto Microsoft Lync, in the User@Host format => ",
                "RemoteUserURI" /* key to specify remote user's URI in app.config */);

            // One of the endpoints schedules the conference in advance. At
            // schedule time, all the conference settings are set.

            // The base conference settings object, used to set the policies for the conference.
            ConferenceScheduleInformation conferenceScheduleInformation = new ConferenceScheduleInformation();

            // An open meeting (participants can join who are not on the list),
            // but requiring authentication (no anonymous users allowed.)
            conferenceScheduleInformation.AccessLevel = ConferenceAccessLevel.SameEnterprise;
            // The below flag determines whether or not the passcode is optional
            // for users joining the conference.
            conferenceScheduleInformation.IsPasscodeOptional = true;
            conferenceScheduleInformation.Passcode           = "1357924680";
            // The verbose description of the conference
            conferenceScheduleInformation.Description = "Interesting Description";
            // The below field indicates the date and time after which the conference can be deleted.
            conferenceScheduleInformation.ExpiryTime = System.DateTime.Now.AddHours(5);

            // These two lines assign a set of modalities (here, only
            // InstantMessage) from the available MCUs to the conference. Custom
            // modalities (and their corresponding MCUs) may be added at this
            // time as part of the extensibility model.
            ConferenceMcuInformation instantMessageMCU = new ConferenceMcuInformation(McuType.InstantMessaging);

            conferenceScheduleInformation.Mcus.Add(instantMessageMCU);

            // Now that the setup object is complete, schedule the conference
            // using the conference services off of Endpoint. Note: the conference
            // organizer is considered a leader of the conference by default.
            _callerEndpoint.ConferenceServices.BeginScheduleConference(conferenceScheduleInformation,
                                                                       EndScheduleConference, _callerEndpoint.ConferenceServices);

            // Wait for the scheduling to complete.
            _waitForConferenceScheduling.WaitOne();

            // Now that the conference is scheduled, it's time to join it. As we
            // already have a reference to the conference object populated from
            // the EndScheduleConference call, we do not need to get the
            // conference first. Initialize a conversation off of the endpoint,
            // and join the conference from the uri provided above.
            Conversation callerConversation = new Conversation(_callerEndpoint);

            callerConversation.ConferenceSession.StateChanged += new
                                                                 EventHandler <StateChangedEventArgs <ConferenceSessionState> >(ConferenceSession_StateChanged);

            // Join and wait, again forcing synchronization.
            callerConversation.ConferenceSession.BeginJoin(_conference.ConferenceUri, null /*joinOptions*/,
                                                           EndJoinConference, callerConversation.ConferenceSession);
            _waitForConferenceJoin.WaitOne();

            // Placing the calls on the conference-connected conversation
            // connects to the respective MCUs. These calls may then be used to
            // communicate with the conference/MCUs.
            InstantMessagingCall instantMessagingCall = new InstantMessagingCall(callerConversation);

            // Hooking up event handlers and then placing the call.
            instantMessagingCall.InstantMessagingFlowConfigurationRequested +=
                this.instantMessagingCall_InstantMessagingFlowConfigurationRequested;
            instantMessagingCall.StateChanged += this._call_StateChanged;
            instantMessagingCall.BeginEstablish(EndCallEstablish, instantMessagingCall);

            //Synchronize to ensure that call has completed.
            _waitForCallEstablish.WaitOne();

            //send conf invite
            ConferenceInvitationDeliverOptions deliverOptions = new ConferenceInvitationDeliverOptions();

            deliverOptions.ToastMessage = new ToastMessage("Welcome to my conference");

            ConferenceInvitation invitation = new ConferenceInvitation(callerConversation);

            invitation.BeginDeliver(_ocUserURI, deliverOptions, EndDeliverInvitation, invitation);

            // Synchronize to ensure that invitation is complete
            _waitForConversationInviteRemoteParticipants.WaitOne();

            //And from the other endpoint's perspective:
            //Initialize a conversation off of the endpoint, and join the
            //conference from the uri provided above.
            Conversation calleeConversation = new Conversation(_calleeEndpoint);

            calleeConversation.ConferenceSession.StateChanged += new
                                                                 EventHandler <StateChangedEventArgs <ConferenceSessionState> >(ConferenceSession_StateChanged);

            // Join and wait, again forcing synchronization.
            calleeConversation.ConferenceSession.BeginJoin(_conference.ConferenceUri, null /*joinOptions*/,
                                                           EndJoinConference, calleeConversation.ConferenceSession);
            _waitForConferenceJoin.WaitOne();

            // Placing the calls on the conference-connected conversation
            // connects to the respective MCUs. These calls may then be used to
            //communicate with the conference/MCUs.
            InstantMessagingCall instantMessagingCall2 = new InstantMessagingCall(calleeConversation);

            //Hooking up event handlers and then placing the call.
            instantMessagingCall2.InstantMessagingFlowConfigurationRequested +=
                this.instantMessagingCall2_InstantMessagingFlowConfigurationRequested;
            instantMessagingCall2.StateChanged += this._call_StateChanged;
            instantMessagingCall2.BeginEstablish(EndCallEstablish, instantMessagingCall2);

            //Synchronize to ensure that call has completed.
            _waitForCallEstablish.WaitOne();

            //Synchronize to ensure that all messages are sent and received
            _waitForMessageReceived.WaitOne();

            //Wait for shutdown initiated by user
            _waitForShutdown.WaitOne();

            UCMASampleHelper.PauseBeforeContinuing("Press ENTER to shutdown and exit.");
        }
Example #25
0
        /// <summary>
        /// Retrieves the application configuration and begins running the
        /// sample.
        /// </summary>
        private void Run()
        {
            // Prepare and instantiate the platform and an endpoint.
            _helper       = new UCMASampleHelper();
            _userEndpoint = _helper.CreateEstablishedUserEndpoint(
                "SubscribePresenceView Sample User" /*endpointFriendlyName*/);

            // Get the Uri of the remote user to subscribe to.
            _remoteUserUri = "sip:" +
                             UCMASampleHelper.PromptUser(
                "Please enter the URI, in the format User@Host, of the user to subscribe to => ",
                "RemoteUserURI");

            Console.WriteLine("\nChanging PresenceSubscriptionCategory Filter to only include ContactCard " +
                              "and PresenceState");
            // Set category filter. This is a global filter for all persistent
            // subscriptions and can only be changed before any subscriptions
            // are active.
            // BUGBUG: error CS0618: 'Microsoft.Rtc.Collaboration.LocalEndpoint.RemotePresence' is obsolete: 'This property will be removed from future Versions. Please see RemotePresenceView and PresenceServices instead.'
            // _userEndpoint.RemotePresence.PresenceSubscriptionCategories =
            //    new string[] { PresenceCategoryNames.ContactCard, PresenceCategoryNames.State };

            // RemotePresencView objects can be used to group subscriptions.
            // When a RemotePresenceView is created, it is created with the
            // specified RemotePresenceViewSettings and associated with the
            // specified LocalEndpoint. The views can then be accessed via the
            // LocalEndpoint setting: RemotePresenceViews.

            // RemotePresenceView.ApplicationContext can be used to pass or
            // store information related to the view (seen below).

            // Create a RemotePresenceView with a persistent subscription mode.
            // This type of view can represent a contact list, for example.
            // Note: The Default SubscriptionMode will start a subscription as
            // Persistent and downgrade to Polling if an error occurs.
            var persistentSettings = new RemotePresenceViewSettings();

            persistentSettings.SubscriptionMode = RemotePresenceViewSubscriptionMode.Default;
            _persistentView = new RemotePresenceView(_userEndpoint, persistentSettings);
            _persistentView.ApplicationContext = "Persistent View";

            // Wire up event handlers for the view
            this.WireUpHandlersForView(_persistentView);

            // Create a RemotePresenceView with a polling subscription mode
            // This type of view can represent a list of people
            // on the To: line of an e-mail, for example.
            var pollingSettings = new RemotePresenceViewSettings();

            pollingSettings.SubscriptionMode = RemotePresenceViewSubscriptionMode.Polling;
            // The line below is not necessary; PollingInterval has a default
            // (and minimum) value of 5 minutes.
            pollingSettings.PollingInterval = TimeSpan.FromMinutes(5);
            _pollingView = new RemotePresenceView(_userEndpoint, pollingSettings);
            _pollingView.ApplicationContext = "Polling View";

            // Wire up event handlers for the view
            this.WireUpHandlersForView(_pollingView);

            Console.WriteLine("\nChanging Polling View's category filter to only include Note.");
            _pollingView.SetPresenceSubscriptionCategoriesForPolling(
                new string[] { PresenceCategoryNames.Note });

            try
            {
                // This constructor does very basic validation on the uri
                _target = new RemotePresentitySubscriptionTarget(_remoteUserUri);
            }
            catch (ArgumentException argumentException)
            {
                // ArgumentException will be thrown if the parameter used to
                // create the RemotePresentitySubscriptionTarget is an
                // invalid sip Uri.

                // TODO (Left to the reader): Error handling code to either
                // retry creating the target with corrected parameters, log
                // the error for debugging or gracefully exit the program.
                Console.WriteLine(argumentException.ToString());
                throw;
            }

            Console.WriteLine("\nInitiating subscriptions for both Views to user: "******"succeed", but the StateChanged notifications will indicate the
            // subscription went to a Terminated state.
            _persistentView.StartSubscribingToPresentities(new RemotePresentitySubscriptionTarget[] { _target });
            _pollingView.StartSubscribingToPresentities(new RemotePresentitySubscriptionTarget[] { _target });

            // There is no callback for the StartSubscribingToPresentities
            // operation because subscriptions to multiple targets can
            // complete at different times. Completion or failure of the
            // subscription can be monitored through the
            // SubscriptionStateChanged event handler,
            // RemotePresenceView_NotificationReceived.

            UCMASampleHelper.PauseBeforeContinuing("Press ENTER to unsubscribe.");

            Console.WriteLine("\nBoth Views are terminating any subscriptions to user: "******"Press ENTER to shutdown and exit.");

            // Shutdown Platform
            _helper.ShutdownPlatform();
        }
Example #26
0
        /// <summary>
        /// Callback from <code>BeginEstablish</code> method on endpoint.
        /// </summary>
        /// <param name="result">
        /// Status of the endpoint establishment operation.
        /// </param>
        private void EndpointEstablishmentCompleted(IAsyncResult result)
        {
            // Extract the endpoint that was passed in as the state argument to
            // the BeginEstablish() method.
            ApplicationEndpoint endpoint = result.AsyncState as ApplicationEndpoint;

            if (endpoint == null)
            {
                UCMASampleHelper.WriteErrorLine("ApplicationEndpoint not passed into BeginEstablish() method.");
                UCMASampleHelper.FinishSample();
                return;
            }

            try
            {
                // Determine whether the establish operation completed
                // successfully.
                endpoint.EndEstablish(result);

                // Endpoint state change event handler will log the successful
                // establishment of the endpoint.
                UCMASampleHelper.FinishSample();
            }
            catch (ConnectionFailureException connectionFailureException)
            {
                // ConnectionFailureException will be thrown when no connection
                // can be made to the server.
                // TODO (Left to the reader): Error handling code to either
                // retry establishing the endpoint, log the error for debugging
                // or gracefully exit the program.
                UCMASampleHelper.WriteException(connectionFailureException);
                UCMASampleHelper.FinishSample();
            }
            catch (OperationFailureException operationFailureException)
            {
                // OperationFailureException will be thrown if the retrieval of
                // in-band provisioning data fails.
                // TODO (Left to the reader): Error handling code to either
                // retry establishing the endpoint, log the error for debugging
                // or gracefully exit the program.
                UCMASampleHelper.WriteException(operationFailureException);
                UCMASampleHelper.FinishSample();
            }
            catch (RegisterException registerException)
            {
                // RegisterException will be thrown if the SIP REGISTER
                // operation fails.
                // TODO (Left to the reader): Error handling code to either
                // retry establishing the endpoint, log the error for debugging
                // or gracefully exit the program.
                UCMASampleHelper.WriteException(registerException);
                UCMASampleHelper.FinishSample();
            }
            catch (AuthenticationException authenticationException)
            {
                // AuthenticationException will be thrown if general
                // authentication-related problem occur.
                // TODO (Left to the reader): Error handling code to either
                // retry establishing the endpoint, log the error for debugging
                // or gracefully exit the program.
                UCMASampleHelper.WriteException(authenticationException);
                UCMASampleHelper.FinishSample();
            }
            catch (OperationTimeoutException operationTimeoutException)
            {
                // OperationTimeoutException will be thrown if the registrar
                // server does not respond to REGISTER request.
                // TODO (Left to the reader): Error handling code to either
                // retry establishing the endpoint, log the error for debugging
                // or gracefully exit the program.
                UCMASampleHelper.WriteException(operationTimeoutException);
                UCMASampleHelper.FinishSample();
            }
            catch (RealTimeException realTimeException)
            {
                // RealTimeException will be thrown if the endpoint establish
                // operation fails due to some other issue.
                // TODO (Left to the reader): Error handling code to either
                // retry establishing the endpoint, log the error for debugging
                // or gracefully exit the program.
                UCMASampleHelper.WriteException(realTimeException);
                UCMASampleHelper.FinishSample();
            }
        }
        private void Run()
        {
            // A helper class to take care of platform and endpoint setup and cleanup.
            _helper = new UCMASampleHelper();

            // Create and establish a user endpoint using the user’s network credentials.
            _userEndpoint = _helper.CreateEstablishedUserEndpoint(
                "FindContact Sample User" /* endpointFriendlyName */);

            // Register a delegate to be called when an incoming InstantMessagingCall arrives.
            _userEndpoint.RegisterForIncomingCall <InstantMessagingCall>(InstantMessagingCall_Received);

            Console.WriteLine("Waiting for an incoming instant messaging call...");
            int ThreadID = Thread.CurrentThread.ManagedThreadId;

            Console.WriteLine("Main thread: ID " + ThreadID);
            // Pause main thread until an incoming call arrives and is accepted.
            _waitUntilIncomingCallIsAccepted.WaitOne();

            InstantMessagingFlow imFlow = _instantMessagingCall.Flow;

            imFlow.BeginSendInstantMessage("Press 1 for Service Department.\n" +
                                           "Press 2 for Sales Department.", CallSendInstantMessageCB, _instantMessagingCall);
            imFlow.MessageReceived += new EventHandler <InstantMessageReceivedEventArgs>(IMFlow_MessageReceived);
            _waitForAvailableTarget.WaitOne();

            if (_remoteContactUri != null)
            {
                imFlow.BeginSendInstantMessage("Contact found: " + _remoteContactUri.ToString(), CallSendInstantMessageCB, _instantMessagingCall);
                // Join the conversation to the IM MCU.
                _conferenceSession = _incomingConversation.ConferenceSession;
                ConferenceJoinOptions confJoinOptions = new ConferenceJoinOptions();
                confJoinOptions.JoinMode = JoinMode.Default;
                _conferenceSession.BeginJoin(confJoinOptions, ConferenceJoinCB, _conferenceSession);

                ThreadID = Thread.CurrentThread.ManagedThreadId;
                Console.WriteLine("Main thread: ID " + ThreadID);
                _waitUntilConferenceInvitationIsDelivered.WaitOne();
            }
            else
            {
                Console.WriteLine("Could not find an available contact.");
                imFlow.BeginSendInstantMessage("Could not find an available contact.\nPlease call again later.", CallSendInstantMessageCB, _instantMessagingCall);
            }
            // Unregister for notification of the MessageReceived event.
            imFlow.MessageReceived -= new EventHandler <InstantMessageReceivedEventArgs>(IMFlow_MessageReceived);
            // Cancel the subscription to the presence session by unsubscribing.
            _userEndpoint.ContactGroupServices.BeginUnsubscribe(ContactGroupUnsubscribeCB, _userEndpoint.ContactGroupServices);
            _remotePresenceView.BeginTerminate(ViewTerminateCB, _remotePresenceView);
            UCMASampleHelper.PauseBeforeContinuing("Press ENTER to shut down and exit.");

            // Terminate the call, the conversation, and then unregister the
            // endpoint from receiving an incoming call. Terminating these
            // additional objects individually is made redundant by shutting down
            // the platform right after, but in the multiple call case, this is
            // needed for object hygiene. Terminating a Conversation terminates
            // all its associated calls, and terminating an endpoint
            // terminates all conversations on that endpoint.
            _instantMessagingCall.BeginTerminate(CallTerminateCB, _instantMessagingCall);
            _waitUntilConversationIsTerminated.WaitOne();
            _userEndpoint.UnregisterForIncomingCall <InstantMessagingCall>(InstantMessagingCall_Received);

            // Clean up by shutting down the platform.
            _helper.ShutdownPlatform();
        }
Example #28
0
        private void Run()
        {
            // Initialize and startup the platform.
            Exception ex = null;

            try
            {
                // Create the UserEndpoint

                _helper       = new UCMASampleHelper();
                _userEndpoint = _helper.CreateEstablishedUserEndpoint(
                    "IMCall Sample User" /*endpointFriendlyName*/);

                Console.Write("The User Endpoint owned by URI: ");
                Console.Write(_userEndpoint.OwnerUri);
                Console.WriteLine(" is now established and registered.");

                // Setup the conversation and place the call.
                ConversationSettings convSettings = new ConversationSettings();
                convSettings.Priority = _conversationPriority;
                convSettings.Subject  = _conversationSubject;

                // Conversation represents a collection of modes of communication
                // (media types)in the context of a dialog with one or multiple
                // callees.
                Conversation conversation = new Conversation(_userEndpoint, convSettings);
                _instantMessagingCall = new InstantMessagingCall(conversation);

                // Call: StateChanged: Only hooked up for logging. Generally,
                // this can be used to surface changes in Call state to the UI
                _instantMessagingCall.StateChanged += this.InstantMessagingCall_StateChanged;

                // Subscribe for the flow created event; the flow will be used to
                // send the media (here, IM).
                // Ultimately, as a part of the callback, the messages will be
                // sent/received.
                _instantMessagingCall.InstantMessagingFlowConfigurationRequested +=
                    this.InstantMessagingCall_FlowConfigurationRequested;

                // Get the sip address of the far end user to communicate with.
                String _calledParty = "sip:" +
                                      UCMASampleHelper.PromptUser(
                    "Enter the URI of the user logged onto Microsoft Lync, in the User@Host format => ",
                    "RemoteUserURI");

                // Place the call to the remote party, without specifying any
                // custom options. Please note that the conversation subject
                // overrides the toast message, so if you want to see the toast
                // message, please set the conversation subject to null.
                _instantMessagingCall.BeginEstablish(_calledParty, new ToastMessage("Hello Toast"), null,
                                                     CallEstablishCompleted, _instantMessagingCall);
            }
            catch (InvalidOperationException iOpEx)
            {
                // Invalid Operation Exception may be thrown if the data provided
                // to the BeginXXX methods was invalid/malformed.
                // TODO (Left to the reader): Write actual handling code here.
                ex = iOpEx;
            }
            finally
            {
                if (ex != null)
                {
                    // If the action threw an exception, terminate the sample,
                    // and print the exception to the console.
                    // TODO (Left to the reader): Write actual handling code here.
                    Console.WriteLine(ex.ToString());
                    Console.WriteLine("Shutting down platform due to error");
                    _helper.ShutdownPlatform();
                }
            }

            // Wait for sample to complete
            _sampleCompletedEvent.WaitOne();
        }