Exemplo n.º 1
0
        /// <summary>
        /// Sets up the OCS objects using the credentials provided
        /// </summary>
        /// <remarks>
        /// In this sample this is invoked when the user presses the "Apply Server Settings" button
        /// </remarks>
        /// <param name="applicationUri">SIP Uri of the OCS account</param>
        /// <param name="serverName">SIP server URI</param>
        /// <param name="serverPort">Port (usually 443)</param>
        /// <param name="credential">Credentials for establishing the user endpoint</param>
        private void InitializeMCSConnection(string applicationUri, string serverName, int serverPort, NetworkCredential credential)
        {
            //Initialize new client platform.
            //Note that this sample only supports TLS, and additionally that it uses ClientPlatform rather than ServerPlatform.
            //In a production application, ServerPlatform should be used; ClientPlatform is preferred here to demonstrate the platform without
            //requiring application provisioning. This is out of the scope of this sample, however.
            ClientPlatformSettings clientPlatformSettings;

            clientPlatformSettings = new ClientPlatformSettings("VoiceXMLTestApp", SipTransportType.Tls);

            collaborationPlatform = new CollaborationPlatform(clientPlatformSettings);
            collaborationPlatform.EndStartup(collaborationPlatform.BeginStartup(null, null));

            //Create a new UserEndpoint based on the information provided through the UI.
            //As with Server/Client platform above, in production, this should be replaced with provisioned ApplicationEndpoint in most circumstances.
            UserEndpointSettings endpointSettings;

            endpointSettings = new UserEndpointSettings(applicationUri, serverName, serverPort);

            endpoint = new UserEndpoint(collaborationPlatform, endpointSettings);

            endpoint.Credential = credential;

            //Bind the event handler to handle incoming calls. Use of the strongly-typed AVCall dictates that calls not matching this type will not be raised.
            endpoint.RegisterForIncomingCall <AudioVideoCall>(AudioVideoCallReceived);

            endpoint.EndEstablish(endpoint.BeginEstablish(null, endpoint));
        }
Exemplo n.º 2
0
            public void Start(List <Uri> chatRoomsToJoin)
            {
                Console.WriteLine("正在登陆用户");
                Console.ReadKey();

                try
                {
                    chatRooms = chatRoomsToJoin;

                    // Connect to Lync Server
                    ClientPlatformSettings platformSettings = new ClientPlatformSettings("PersistentChat.Test", SipTransportType.Tls);
                    CollaborationPlatform  collabPlatform   = new CollaborationPlatform(platformSettings);
                    collabPlatform.EndStartup(collabPlatform.BeginStartup(null, null));
                    UserEndpointSettings userEndpointSettings = new UserEndpointSettings(UserUri.AbsoluteUri, SampleCommon.LyncServer);
                    userEndpointSettings.Credential = new NetworkCredential(UserName, Password);
                    userEndpoint = new UserEndpoint(collabPlatform, userEndpointSettings);
                    Console.WriteLine("正在登陆用户----------->");
                    // Login to Lync Server
                    currentOperation.Begin("Connect to Lync Server",
                                           () => userEndpoint.BeginEstablish(ar => LyncServerBeginEstablishFinished(ar), null));
                }
                catch (Exception e) {
                    Console.WriteLine("正在登陆用户");
                }
            }
Exemplo n.º 3
0
        public UserEndpoint CreateUserEndpoint(UserEndpointSettings userEndpointSettings)
        {
            if (_collabPlatform == null)
            {
                // Initalize and startup the platform.
                ClientPlatformSettings clientPlatformSettings = new ClientPlatformSettings(_applicationName, _transportType);
                _collabPlatform = new CollaborationPlatform(clientPlatformSettings);
            }

            _userEndpoint = new UserEndpoint(_collabPlatform, userEndpointSettings);
            return(_userEndpoint);
        }
Exemplo n.º 4
0
        public void CreateUserEndpoint(string userURI)
        {
            UserEndpointSettings settings = new UserEndpointSettings(userURI);

            user = new UserEndpoint(collabPlatform, settings);
            user.EndEstablish(user.BeginEstablish(null, null));
            if (user.State != LocalEndpointState.Established)
            {
                throw new Exception("Local endpoint state is not established");
            }

            alertNotification = null;
        }
Exemplo n.º 5
0
        // Method to create an endpoint given a UserEndpointSettings object.
        // This method returns a UserEndpoint object so that you can wire up Endpoint-specific event handlers.
        // If you do not want to get endpoint specific event information at the time the endpoint is established, you may
        // want to call the CreateEstablishedUserEndpoint method directly. Otherwise, you may call ReadUserSettings
        // followed by CreateUserEndpoint, followed by EstablishUserEndpoint methods.
        public UserEndpoint CreateUserEndpoint(UserEndpointSettings userEndpointSettings)
        {
            // Reuse platform instance so that all endpoints share the same platform.
            if (_collabPlatform == null)
            {
                // Initialize and start the platform.
                ClientPlatformSettings clientPlatformSettings = new ClientPlatformSettings(_applicationName, _transportType);
                _collabPlatform = new CollaborationPlatform(clientPlatformSettings);
            }

            _userEndpoint = new UserEndpoint(_collabPlatform, userEndpointSettings);
            return(_userEndpoint);
        }
