예제 #1
0
        public override async Task<AcdActionResult> Execute(LocalEndpoint localEndpoint, AudioVideoCall call, CancellationToken cancellationToken)
        {
            if (Endpoint == null)
                return AcdActionResult.Continue;

            // only allow one call through to a contact at a time
            if (Busy)
                return AcdActionResult.Continue;

            try
            {
                Busy = true;

                var available = IgnorePresence || await GetAvailableAsync(localEndpoint, cancellationToken);
                if (available)
                    return await base.Execute(localEndpoint, call, cancellationToken);
            }
            catch (OperationCanceledException)
            {
                // ignore
            }
            finally
            {
                Busy = false;
            }

            return AcdActionResult.Continue;
        }
예제 #2
0
 /// <summary>
 /// Initializes a new instance.
 /// </summary>
 /// <param name="endpoint"></param>
 /// <param name="holdUri"></param>
 /// <param name="conferenceId"></param>
 public QueueHoldConference(LocalEndpoint endpoint, string holdUri, string conferenceId = null)
 {
     this.sync = new AsyncLock();
     this.endpoint = endpoint;
     this.holdUri = holdUri;
     this.conferenceId = conferenceId;
 }
예제 #3
0
        public void Reading_without_receiving_should_return_the_same_set_of_messages()
        {
            LocalEndpoint.Send(new PingMessage());

            int count = 0;

            foreach (var selector in LocalEndpoint.SelectiveReceive(1.Seconds()))
            {
                object message = selector.DeserializeMessage();
                Assert.IsInstanceOfType(typeof(PingMessage), message);

                count++;
            }

            int secondCount = 0;

            foreach (var selector in LocalEndpoint.SelectiveReceive(1.Seconds()))
            {
                object message = selector.DeserializeMessage();
                Assert.IsInstanceOfType(typeof(PingMessage), message);

                secondCount++;
            }

            Assert.AreEqual(1, count);
            Assert.AreEqual(1, secondCount);
        }
예제 #4
0
        // Callback for ApplicationEndpoint's BeginEstablish().
        private void EndEndpointEstablish(IAsyncResult ar)
        {
            LocalEndpoint currentEndpoint = ar.AsyncState as LocalEndpoint;

            try
            {
                currentEndpoint.EndEstablish(ar);
            }
            catch (ConnectionFailureException connFailEx)
            {
                // ConnectionFailureException will be thrown when the endpoint
                // cannot connect to the server.
                // TODO (Left to the reader): Write actual handling code for the
                // occurrence.
                Console.WriteLine("ConnectionFailure Exception: " + connFailEx.ToString());
            }
            catch (RealTimeException realTimeEx)
            {
                // RealTimeException may be thrown as a result of any UCMA
                // operation.
                // TODO (Left to the reader): Write actual handling code for the
                // occurrence.
                Console.WriteLine("RealTimeException : " + realTimeEx.ToString());
            }
        }
        public void The_message_should_not_exist_in_the_input_queue()
        {
            _future.IsAvailable(3.Seconds())
            .ShouldBeTrue();

            LocalEndpoint.ShouldNotContain(_ping);
        }
예제 #6
0
        public override async Task<AcdActionResult> Execute(LocalEndpoint localEndpoint, AudioVideoCall call, CancellationToken cancellationToken)
        {
            var cs = new CancellationTokenSource();
            var ct = CancellationTokenSource.CreateLinkedTokenSource(cs.Token, cancellationToken).Token;

            // initiate agent calls
            var ops = this
                .Select(async i =>
                {
                    try
                    {
                        // we were canceled
                        if (ct.IsCancellationRequested)
                            return AcdActionResult.Continue;

                        // initiate delegate, cancel the rest on success
                        var result = await i.Execute(localEndpoint, call, ct);
                        if (result)
                            cs.Cancel();

                        return result;
                    }
                    catch (OperationCanceledException)
                    {
                        // ignore
                    }

                    return AcdActionResult.Continue;
                })
                .ToArray();

            // did any complete the call
            return (await Task.WhenAll(ops))
                .Any(i => i);
        }
예제 #7
0
        public void Should_process_the_messages_in_order_and_not_at_the_same_time()
        {
            Guid transactionId = NewId.NextGuid();

            Trace.WriteLine("Creating transaction for " + transactionId);

            int startValue = 1;

            var startConcurrentSaga = new StartConcurrentSaga
            {
                CorrelationId = transactionId, Name = "Chris", Value = startValue
            };

            LocalBus.Publish(startConcurrentSaga);
            LocalBus.Publish(startConcurrentSaga);
            Trace.WriteLine("Just published the start message");

            _sagaRepository.ShouldContainSaga(transactionId).ShouldNotBeNull();

            int nextValue = 2;
            var continueConcurrentSaga = new ContinueConcurrentSaga {
                CorrelationId = transactionId, Value = nextValue
            };

            LocalBus.Publish(continueConcurrentSaga);
            Trace.WriteLine("Just published the continue message");

            _sagaRepository.ShouldContainSaga(x => x.CorrelationId == transactionId && x.Value == nextValue).
            ShouldNotBeNull();

            Thread.Sleep(8000);

            LocalEndpoint.ShouldNotContain <StartConcurrentSaga>();
            LocalErrorEndpoint.ShouldContain <StartConcurrentSaga>();
        }