Exemplo n.º 6
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();
            }
        }
Exemplo n.º 7
0
        protected override async void OnStart(string[] args) {
            if (!Directory.Exists(Path.Combine(ZMachineSettings.AppDataFolder, "Saves"))) {
                Directory.CreateDirectory(Path.Combine(ZMachineSettings.AppDataFolder, "Saves"));
            }
            if (!Directory.Exists(Path.Combine(ZMachineSettings.AppDataFolder, "Games"))) {
                Log.Warn("No Z-Machine games included");
                Directory.CreateDirectory(Path.Combine(ZMachineSettings.AppDataFolder, "Games"));
            } else {
                if (!Directory.GetFiles(Path.Combine(ZMachineSettings.AppDataFolder, "Games")).Any()) {
                    Log.Warn("No Z-Machine games included");
                }
            }


            var clientPlatformSettings = new ClientPlatformSettings("LyncZMachine", SipTransportType.Tls);
            _collabPlatform = new CollaborationPlatform(clientPlatformSettings);
            await _collabPlatform.StartupAsync();

            _settings = new UserEndpointSettings(
                ZMachineSettings.Settings.Sip,
                ZMachineSettings.Settings.LyncServer
                //ConfigurationManager.AppSettings["sip"], 
                //ConfigurationManager.AppSettings["LyncServer"]
            ) {
                Credential = new NetworkCredential(
                    ZMachineSettings.Settings.Username,
                    ZMachineSettings.Settings.Password,
                    ZMachineSettings.Settings.Domain
                    //ConfigurationManager.AppSettings["username"], 
                    //ConfigurationManager.AppSettings["pw"], 
                    //ConfigurationManager.AppSettings["domain"]
                ),
                AutomaticPresencePublicationEnabled = true
            };
            _settings.Presence.UserPresenceState = PresenceState.UserAvailable;

            _endpoint = new UserEndpoint(_collabPlatform, _settings);
            await _endpoint.EstablishAsync();

            _endpoint.RegisterForIncomingCall<InstantMessagingCall>(GameStarted);

            _webServer = WebApp.Start<Startup>(string.Format("http://+:{0}/ZMachine", ZMachineSettings.Settings.Port));
        }
Exemplo n.º 8
0
        private async Task Establish()
        {
            Console.WriteLine("Establishing with endpoint:" + _sipaddress);

            if (!_endpointStarted)
            {
                Console.WriteLine("Collab Platform not started, starting now");
                {
                    await EstablishCollaborationPlatform();
                }
            }

            var settings = new UserEndpointSettings(_sipaddress);

            settings.Credential = new System.Net.NetworkCredential(_username, _password);


            _endpoint = new UserEndpoint(_collabPlatform, settings);
            await _endpoint.EstablishAsync();
        }
Exemplo n.º 9
0
        public UserEndpoint CreateEstablishedUserEndpoint()
        {
            UserEndpointSettings userEndpointSettings;
            UserEndpoint         userEndpoint = null;

            try
            {
                userEndpointSettings = new UserEndpointSettings("sip:" + _ocsaccountemail, _sip);
                //userEndpointSettings.Credential = System.Net.CredentialCache.DefaultNetworkCredentials;
                userEndpointSettings.Credential = new NetworkCredential(_ocsaccount, _oscaccountpsd, _oscaccountdomain);
                log("Login success : srv_eplm");
                userEndpoint = CreateUserEndpoint(userEndpointSettings);
                EstablishUserEndpoint(userEndpoint);
            }
            catch (InvalidOperationException iOpEx)
            {
                log("Invalid Operation Exception: " + iOpEx.ToString());
            }
            return(userEndpoint);
        }
Exemplo n.º 10
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; }
        }
Exemplo n.º 11
0
            public void Start(List <Uri> chatRoomsToJoin)
            {
                chatRooms = chatRoomsToJoin;
                Log(string.Format("Start Client: chatRooms.Count={0}", chatRooms.Count));

                currentOperation.Reset();

                // Connect to OCS
                ClientPlatformSettings platformSettings = new ClientPlatformSettings("PersistentChat.Test", SipTransportType.Tls);
                CollaborationPlatform  collabPlatform   = new CollaborationPlatform(platformSettings);

                collabPlatform.EndStartup(collabPlatform.BeginStartup(null, null));
                UserEndpointSettings userEndpointSettings = new UserEndpointSettings(UserUri.AbsoluteUri, SampleCommon.OcsServer);

                userEndpointSettings.Credential = new NetworkCredential(UserName, Password);
                userEndpoint = new UserEndpoint(collabPlatform, userEndpointSettings);

                // Login to OCS
                currentOperation.Begin("Connect to OCS",
                                       () => userEndpoint.BeginEstablish(OcsBeginEstablishFinished, null));
            }
        public static UserEndpoint ConnectLyncServer(string userSipUri, string lyncServer, bool usingSso, string username, string password)
        {
            // Create the Lync Server UserEndpoint and attempt to connect to Lync Server
            Console.WriteLine("{0} Connecting to Lync Server... [{1}]", username, lyncServer);

            // Use the appropriate SipTransportType depending on current Lync Server deployment
            ClientPlatformSettings platformSettings = new ClientPlatformSettings("PersistentChat.Test", SipTransportType.Tls);
            CollaborationPlatform  collabPlatform   = new CollaborationPlatform(platformSettings);

            collabPlatform.AllowedAuthenticationProtocol = SipAuthenticationProtocols.Ntlm;

            // Initialize the platform
            collabPlatform.EndStartup(collabPlatform.BeginStartup(null, null));

            // You can also pass in the server's port # here.
            UserEndpointSettings userEndpointSettings = new UserEndpointSettings(userSipUri, lyncServer);

            // When usingSso is true use the current users credentials, otherwise use username and password
            userEndpointSettings.Credential = usingSso ? SipCredentialCache.DefaultCredential : new NetworkCredential(username, password);

            UserEndpoint userEndpoint = new UserEndpoint(collabPlatform, userEndpointSettings);

            // Login to Lync Server.
            userEndpoint.EndEstablish(userEndpoint.BeginEstablish(null, null));

            if (PersistentChatServerUri == null)
            {
                // Extract default Persistent Chat pool uri from inband
                ProvisioningData provisioningData =
                    userEndpoint.EndGetProvisioningData(userEndpoint.BeginGetProvisioningData(null, null));
                PersistentChatServerUri = new Uri(provisioningData.PersistentChatConfiguration.DefaultPersistentChatUri);
                Console.WriteLine("\t-- {0}PersistentChatServerUri:{1}", username, PersistentChatServerUri);
            }

            Console.WriteLine("\t{0} Connecting>>>>Success", username);
            return(userEndpoint);
        }