예제 #8
0
 private void PurgeEndpoint()
 {
     foreach (var selector in LocalEndpoint.SelectiveReceive(10.Milliseconds()))
     {
         selector.AcceptMessage();
     }
 }
예제 #9
0
        // Callback for ApplicationEndpoint's BeginEstablish().
        static void EndEndpointEstablish(IAsyncResult ar)
        {
            LocalEndpoint currentEndpoint = ar.AsyncState as LocalEndpoint;

            try
            {
                currentEndpoint.EndEstablish(ar);

                _currentEndpoint = currentEndpoint;

                // Here, we have the endpoint fully established
                // So let's get started
                _currentEndpoint.RegisterForIncomingCall <AudioVideoCall>(IncomingAVCallReceived);

                _locations.Add(new Location(0, "Airport", ConfigurationManager.AppSettings["AirportRoomMusic"], _currentEndpoint));
                _locations.Add(new Location(1, "Bus", ConfigurationManager.AppSettings["BusRoomMusic"], _currentEndpoint));
                _locations.Add(new Location(2, "Outdoor", ConfigurationManager.AppSettings["OutdoorRoomMusic"], _currentEndpoint));
            }
            catch (ConnectionFailureException connFailEx)
            {
                Console.WriteLine("ConnectionFailure Exception: " + connFailEx.ToString());
            }
            catch (RealTimeException realTimeEx)
            {
                Console.WriteLine("RealTimeException : " + realTimeEx.ToString());
            }
            catch (Exception Ex)
            {
                Console.WriteLine("Exception : " + Ex.ToString());
            }
        }
예제 #10
0
        public override int GetHashCode()
        {
            int h = 1;

            h *= 1000003;
            h ^= TraceId.GetHashCode();
            h *= 1000003;
            h ^= (ParentId == null) ? 0 : ParentId.GetHashCode();
            h *= 1000003;
            h ^= Id.GetHashCode();
            h *= 1000003;
            h ^= Kind.GetHashCode();
            h *= 1000003;
            h ^= (Name == null) ? 0 : Name.GetHashCode();
            h *= 1000003;
            h ^= (int)(h ^ ((Timestamp >> 32) ^ Timestamp));
            h *= 1000003;
            h ^= (int)(h ^ ((Duration >> 32) ^ Duration));
            h *= 1000003;
            h ^= (LocalEndpoint == null) ? 0 : LocalEndpoint.GetHashCode();
            h *= 1000003;
            h ^= (RemoteEndpoint == null) ? 0 : RemoteEndpoint.GetHashCode();
            h *= 1000003;
            h ^= Annotations.GetHashCode();
            h *= 1000003;
            h ^= Tags.GetHashCode();
            h *= 1000003;
            return(h);
        }
예제 #11
0
        public override bool Equals(object o)
        {
            if (o == this)
            {
                return(true);
            }

            if (!(o is ZipkinSpan))
            {
                return(false);
            }

            ZipkinSpan that = (ZipkinSpan)o;

            return(TraceId.Equals(that.TraceId) &&
                   ((ParentId == null) ? (that.ParentId == null) : ParentId.Equals(that.ParentId)) &&
                   Id.Equals(that.Id) &&
                   Kind.Equals(that.Kind) &&
                   ((Name == null) ? (that.Name == null) : Name.Equals(that.Name)) &&
                   (Timestamp == that.Timestamp) &&
                   (Duration == that.Duration) &&
                   ((LocalEndpoint == null) ? (that.LocalEndpoint == null) : LocalEndpoint.Equals(that.LocalEndpoint)) &&
                   ((RemoteEndpoint == null) ? (that.RemoteEndpoint == null) : RemoteEndpoint.Equals(that.RemoteEndpoint)) &&
                   Annotations.SequenceEqual(that.Annotations) &&
                   Tags.SequenceEqual(that.Tags) &&
                   (Debug == that.Debug) &&
                   (Shared == that.Shared));
        }
예제 #12
0
        private void EndEndpointEstablish(IAsyncResult ar)
        {
            LocalEndpoint currentEndpoint = ar.AsyncState as LocalEndpoint;

            try
            {
                currentEndpoint.EndEstablish(ar);
            }
            catch (AuthenticationException authEx)
            {
                // AuthenticationException will be thrown when the credentials are invalid.
                NonBlockingConsole.WriteLine(authEx.Message);
                throw;
            }
            catch (ConnectionFailureException connFailEx)
            {
                // ConnectionFailureException will be thrown when the endpoint cannot connect to the server, or the credentials are invalid.
                NonBlockingConsole.WriteLine(connFailEx.Message);
                throw;
            }
            catch (InvalidOperationException iOpEx)
            {
                // InvalidOperationException will be thrown when the endpoint is not in a valid state to connect. To connect, the platform must be started and the Endpoint Idle.
                NonBlockingConsole.WriteLine(iOpEx.Message);
                throw;
            }
            finally
            {
                // Again, just for sync. reasons.
                _endpointInitCompletedEvent.Set();
            }
        }
예제 #13
0
 public override Task<AcdActionResult> Execute(LocalEndpoint localEndpoint, AudioVideoCall call, CancellationToken cancellationToken)
 {
     if (Schedule == null || Schedule.InSchedule(DateTime.Now))
         return base.Execute(localEndpoint, call, cancellationToken);
     else
         return AcdActionResult.ContinueTask;
 }
 public static Task <SipResponseData> EstablishAsync(this
                                                     LocalEndpoint endpoint)
 {
     return(Task <SipResponseData> .Factory.FromAsync(
                endpoint.BeginEstablish,
                endpoint.EndEstablish, null));
 }
예제 #15
0
        /// <summary>
        /// Constructor of a presence watcher supporting persistent, polling and on-demand subscriptions 
        /// to presence categories published by specified remote presentities. on-demand subscription is 
        /// also known as presence query. The code here also handles self-presence.
        /// </summary>
        /// <param name="endpoint"></param>
        public PresenceWatcher(LocalEndpoint endpoint)
        {
            _remotePresenceServices = endpoint.PresenceServices;

            // RemotePresenceView for persitent subscription:
            RemotePresenceViewSettings rpvs = new RemotePresenceViewSettings();
            rpvs.SubscriptionMode = RemotePresenceViewSubscriptionMode.Persistent;
            
            _persistentPresenceView = new RemotePresenceView(endpoint, rpvs);
            _persistentPresenceView.PresenceNotificationReceived += new EventHandler<RemotePresentitiesNotificationEventArgs>(PersistentPresenceReceivedEventHandler);
            
            _persistentPresenceView.SubscriptionStateChanged += new EventHandler<RemoteSubscriptionStateChangedEventArgs>(PersistentSubscriptionStateChangedEventHandler);
            
            // RemotePresenceView for polling subscription
            rpvs = new RemotePresenceViewSettings();
            rpvs.SubscriptionMode = RemotePresenceViewSubscriptionMode.Polling;
            rpvs.PollingInterval = new TimeSpan(0, 5, 0);  // every 5 minutes
            _pollingPresenceView = new RemotePresenceView(endpoint, rpvs);

            _pollingPresenceView.SetPresenceSubscriptionCategoriesForPolling(new string[] { "contactCard", "state", "note", "noteHistory" });
            
            _pollingPresenceView.PresenceNotificationReceived += new EventHandler<RemotePresentitiesNotificationEventArgs>(PollingPresenceReceivedEventHandler);

            _pollingPresenceView.SubscriptionStateChanged += new EventHandler<RemoteSubscriptionStateChangedEventArgs>(PollingSubscriptionStateChangedEventHandler);

        }
예제 #16
0
        public override async Task<AcdActionResult> Execute(LocalEndpoint localEndpoint, AudioVideoCall call, CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    // record start time
                    var t = DateTime.UtcNow;

                    // execute delegate
                    if (await base.Execute(localEndpoint, call, cancellationToken))
                        return true;

                    // do not execute more than once a second
                    if (DateTime.UtcNow - t < TimeSpan.FromSeconds(1))
                        await Task.Delay(1000, cancellationToken);
                }
                catch (OperationCanceledException)
                {
                    // ignore
                }
            }

            return false;
        }
예제 #17
0
 /// <summary>
 /// Constructor to create the poller.
 /// </summary>
 /// <param name="endpoint">Endpoint. Cannot be null.</param>
 /// <param name="contactCenterUri">Contact center uri. Cannot be null or empty.</param>
 /// <param name="timerWheel">Timerwheel</param>
 internal ContactCenterServicePoller(LocalEndpoint endpoint, string contactCenterUri, TimerWheel timerWheel)
 {
     Debug.Assert(null != endpoint, "Endpoint is null");
     Debug.Assert(!String.IsNullOrEmpty(contactCenterUri), "Contact center uri is null or empty");
     m_endpoint         = endpoint;
     m_contactCenterUri = contactCenterUri;
     m_timerWheel       = timerWheel;
 }
 public static Task <ProvisioningData> GetProvisioningDataAsync(this
                                                                LocalEndpoint endpoint)
 {
     return(Task <ProvisioningData> .Factory.FromAsync(
                endpoint.BeginGetProvisioningData,
                endpoint.EndGetProvisioningData,
                null));
 }
 public static Task <SipResponseData> EstablishAsync(this
                                                     LocalEndpoint endpoint,
                                                     IEnumerable <SignalingHeader> additionalHeaders)
 {
     return(Task <SipResponseData> .Factory.FromAsync(
                endpoint.BeginEstablish,
                endpoint.EndEstablish, additionalHeaders, null));
 }