Exemplo n.º 13
0
        private async void btnTest_Click(object sender, EventArgs e) {
            try {
                Cursor = Cursors.WaitCursor;
                var clientPlatformSettings = new ClientPlatformSettings("LyncZMachine", SipTransportType.Tls);
                var collabPlatform = new CollaborationPlatform(clientPlatformSettings);
                await collabPlatform.StartupAsync();

                var settings = new UserEndpointSettings(txtSip.Text, txtServer.Text) {
                    Credential = new NetworkCredential(txtUsername.Text, txtPassword.Text, txtDomain.Text),
                    AutomaticPresencePublicationEnabled = true
                };

                var endpoint = new UserEndpoint(collabPlatform, settings);

                await endpoint.EstablishAsync();
                btnSave.Enabled = true;
                MessageBox.Show("Connected successfully to " + txtServer.Text + " as " + txtSip.Text);
                try {
                    await endpoint.TerminateAsync();
                    await collabPlatform.ShutdownAsync();
                } catch (Exception ex) {
                    MessageBox.Show(ex.Message, "An Error Occurred", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }

            } catch (Exception ex) {
                MessageBox.Show(ex.Message, "An Error Occurred", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                btnSave.Enabled = false;
            } finally {
                Cursor = Cursors.Default;
            }
        }
Exemplo n.º 14
0
        public UserEndpoint CreateUserEndpointWithServerPlatform(string endpointFriendlyName)
        {
            string prompt = string.Empty;

            if (string.IsNullOrEmpty(endpointFriendlyName))
            {
                endpointFriendlyName = "Default User";
            }

            try
            {
                Console.WriteLine(string.Empty);
                Console.WriteLine("Creating User Endpoint for {0}...", endpointFriendlyName);
                Console.WriteLine();

                if (ConfigurationManager.AppSettings[_serverFQDNPrompt + _userCount] != null)
                {
                    if (ReadGenericApplicationContactConfiguration())
                    {
                        Console.WriteLine("Using {0} as Microsoft Lync Server", _serverFqdn);
                    }
                    else
                    {
                        Console.WriteLine("Error. Could not read AppSettings");
                    }
                }
                else
                {
                    Console.WriteLine("Please fill in the App.config file.");
                }

                // Prompt user for user name
                prompt = String.Concat(
                    "Please enter the User Name for ",
                    endpointFriendlyName,
                    " (or hit the ENTER key to use current credentials)\r\n" +
                    "Please enter the User Name => ");
                _userName = PromptUser(prompt, _userNamePrompt + _userCount);

                // If user name is empty, use current credentials
                if (string.IsNullOrEmpty(_userName))
                {
                    Console.WriteLine("Username was empty - using current credentials...");
                    _useSuppliedCredentials = true;
                }
                else
                {
                    // Prompt for password
                    prompt        = String.Concat("Enter the User Password for ", endpointFriendlyName, " => ");
                    _userPassword = PromptUser(prompt, null);

                    prompt      = String.Concat("Please enter the User Domain for ", endpointFriendlyName, " => ");
                    _userDomain = PromptUser(prompt, _userDomainPrompt + _userCount);
                }

                // Prompt user for user URI
                prompt   = String.Concat("Please enter the User URI for ", endpointFriendlyName, " in the User@Host format => ");
                _userURI = PromptUser(prompt, _userURIPrompt + _userCount);
                if (!(_userURI.ToLower().StartsWith("sip:") || _userURI.ToLower().StartsWith("tel:")))
                {
                    _userURI = "sip:" + _userURI;
                }

                // Reuse platform instance so that all endpoints share the same platform.
                if (_serverCollabPlatform == null)
                {
                    CreateAndStartServerPlatform();
                }

                // Increment the last user number
                _userCount++;

                // Initalize and register the endpoint, using the credentials of the user the application will be acting as.
                // NOTE: the _userURI should always be of the form "sip:user@host"
                UserEndpointSettings userEndpointSettings = new UserEndpointSettings(_userURI, _serverFqdn);
                if (!_useSuppliedCredentials)
                {
                    _credential = new System.Net.NetworkCredential(_userName, _userPassword, _userDomain);
                    userEndpointSettings.Credential = _credential;
                }
                else
                {
                    userEndpointSettings.Credential = System.Net.CredentialCache.DefaultNetworkCredentials;
                }

                _userEndpoint = new UserEndpoint(_serverCollabPlatform, userEndpointSettings);
                _endpointInitCompletedEvent.Reset();
                _userEndpoint.BeginEstablish(EndEndpointEstablish, _userEndpoint);

                // Sync; wait for the registration to complete.
                _endpointInitCompletedEvent.WaitOne();
                Console.WriteLine("{0} endpoint established...", endpointFriendlyName);
            }
            catch (InvalidOperationException iOpEx)
            {
                // Invalid Operation Exception should only be thrown on poorly-entered input.
                Console.WriteLine("Invalid Operation Exception: " + iOpEx.ToString());
            }

            return(_userEndpoint);
        }
Exemplo n.º 15
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();
        }
Exemplo n.º 16
0
        public void CreateOrGetUserEndpoint(AsyncTask task, object state)
        {
            string ownerUri = state as string;

            if (String.IsNullOrEmpty(ownerUri))
            {
                task.Complete(new InvalidOperationException("OwnerUri is needed to request a user endpoint."));
                return;
            }
            RealTimeAddress ownerAddress = null;

            try
            {
                ownerAddress = new RealTimeAddress(ownerUri);
            }
            catch (ArgumentException exception)
            {
                task.Complete(exception);
                return;
            }
            MyUserEndpoint myUserEndpoint = null;

            lock (this.SyncRoot)
            {
                if (m_userEndpoints.ContainsKey(ownerAddress))
                {
                    myUserEndpoint = m_userEndpoints[ownerAddress];
                    if (myUserEndpoint.UserEndpoint.State == LocalEndpointState.Terminating || myUserEndpoint.UserEndpoint.State == LocalEndpointState.Terminated)
                    {
                        myUserEndpoint = null; // Loose it since it is going away.
                        m_userEndpoints.Remove(ownerAddress);
                        m_userEndpointReferenceCounts.Remove(ownerAddress);
                    }
                    else
                    {
                        int count = m_userEndpointReferenceCounts[ownerAddress];
                        count++;
                        m_userEndpointReferenceCounts[ownerAddress] = count;
                    }
                }
                if (myUserEndpoint == null)
                {
                    // Create and add user endpoint into dictionary.
                    // One could use the platform discover server from uri if the topology has DNS srv records for server auto discovery.
                    // Normally, this would point to a director. Here, we will use the proxy of the application endpoint.
                    UserEndpointSettings userEndpointSettings = new UserEndpointSettings(ownerUri, m_settings.ProxyHost, m_settings.ProxyPort);
                    UserEndpoint         userEndpoint         = new UserEndpoint(m_parent.Platform, userEndpointSettings);
                    myUserEndpoint = new MyUserEndpoint(userEndpoint);
                    m_userEndpoints.Add(ownerAddress, myUserEndpoint);
                    m_userEndpointReferenceCounts.Add(ownerAddress, 1);
                    myUserEndpoint.UserEndpoint.StateChanged += UserEndpointStateChanged; // Ensures that only one registration per endpoint.
                }
                UserEndpointCreationActionResult result = new UserEndpointCreationActionResult(myUserEndpoint, null);
                task.TaskResult = result; // Store it for now.
                if (myUserEndpoint.UserEndpoint.State == LocalEndpointState.Established)
                {
                    task.Complete(null, result);
                }
                else if (myUserEndpoint.UserEndpoint.State == LocalEndpointState.Establishing)
                {
                    // Wait till the endpoint establish completes.
                    lock (this.SyncRoot)
                    {
                        m_pendingUserEndpointCreationTasks.Add(task);
                    }
                }
                else if (myUserEndpoint.UserEndpoint.State == LocalEndpointState.Idle)
                {
                    AsyncTask establishTask = new AsyncTask(this.StartupUserEndpoint, myUserEndpoint.UserEndpoint);
                    establishTask.TaskCompleted +=
                        delegate(object sender, AsyncTaskCompletedEventArgs e)
                    {
                        task.TaskResult.Exception = e.ActionResult.Exception;     // Transfer
                        task.Complete(e.ActionResult.Exception, task.TaskResult);
                        lock (this.SyncRoot)
                        {
                            // Complete pending tasks
                            foreach (AsyncTask pendingTask in m_pendingUserEndpointCreationTasks)
                            {
                                pendingTask.TaskResult.Exception = e.ActionResult.Exception;
                                pendingTask.Complete(e.ActionResult.Exception, pendingTask.TaskResult);
                            }
                            m_pendingUserEndpointCreationTasks.Clear();
                        }
                    };
                    establishTask.StartTask();
                }
            }
        }
Exemplo n.º 17
0
        // Method to create an endpoint given a UserEndpointSettings object.
        // This method returns a UserEndpoint object so that you can wire up Endpoint-specific event handlers. 
        // If you do not want to get endpoint specific event information at the time the endpoint is established, you may 
        // want to call the CreateEstablishedUserEndpoint method directly. Otherwise, you may call ReadUserSettings
        // followed by CreateUserEndpoint, followed by EstablishUserEndpoint methods.
        public UserEndpoint CreateUserEndpoint(UserEndpointSettings userEndpointSettings)
        {
            // Reuse platform instance so that all endpoints share the same platform.
            if (_collabPlatform == null)
            {
                // Initialize and start the platform.
                ClientPlatformSettings clientPlatformSettings = new ClientPlatformSettings(_applicationName, _transportType);
                _collabPlatform = new CollaborationPlatform(clientPlatformSettings);
            }

            _userEndpoint = new UserEndpoint(_collabPlatform, userEndpointSettings);
            return _userEndpoint;
        }
Exemplo n.º 18
0
        // Method to read user settings from app.config file or from the console prompts
        // This method returns a UserEndpointSettings object. If you do not want to monitor LocalOwnerPresence, you may 
        // want to call the CreateEstablishedUserEndpoint method directly. Otherwise, you may call ReadUserSettings
        // followed by CreateUserEndpoint, followed by EstablishUserEndpoint methods.
        public UserEndpointSettings ReadUserSettings(string userFriendlyName)
        {
            UserEndpointSettings userEndpointSettings = null;
            string prompt = string.Empty;
            if (string.IsNullOrEmpty(userFriendlyName))
            {
                userFriendlyName = "Default User";
            }

            try
            {
                NonBlockingConsole.WriteLine(string.Empty);
                NonBlockingConsole.WriteLine("Creating User Endpoint for {0}...", userFriendlyName);
                NonBlockingConsole.WriteLine("");

                if (ConfigurationManager.AppSettings[_serverFQDNPrompt + _userCount] != null)
                {
                    _serverFqdn = ConfigurationManager.AppSettings[_serverFQDNPrompt + _userCount];
                    NonBlockingConsole.WriteLine("Using {0} as Microsoft Lync Server", _serverFqdn);
                }
                else
                {
                    // Prompt user for server FQDN. If server FQDN was entered before, then let the user use the saved value.
                    string localServer;
                    StringBuilder promptBuilder = new StringBuilder();
                    if (!string.IsNullOrEmpty(_serverFqdn))
                    {
                        promptBuilder.Append("Current Microsoft Lync Server = ");
                        promptBuilder.Append(_serverFqdn);
                        promptBuilder.AppendLine(". Please hit ENTER to retain this setting - OR - ");
                    }

                    promptBuilder.Append("Please enter the FQDN of the Microsoft Lync Server that the ");
                    promptBuilder.Append(userFriendlyName);
                    promptBuilder.Append(" endpoint is homed on => ");
                    localServer = PromptUser(promptBuilder.ToString(), null);

                    if (!String.IsNullOrEmpty(localServer))
                    {
                        _serverFqdn = localServer;
                    }
                }

                // Prompt user for user name
                prompt = String.Concat("Please enter the User Name for ",
                                        userFriendlyName,
                                        " (or hit the ENTER key to use current credentials)\r\n" +
                                        "Please enter the User Name => ");
                _userName = PromptUser(prompt, _userNamePrompt + _userCount);

                // If user name is empty, use current credentials
                if (string.IsNullOrEmpty(_userName))
                {
                    NonBlockingConsole.WriteLine("Username was empty - using current credentials...");
                    _useSuppliedCredentials = true;
                }
                else
                {
                    // Prompt for password
                    prompt = String.Concat("Enter the User Password for ", userFriendlyName, " => ");
                    _userPassword = PromptUser(prompt, null);

                    prompt = String.Concat("Please enter the User Domain for ", userFriendlyName, " => ");
                    _userDomain = PromptUser(prompt, _userDomainPrompt + _userCount);
                }

                // Prompt user for user URI
                prompt = String.Concat("Please enter the User URI for ", userFriendlyName, " in the User@Host format => ");
                _userURI = PromptUser(prompt, _userURIPrompt + _userCount);
                if (!(_userURI.ToLower().StartsWith("sip:") || _userURI.ToLower().StartsWith("tel:")))
                    _userURI = "sip:" + _userURI;

                // Increment the last user number
                _userCount++;

                // Initalize and register the endpoint, using the credentials of the user the application will be acting as.
                // NOTE: the _userURI should always be of the form "sip:user@host"
                userEndpointSettings = new UserEndpointSettings(_userURI, _serverFqdn);

                if (!_useSuppliedCredentials)
                {
                    _credential = new System.Net.NetworkCredential(_userName, _userPassword, _userDomain);
                    userEndpointSettings.Credential = _credential;
                }
                else
                {
                    userEndpointSettings.Credential = System.Net.CredentialCache.DefaultNetworkCredentials;
                }
            }
            catch (InvalidOperationException iOpEx)
            {
                // Invalid Operation Exception should only be thrown on poorly-entered input.
                NonBlockingConsole.WriteLine("Invalid Operation Exception: " + iOpEx.ToString());
            }

            return userEndpointSettings;
        }
Exemplo n.º 19
0
        private async Task Establish()
        {
            Console.WriteLine("Establishing with endpoint:" + _sipaddress);

            if (!_endpointStarted)
            {
                Console.WriteLine("Collab Platform not started, starting now");
                {
                   await EstablishCollaborationPlatform();
                }
            }
                     
            var settings = new UserEndpointSettings(_sipaddress);
            settings.Credential = new System.Net.NetworkCredential(_username, _password);

            
            _endpoint = new UserEndpoint(_collabPlatform, settings);
            await _endpoint.EstablishAsync();
        }
Exemplo n.º 20
0
        // Method to read user settings from app.config file or from the console prompts
        // This method returns a UserEndpointSettings object. If you do not want to monitor LocalOwnerPresence, you may
        // want to call the CreateEstablishedUserEndpoint method directly. Otherwise, you may call ReadUserSettings
        // followed by CreateUserEndpoint, followed by EstablishUserEndpoint methods.
        public UserEndpointSettings ReadUserSettings(string userFriendlyName)
        {
            UserEndpointSettings userEndpointSettings = null;
            string prompt = string.Empty;

            if (string.IsNullOrEmpty(userFriendlyName))
            {
                userFriendlyName = "Default User";
            }

            try
            {
                NonBlockingConsole.WriteLine(string.Empty);
                NonBlockingConsole.WriteLine("Creating User Endpoint for {0}...", userFriendlyName);
                NonBlockingConsole.WriteLine("");

                if (ConfigurationManager.AppSettings[_serverFQDNPrompt + _userCount] != null)
                {
                    _serverFqdn = ConfigurationManager.AppSettings[_serverFQDNPrompt + _userCount];
                    NonBlockingConsole.WriteLine("Using {0} as Microsoft Lync Server", _serverFqdn);
                }
                else
                {
                    // Prompt user for server FQDN. If server FQDN was entered before, then let the user use the saved value.
                    string        localServer;
                    StringBuilder promptBuilder = new StringBuilder();
                    if (!string.IsNullOrEmpty(_serverFqdn))
                    {
                        promptBuilder.Append("Current Microsoft Lync Server = ");
                        promptBuilder.Append(_serverFqdn);
                        promptBuilder.AppendLine(". Please hit ENTER to retain this setting - OR - ");
                    }

                    promptBuilder.Append("Please enter the FQDN of the Microsoft Lync Server that the ");
                    promptBuilder.Append(userFriendlyName);
                    promptBuilder.Append(" endpoint is homed on => ");
                    localServer = PromptUser(promptBuilder.ToString(), null);

                    if (!String.IsNullOrEmpty(localServer))
                    {
                        _serverFqdn = localServer;
                    }
                }

                // Prompt user for user name
                prompt = String.Concat("Please enter the User Name for ",
                                       userFriendlyName,
                                       " (or hit the ENTER key to use current credentials)\r\n" +
                                       "Please enter the User Name => ");
                _userName = PromptUser(prompt, _userNamePrompt + _userCount);

                // If user name is empty, use current credentials
                if (string.IsNullOrEmpty(_userName))
                {
                    NonBlockingConsole.WriteLine("Username was empty - using current credentials...");
                    _useSuppliedCredentials = true;
                }
                else
                {
                    // Prompt for password
                    prompt        = String.Concat("Enter the User Password for ", userFriendlyName, " => ");
                    _userPassword = PromptUser(prompt, null);

                    prompt      = String.Concat("Please enter the User Domain for ", userFriendlyName, " => ");
                    _userDomain = PromptUser(prompt, _userDomainPrompt + _userCount);
                }

                // Prompt user for user URI
                prompt   = String.Concat("Please enter the User URI for ", userFriendlyName, " in the User@Host format => ");
                _userURI = PromptUser(prompt, _userURIPrompt + _userCount);
                if (!(_userURI.ToLower().StartsWith("sip:") || _userURI.ToLower().StartsWith("tel:")))
                {
                    _userURI = "sip:" + _userURI;
                }

                // Increment the last user number
                _userCount++;

                // Initalize and register the endpoint, using the credentials of the user the application will be acting as.
                // NOTE: the _userURI should always be of the form "sip:user@host"
                userEndpointSettings = new UserEndpointSettings(_userURI, _serverFqdn);

                if (!_useSuppliedCredentials)
                {
                    _credential = new System.Net.NetworkCredential(_userName, _userPassword, _userDomain);
                    userEndpointSettings.Credential = _credential;
                }
                else
                {
                    userEndpointSettings.Credential = System.Net.CredentialCache.DefaultNetworkCredentials;
                }
            }
            catch (InvalidOperationException iOpEx)
            {
                // Invalid Operation Exception should only be thrown on poorly-entered input.
                NonBlockingConsole.WriteLine("Invalid Operation Exception: " + iOpEx.ToString());
            }

            return(userEndpointSettings);
        }
Exemplo n.º 21
0
        public void Run()
        {
            //Initalize and startup the platform.
            ClientPlatformSettings clientPlatformSettings = new ClientPlatformSettings(_applicationName, _transportType);

            _collabPlatform = new CollaborationPlatform(clientPlatformSettings);
            _collabPlatform.BeginStartup(EndPlatformStartup, _collabPlatform);

            // Get port range
            NetworkPortRange portRange = CollaborationPlatform.AudioVideoSettings.GetPortRange();

            Console.WriteLine("Port range is from " + portRange.LocalNetworkPortMin + " to " + portRange.LocalNetworkPortMax);

            // Modifying port range
            portRange.SetRange(1500, 2000);
            CollaborationPlatform.AudioVideoSettings.SetPortRange(portRange);
            Console.WriteLine("Port range now is from " + portRange.LocalNetworkPortMin + " to " + portRange.LocalNetworkPortMax);

            //Sync; wait for the startup to complete.
            _autoResetEvent.WaitOne();


            //Initalize and register the endpoint, using the credentials of the user the application will be acting as.
            UserEndpointSettings userEndpointSettings = new UserEndpointSettings(_userURI, _userServer);

            userEndpointSettings.Credential = _credential;
            _userEndpoint = new UserEndpoint(_collabPlatform, userEndpointSettings);
            _userEndpoint.BeginEstablish(EndEndpointEstablish, _userEndpoint);

            //Sync; wait for the registration to complete.
            _autoResetEvent.WaitOne();


            //Setup the conversation and place the call.
            ConversationSettings convSettings = new ConversationSettings();

            convSettings.Priority = _conversationPriority;
            convSettings.Subject  = _conversationSubject;
            //Conversation represents a collection of modalities in the context of a dialog with one or multiple callees.
            Conversation conversation = new Conversation(_userEndpoint, convSettings);

            _audioVideoCall = new AudioVideoCall(conversation);

            //Call: StateChanged: Only hooked up for logging.
            _audioVideoCall.StateChanged += new EventHandler <CallStateChangedEventArgs>(audioVideoCall_StateChanged);

            //Subscribe for the flow configuration requested event; the flow will be used to send the media.
            //Ultimately, as a part of the callback, the media will be sent/recieved.
            _audioVideoCall.AudioVideoFlowConfigurationRequested += this.audioVideoCall_FlowConfigurationRequested;


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

            //Sync; wait for the call to complete.
            _autoResetEvent.WaitOne();

            // Shutdown the platform
            _collabPlatform.BeginShutdown(EndPlatformShutdown, _collabPlatform);

            //Wait for shutdown to occur.
            _autoResetShutdownEvent.WaitOne();
        }
Exemplo n.º 22
0
        //#endregion


        /// <summary>
        /// Initialize application endpoint
        /// </summary>
        private void StartEndpoint()
        {
            try
            {
                if (!useUserEndPoint)
                {
                    this.logger.Log("Setting up application end point");


                    var settings = new ApplicationEndpointSettings(
                        ownerUri: this.trustedContactUri,
                        proxyHost: this.lyncServer,
                        proxyPort: 0);

                    settings.IsDefaultRoutingEndpoint            = true;
                    settings.AutomaticPresencePublicationEnabled = true;
                    settings.Presence.PresentityType             = FastHelpServerApp.ApplicationPresentityType;
                    settings.Presence.Description = FastHelpServerApp.ApplicationPresentityTypeDescription;

                    this.applicationEndpoint = new ApplicationEndpoint(this.collabPlatform, settings);
                }
                else
                {
                    this.logger.Log("Setting up user end point");

                    var userURI      = ConfigurationManager.AppSettings["UserURI"];
                    var userName     = ConfigurationManager.AppSettings["UserName"];
                    var userPassword = ConfigurationManager.AppSettings["Password"];
                    var userDomain   = ConfigurationManager.AppSettings["UserDomain"];
                    var poolFQDN     = ConfigurationManager.AppSettings["PoolFQDN"];

                    var userEndpointSettings = new UserEndpointSettings(userURI, poolFQDN);

                    userEndpointSettings.AutomaticPresencePublicationEnabled = true;

                    if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(userPassword))
                    {
                        userEndpointSettings.Credential = System.Net.CredentialCache.DefaultNetworkCredentials;
                    }
                    else
                    {
                        var credential = new System.Net.NetworkCredential(userName, userPassword, userDomain);
                        userEndpointSettings.Credential = credential;
                    }

                    this.applicationEndpoint = new UserEndpoint(this.collabPlatform, userEndpointSettings);
                }

                this.applicationEndpoint.InnerEndpoint.AddFeatureParameter("isAcd");

                this.applicationEndpoint.RegisterForIncomingCall <AudioVideoCall>(this.AV_Received);
                this.applicationEndpoint.RegisterForIncomingCall <InstantMessagingCall>(this.IM_Received);

                this.logger.Log("Establishing the endpoint.");
                this.applicationEndpoint.EndEstablish(this.applicationEndpoint.BeginEstablish(null, null));
            }
            catch (InvalidOperationException ioe)
            {
                // InvalidOperationException will be thrown when the platform isn't started or the endpoint isn't established
                this.logger.Log("Invalid Operation Exception {0}", ioe);
                Console.WriteLine(ioe);
            }
            catch (ConnectionFailureException connFailEx)
            {
                // ConnectionFailureException will be thrown when the endpoint cannot connect to the server,
                //or the credentials are invalid.
                this.logger.Log("Connection Failure Exception {0}", connFailEx);
                Console.WriteLine(connFailEx);
            }
            catch (RegisterException regEx)
            {
                // RegisterException will be thrown when the endpoint cannot be registered (usually due to bad credentials).
                this.logger.Log("Register Exception  {0}", regEx);
                Console.WriteLine(regEx);
            }
            catch (AuthenticationException ae)
            {
                // AuthenticationException will be thrown when a general authentication-related problem occurred.
                this.logger.Log("Authentication Exception  {0}", ae);
                Console.WriteLine(ae);
            }
            catch (OperationTimeoutException ate)
            {
                // OperationTimeoutException will be thrown when server did not respond for Register request.
                this.logger.Log("Operation Timeout Exception {0}", ate);
                Console.WriteLine(ate);
            }
            catch (RealTimeException rte)
            {
                this.logger.Log("Operation Timeout Exception {0}", rte);
                Console.WriteLine(rte);
            }
        }