예제 #20
0
파일: AcdDebug.cs 프로젝트: wasabii/UcmaKit
        public override async Task<AcdActionResult> Execute(LocalEndpoint localEndpoint, AudioVideoCall call, CancellationToken cancellationToken)
        {
            Trace.TraceInformation("Debug: {0} start", Name);
            await Task.Delay(TimeSpan.FromSeconds(random.Next(3, 30)), cancellationToken);
            var r = cancellationToken.IsCancellationRequested ? false : (random.Next(1, 100) <= 20);
            Trace.TraceInformation("Debug: {0} stop {1}", Name, r);

            return r;
        }
예제 #21
0
 protected void ConstructTestSubject()
 {
     ChannelUnderTest = new OneWayPullChannel
                        <LocalTestResource, RemoteTestResource, int, ItemMatch <LocalTestResource, RemoteTestResource> >(
         ChannelConfig,
         Plumber,
         () => Task.FromResult(LocalEndpoint.ReadAll().AsEnumerable()),
         () => Task.FromResult(RemoteEndpoint.ReadAll().AsEnumerable()));
 }
        /// <summary>
        /// Creates new Contact center discovery async result.
        /// </summary>
        /// <param name="localEndpoint"></param>
        /// <param name="targetUri"></param>
        /// <param name="localContactHeaderValue"></param>
        internal ContactCenterDiscoveryAsyncResult(LocalEndpoint localEndpoint, string targetUri, AsyncCallback userCallback, object state)
            : base(userCallback, state)
        {
            Debug.Assert(null != localEndpoint, "Local endpoint is null");
            Debug.Assert(!String.IsNullOrEmpty(targetUri), "Target uri is null or empty");

            m_endpoint  = localEndpoint;
            m_targetUri = targetUri;
        }
예제 #23
0
        /// <summary>
        /// Endpoint state changed event handler
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">Event args.</param>
        private void Endpoint_StateChanged(object sender, LocalEndpointStateChangedEventArgs e)
        {
            LocalEndpoint endpoint = sender as LocalEndpoint;

            Helper.Logger.Info("Endpoint {0} state changed from {1} to {2}. Reason = {3}.", endpoint.OwnerUri, e.PreviousState, e.State, e.Reason);

            if (e.State == LocalEndpointState.Terminating)
            {
                //Unregister event handlers.
                this.UnregisterEndpointEventHandlers(endpoint);
            }
        }
예제 #24
0
        public void Reading_from_an_empty_queue_should_just_return_an_empty_enumerator()
        {
            int count = 0;

            foreach (var selector in LocalEndpoint.SelectiveReceive(1.Seconds()))
            {
                selector.AcceptMessage();
                count++;
            }

            Assert.AreEqual(0, count);
        }
예제 #25
0
파일: AcdDelay.cs 프로젝트: wasabii/UcmaKit
        public override async Task<AcdActionResult> Execute(LocalEndpoint localEndpoint, AudioVideoCall call, CancellationToken cancellationToken)
        {
            try
            {
                await Task.Delay(Duration, cancellationToken);
            }
            catch (OperationCanceledException)
            {
                // ignore
            }

            return AcdActionResult.Continue;
        }
예제 #26
0
        public async Task ShouldBreakOutOfSynchronizationWhenDataSource2NullData()
        {
            // Should I throw an exception if one of the data providers returns null? I simply can not proceed.
            // Silently simply stepping out of the execution is not really informative.
            ChannelUnderTest = new OneWayPullChannel
                               <LocalTestResource, RemoteTestResource, int, ItemMatch <LocalTestResource, RemoteTestResource> >(
                ChannelConfig,
                Plumber,
                () => Task.FromResult(LocalEndpoint.ReadAll().AsEnumerable()),
                () => Task.FromResult((IEnumerable <RemoteTestResource>)null));

            await ChannelUnderTest.Synchronize();
        }
예제 #27
0
        public void Reading_a_single_message_should_return_one_message_selector()
        {
            LocalEndpoint.Send(new PingMessage());

            int count = 0;

            foreach (var selector in LocalEndpoint.SelectiveReceive(1.Seconds()))
            {
                selector.AcceptMessage();
                count++;
            }

            Assert.AreEqual(1, count);
        }
예제 #28
0
        public async Task ShouldSynchNewDataFromRemote()
        {
            // First just make a channel that we can call synch on.
            await ChannelUnderTest.Synchronize();

/*            var synched1 = localEndpoint.Read(1);
 *          Assert.IsNotNull(synched1);
 *          Assert.AreEqual(TestData.RemoteResults[0].Name, synched1.Name);
 *
 *          Assert.IsNull(localEndpoint.Read(2));*/

            var synched3 = LocalEndpoint.Read(3);

            Assert.IsNotNull(synched3);
            Assert.AreEqual(TestData.RemoteResults[1].Name, synched3.Name);
        }
        protected override void TeardownContext()
        {
            LocalBus.Dispose();
            LocalBus = null;

            RemoteBus.Dispose();
            RemoteBus = null;

            LocalEndpoint.Dispose();
            LocalEndpoint = null;

            LocalErrorEndpoint.Dispose();
            LocalErrorEndpoint = null;

            base.TeardownContext();
        }
        public void The_exception_should_not_disrupt_the_flow_of_messages()
        {
            CrashingService service = new CrashingService();

            LocalBus.SubscribeInstance(service);

            LocalEndpoint.Send(new BogusMessage());

            CrashingService.Received.WaitOne(5.Seconds(), true).ShouldBeTrue("No message received");

            CrashingService.Received.Reset();

            LocalEndpoint.Send(new LegitMessage());

            CrashingService.LegitReceived.WaitOne(5.Seconds(), true).ShouldBeTrue("No message received");
        }
예제 #31
0
파일: Program.cs 프로젝트: kehinze/Hermes
        static void Main(string[] args)
        {
            var endpoint = new LocalEndpoint();
            endpoint.Start();
            var bus = Settings.RootContainer.GetInstance<IInMemoryBus>();

            var stopwatch = new Stopwatch();
            stopwatch.Start();

            Parallel.ForEach(Iterations, i =>
            {
                bus.Execute(new AddRecordToDatabase(i + 1));
            });

            stopwatch.Stop();
            Console.WriteLine(TimeSpan.FromTicks(stopwatch.ElapsedTicks));
            Console.ReadKey();
        }
예제 #32
0
파일: AcdHold.cs 프로젝트: wasabii/UcmaKit
        public override async Task<AcdActionResult> Execute(LocalEndpoint localEndpoint, AudioVideoCall call, CancellationToken cancellationToken)
        {
            using (var hold = new AcdHoldContext(Audio))
            {
                // initiate delayed hold operation
                var s = new CancellationTokenSource();
                var h = Hold(hold, call, s.Token);

                // invoke next action
                var r = await base.Execute(localEndpoint, call, cancellationToken);

                // wait for delayed hold operation to exit
                s.Cancel();
                await h;

                return r;
            }
        }
예제 #33
0
    public override int GetHashCode()
    {
        int hash = 1;

        if (ErrorMsg.Length != 0)
        {
            hash ^= ErrorMsg.GetHashCode();
        }
        if (localEndpoint_ != null)
        {
            hash ^= LocalEndpoint.GetHashCode();
        }
        hash ^= metaNodes_.GetHashCode();
        if (_unknownFields != null)
        {
            hash ^= _unknownFields.GetHashCode();
        }
        return(hash);
    }
예제 #34
0
        //#region Presence
        //// Registered event handler for the ApplicationEndpointOwnerDiscovered
        //// event on the CollaborationPlatform for the provisioned application.
        private void Platform_ApplicationEndpointOwnerDiscovered(object sender,
                                                                 ApplicationEndpointSettingsDiscoveredEventArgs e)
        {
            collabPlatform.UnregisterForApplicationEndpointSettings(Platform_ApplicationEndpointOwnerDiscovered);
            ApplicationEndpointSettings settings = e.ApplicationEndpointSettings;

            this.logger.Log("Publishing Presence");
            //Set the endpoint presence to appear as always online
            InitializePublishAlwaysOnlineSettings(settings);
            this.applicationEndpoint = new ApplicationEndpoint(this.collabPlatform, settings);

            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));
        }
예제 #35
0
        public override async Task<AcdActionResult> Execute(LocalEndpoint localEndpoint, AudioVideoCall call, CancellationToken cancellationToken)
        {
            foreach (var dispatcher in this)
            {
                if (cancellationToken.IsCancellationRequested)
                    return AcdActionResult.Continue;

                try
                {
                    if (await dispatcher.Execute(localEndpoint, call, cancellationToken))
                        return AcdActionResult.Complete;
                }
                catch (OperationCanceledException)
                {
                    // ignore
                }
            }

            return AcdActionResult.Continue;
        }
예제 #36
0
        public void Receiving_the_message_and_accepting_it_should_make_it_go_away()
        {
            LocalEndpoint.Send(new PingMessage());

            foreach (var selector in LocalEndpoint.SelectiveReceive(1.Seconds()))
            {
                object message = selector.DeserializeMessage();
                Assert.IsInstanceOfType(typeof(PingMessage), message);

                Assert.IsTrue(selector.AcceptMessage());
            }

            int count = 0;

            foreach (var selector in LocalEndpoint.SelectiveReceive(1.Seconds()))
            {
                count++;
            }

            Assert.AreEqual(0, count);
        }