Exemplo n.º 23
0
        public void SendMessage(string[] targets, string subject, string message, InstantMessagePriority priority)
        {
            var cps = new ClientPlatformSettings(null, SipTransportType.Tls);
            var cp  = new CollaborationPlatform(cps);
            var us  = new UserEndpointSettings(string.Format("sip:{0}", _username))
            {
                Credential = new NetworkCredential(_username, _password)
            };

            log.DebugFormat("OwnerUri: {0}", us.OwnerUri);
            var ue = new UserEndpoint(cp, us);

            // start up the platform
            Task.Factory.FromAsync(ue.Platform.BeginStartup, ue.Platform.EndStartup, null).Wait();
            Task.Factory.FromAsync <SipResponseData>(ue.BeginEstablish, ue.EndEstablish, null).Wait();

            // send the messages
            var tasks = targets.Select(t =>
            {
                var cts = new CancellationTokenSource(TimeSpan.FromMinutes(2));
                var tsc = new TaskCompletionSource <SendInstantMessageResult>();
                cts.Token.Register(() => tsc.TrySetCanceled());

                var sent   = false;
                var doSend = new Action <InstantMessagingFlow>(flow =>
                {
                    if (sent || flow.State != MediaFlowState.Active)
                    {
                        return;
                    }
                    sent = true;
                    Task.Factory.FromAsync <string, SendInstantMessageResult>(
                        flow.BeginSendInstantMessage,
                        flow.EndSendInstantMessage,
                        message,
                        null)
                    .ContinueWith(
                        r =>
                    {
                        if (r.IsCanceled)
                        {
                            tsc.TrySetCanceled();
                        }
                        else if (r.IsFaulted)
                        {
                            tsc.TrySetException(r.Exception);
                        }
                        else
                        {
                            tsc.TrySetResult(r.Result);
                        }
                    });
                });

                var p = priority == InstantMessagePriority.Emergency
                    ? ConversationPriority.Emergency
                    : priority == InstantMessagePriority.Urgent
                        ? ConversationPriority.Urgent
                        : priority == InstantMessagePriority.NonUrgent
                            ? ConversationPriority.NonUrgent
                            : ConversationPriority.Normal;
                var c = new Conversation(ue, new ConversationSettings()
                {
                    Priority = p
                });
                var im = new InstantMessagingCall(c);
                im.InstantMessagingFlowConfigurationRequested += (sender, args) =>
                {
                    doSend(im.Flow);
                    im.Flow.StateChanged += (o, eventArgs) =>
                    {
                        doSend(im.Flow);
                    };
                };
                Task.Factory.FromAsync <string, ToastMessage, CallEstablishOptions, CallMessageData>(im.BeginEstablish,
                                                                                                     im.EndEstablish, "sip:" + t, new ToastMessage(subject), null, null).ContinueWith(r =>
                {
                    if (r.IsCanceled)
                    {
                        tsc.TrySetCanceled();
                    }
                    else if (r.IsFaulted)
                    {
                        tsc.TrySetException(r.Exception);
                    }
                });
                return(tsc.Task);
            }).ToArray();

            // wait for the messages to go
            Task.WhenAll(tasks).ContinueWith(r =>
            {
                if (r.IsCanceled)
                {
                    log.DebugFormat("Message send was cancelled");
                }
                else if (r.IsFaulted)
                {
                    log.WarnFormat("Message send failed: {0}", r.Exception);
                }
                Task.Factory.FromAsync(ue.Platform.BeginShutdown, ue.Platform.EndShutdown, null).Wait();
            });
        }