예제 #37
0
        public override async Task<AcdActionResult> Execute(LocalEndpoint localEndpoint, AudioVideoCall call, CancellationToken cancellationToken)
        {
            // if we have a timeout, combine with existing cancellation token
            if (Length.TotalMilliseconds > 0)
                cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(
                    cancellationToken,
                    new CancellationTokenSource(Length).Token)
                    .Token;

            // send to base dispatcher
            try
            {
                return await base.Execute(localEndpoint, call, cancellationToken);
            }
            catch (OperationCanceledException)
            {
                // ignore
            }

            return false;
        }
예제 #38
0
 public void MergeFrom(JoinClusterResult other)
 {
     if (other == null)
     {
         return;
     }
     if (other.ErrorMsg.Length != 0)
     {
         ErrorMsg = other.ErrorMsg;
     }
     if (other.localEndpoint_ != null)
     {
         if (localEndpoint_ == null)
         {
             localEndpoint_ = new global::PeerEndpoint();
         }
         LocalEndpoint.MergeFrom(other.LocalEndpoint);
     }
     metaNodes_.Add(other.metaNodes_);
     _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
 }
예제 #39
0
        private static void ConfigureWebApi(IAppBuilder app, HttpConfiguration config)
        {
            config.Formatters.Remove(config.Formatters.XmlFormatter);
            config.MapHttpAttributeRoutes();
            var corsAttr = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(corsAttr);
            config.Routes.MapHttpRoute(
                name: RouteNames.DefaultApi,
                routeTemplate: "api/{controller}/{id}",
                defaults: new
                {
                    id = RouteParameter.Optional
                });
            app.UseCors(CorsOptions.AllowAll);

            app.UseWebApi(config);
            var endpoint = new LocalEndpoint();
            endpoint.Start();
            config.DependencyResolver = ((WebApiAutofacAdapter)Settings.RootContainer).BuildAutofacDependencyResolver();
            GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
        }
예제 #40
0
        /// <summary>
        /// Gets whether or not the contact is available.
        /// </summary>
        /// <param name="localEndpoint"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        async Task<bool> GetAvailableAsync(LocalEndpoint localEndpoint, CancellationToken cancellationToken)
        {
            // obtain presense state
            var presence = await localEndpoint
                .GetPresenceContext()
                .GetPresenceStateAsync(Endpoint.Uri, cancellationToken);
            
            // assume present if no status at all; failsafe
            if (presence == null)
                return true;

            // currently online
            if (presence.Availability == PresenceAvailability.IdleOnline ||
                presence.Availability == PresenceAvailability.None ||
                presence.Availability == PresenceAvailability.Online)
                return true;

            // active within 30 seconds
            if (DateTime.UtcNow - presence.LastActive <= TimeSpan.FromSeconds(30))
                return true;

            return false;
        }
예제 #41
0
        static void Main(string[] args)
        {
            var endpoint = new LocalEndpoint();
            endpoint.Start();
            var bus = Settings.RootContainer.GetInstance<IInMemoryBus>();

            var stopwatch = new Stopwatch();
            stopwatch.Start();

            foreach (var i in Iterations)
            {
                try
                {
                    bus.Execute(new AddRecordToDatabase(i + 1));
                }
                catch (Exception)
                {
                }
            }

            //Parallel.ForEach(Iterations, i =>
            //{
            //    try
            //    {
            //        bus.Execute(new AddRecordToDatabase(i + 1));
            //    }
            //    catch (Exception ex)
            //    {
            //        Console.WriteLine(ex.Message);
            //    }
            //});

            stopwatch.Stop();
            Console.WriteLine(TimeSpan.FromTicks(stopwatch.ElapsedTicks));
            Console.ReadKey();
        }
 public static Task TerminateAsync(this LocalEndpoint endpoint)
 {
     return(Task.Factory.FromAsync(endpoint.BeginTerminate,
                                   endpoint.EndTerminate, null));
 }
예제 #43
0
 /// <summary>
 /// Attempts to handle the call. Returns <c>true</c> if the call has been successfully handled.
 /// </summary>
 /// <param name="localEndpoint"></param>
 /// <param name="call"></param>
 /// <param name="cancellationToken"></param>
 /// <returns></returns>
 public abstract Task<AcdActionResult> Execute(LocalEndpoint localEndpoint, AudioVideoCall call, CancellationToken cancellationToken);
예제 #44
0
        public override async Task<AcdActionResult> Execute(LocalEndpoint localEndpoint, AudioVideoCall call, CancellationToken cancellationToken)
        {
            if (Endpoint == null)
                return AcdActionResult.Continue;

            // extract information from incoming caller
            var callParticipant = call.RemoteEndpoint.Participant;
            var callAddress = new RealTimeAddress(callParticipant.Uri, localEndpoint.DefaultDomain, localEndpoint.PhoneContext);
            var callSipUri = new SipUriParser(callAddress.Uri);
            callSipUri.RemoveParameter(new SipUriParameter("user", "phone"));
            var callUri = callSipUri.ToString();
            var callPhoneUri = callParticipant.OtherPhoneUri;
            var callName = callParticipant.DisplayName;

            // impersonate incoming caller to agent
            var remoteConversation = new Conversation(localEndpoint);
            remoteConversation.Impersonate(callUri, callPhoneUri, callName);

            // establish call to endpoint
            var remoteCall = new AudioVideoCall(remoteConversation);
            var remoteOpts = new CallEstablishOptions();
            remoteOpts.Transferor = localEndpoint.OwnerUri;
            remoteOpts.Headers.Add(new SignalingHeader("Ms-Target-Class", "secondary"));

            // initiate call with duration
            var destCallT = remoteCall.EstablishAsync(Endpoint.Uri, remoteOpts, cancellationToken);

            try
            {
                // wait for agent call to complete
                await destCallT;
            }
            catch (OperationCanceledException)
            {
                // ignore
            }
            catch (RealTimeException)
            {
                // ignore
            }

            // ensure two accepted transfers cannot both complete
            using (var lck = await call.GetContext<AsyncLock>().LockAsync())
                if (call.State == CallState.Established)
                    if (remoteCall.State == CallState.Established)
                    {
                        var participant = remoteConversation.RemoteParticipants.FirstOrDefault();
                        if (participant != null)
                        {
                            var endpoint = participant.GetEndpoints().FirstOrDefault(i => i.EndpointType == EndpointType.User);
                            if (endpoint != null)
                            {
                                var ctx = new ConversationContextChannel(remoteConversation, endpoint);

                                // establish conversation context with application
                                await ctx.EstablishAsync(
                                    new Guid("FA44026B-CC48-42DA-AAA8-B849BCB43A21"), 
                                    new ConversationContextChannelEstablishOptions());

                                // send context data
                                await ctx.SendDataAsync(
                                    new ContentType("text/plain"), 
                                    Encoding.UTF8.GetBytes("Id=123"));
                            }
                        }

                        return await TransferAsync(call, remoteCall);
                    }

            // terminate outbound call if still available
            if (remoteCall.State != CallState.Terminating &&
                remoteCall.State != CallState.Terminated)
                await remoteCall.TerminateAsync();

            // we could not complete the transfer attempt
            return AcdActionResult.Continue;
        }
예제 #45
0
 public void The_message_should_not_exist_in_the_input_queue()
 {
     LocalEndpoint.ShouldNotContain(_ping);
 }
예제 #46
0
 /// <summary>
 /// Initializes a new instance.
 /// </summary>
 /// <param name="endpoint"></param>
 public QueueAgentConference(LocalEndpoint endpoint)
 {
     this.sync = new AsyncLock();
     this.endpoint = endpoint;
 }
예제 #47
0
        public Location(int id, string name, string fileName, LocalEndpoint endpoint)
        {
            if (!File.Exists(fileName))
                throw new FileNotFoundException(fileName);

            _id = id;
            _Name = name;
            _FileName = fileName;
            _Endpoint = endpoint;

            ConferenceScheduleInformation csi = new ConferenceScheduleInformation()
            {
                AccessLevel = ConferenceAccessLevel.Everyone,
                Description = _Name,
                ExpiryTime = DateTime.Now.AddYears(5),
                AutomaticLeaderAssignment = AutomaticLeaderAssignment.Everyone
            };

            csi.Mcus.Add(new ConferenceMcuInformation(McuType.AudioVideo));

            _Endpoint.ConferenceServices.BeginScheduleConference(csi,
                ar =>
                {
                    try
                    {
                        _conference = _Endpoint.ConferenceServices.EndScheduleConference(ar);

                        Log("Conference " + _conference.ConferenceId + " scheduled. Starting music...");

                        Log(_conference.ConferenceUri);

                        ConversationSettings cs = new ConversationSettings()
                        {
                            Subject = _Name
                        };

                        _conversation = new Conversation(_Endpoint, cs);

                        ConferenceJoinOptions cjo = new ConferenceJoinOptions()
                        {
                            JoinMode = JoinMode.TrustedParticipant
                        };

                        _conversation.ConferenceSession.BeginJoin(_conference.ConferenceUri,
                            cjo,
                            ar1 =>
                            {
                                try
                                {
                                    _conversation.ConferenceSession.EndJoin(ar1);

                                    _avCall = new AudioVideoCall(_conversation);
                                    _avCall.AudioVideoFlowConfigurationRequested +=
                                        new EventHandler<AudioVideoFlowConfigurationRequestedEventArgs>(_avCall_AudioVideoFlowConfigurationRequested);

                                    AudioVideoCallEstablishOptions options = new AudioVideoCallEstablishOptions()
                                    {
                                        UseGeneratedIdentityForTrustedConference = true,
                                        SupportsReplaces = CapabilitySupport.Supported
                                    };

                                    _avCall.BeginEstablish(
                                        options,
                                        ar2 =>
                                        {
                                            try
                                            {
                                                _avCall.EndEstablish(ar2);
                                            }
                                            catch (Exception ex)
                                            {
                                                Log(ex.ToString());
                                            }
                                        },
                                        null);
                                }
                                catch (Exception ex)
                                {
                                    Log(ex.ToString());
                                }
                            },
                            null);
                    }
                    catch (Exception ex)
                    {
                        Log(ex.ToString());
                    }
                },
                null);
        }
예제 #48
0
 public override Task<AcdActionResult> Execute(LocalEndpoint localEndpoint, AudioVideoCall call, CancellationToken cancellationToken)
 {
     return Action != null ? Action.Execute(localEndpoint, call, cancellationToken) : AcdActionResult.ContinueTask;
 }
예제 #49
0
 public LocalEndpoint(LocalEndpoint server)
 {
     this.server = server;
 }
예제 #50
0
 /// <summary>
 /// Initializes a new instance.
 /// </summary>
 /// <param name="endpoint"></param>
 internal RtcPresenceContext(LocalEndpoint endpoint)
 {
     Endpoint = endpoint;
 }
예제 #51
0
        // Callback for ApplicationEndpoint's BeginEstablish().
        static void EndEndpointEstablish(IAsyncResult ar)
        {
            LocalEndpoint currentEndpoint = ar.AsyncState as LocalEndpoint;
            try
            {
                currentEndpoint.EndEstablish(ar);

                _currentEndpoint = currentEndpoint;

                // Here, we have the endpoint fully established
                // So let's get started
                _currentEndpoint.RegisterForIncomingCall<AudioVideoCall>(IncomingAVCallReceived);

                _locations.Add(new Location(0, "Airport", ConfigurationManager.AppSettings["AirportRoomMusic"], _currentEndpoint));
                _locations.Add(new Location(1, "Bus", ConfigurationManager.AppSettings["BusRoomMusic"], _currentEndpoint));
                _locations.Add(new Location(2, "Outdoor", ConfigurationManager.AppSettings["OutdoorRoomMusic"], _currentEndpoint));
            }
            catch (ConnectionFailureException connFailEx)
            {
                Console.WriteLine("ConnectionFailure Exception: " + connFailEx.ToString());
            }
            catch (RealTimeException realTimeEx)
            {
                Console.WriteLine("RealTimeException : " + realTimeEx.ToString());
            }
            catch (Exception Ex)
            {
                Console.WriteLine("Exception : " + Ex.ToString());
            }
        }
예제 #52
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);
            }
        }
예제 #53
0
 /// <summary>
 /// Gets the hash code
 /// </summary>
 /// <returns>Hash code</returns>
 public override int GetHashCode()
 {
     unchecked // Overflow is fine, just wrap
     {
         var hashCode = 41;
         // Suitable nullity checks etc, of course :)
         if (TraceId != null)
         {
             hashCode = hashCode * 59 + TraceId.GetHashCode();
         }
         if (Name != null)
         {
             hashCode = hashCode * 59 + Name.GetHashCode();
         }
         if (ParentId != null)
         {
             hashCode = hashCode * 59 + ParentId.GetHashCode();
         }
         if (Id != null)
         {
             hashCode = hashCode * 59 + Id.GetHashCode();
         }
         if (Kind != null)
         {
             hashCode = hashCode * 59 + Kind.GetHashCode();
         }
         if (Timestamp != null)
         {
             hashCode = hashCode * 59 + Timestamp.GetHashCode();
         }
         if (Duration != null)
         {
             hashCode = hashCode * 59 + Duration.GetHashCode();
         }
         if (Debug != null)
         {
             hashCode = hashCode * 59 + Debug.GetHashCode();
         }
         if (Shared != null)
         {
             hashCode = hashCode * 59 + Shared.GetHashCode();
         }
         if (LocalEndpoint != null)
         {
             hashCode = hashCode * 59 + LocalEndpoint.GetHashCode();
         }
         if (RemoteEndpoint != null)
         {
             hashCode = hashCode * 59 + RemoteEndpoint.GetHashCode();
         }
         if (Annotations != null)
         {
             hashCode = hashCode * 59 + Annotations.GetHashCode();
         }
         if (Tags != null)
         {
             hashCode = hashCode * 59 + Tags.GetHashCode();
         }
         return(hashCode);
     }
 }