/// <summary>
        /// Prevents a default instance of the ApplicationEndpoint class from being created
        /// </summary>
        public ApplicationEndpoint(IClientPlatform platform, ApplicationEndpointSettings applicationEndpointSettings, IEventChannel eventChannel)
        {
            ClientPlatform     = platform;
            m_endpointSettings = applicationEndpointSettings;

            if (eventChannel != null)
            {
                m_eventChannel = eventChannel;
                m_eventChannel.HandleIncomingEvents += this.OnReceivedCallback;
            }

            Logger.Instance.Information("Initializing ApplicationEndpoint");

            var oauthTokenIdentitifier = new OAuthTokenIdentifier(
                Constants.PlatformAudienceUri,
                applicationEndpointSettings.ApplicationEndpointId.Domain);

            var tokenProvider = new AADServiceTokenProvider(platform.AADClientId.ToString(), Constants.AAD_AuthorityUri, platform.AADAppCertificate, platform.AADClientSecret);

            if (!platform.IsInternalPartner)
            {
                TokenMapper.RegisterNameSpaceHandling(Constants.DefaultResourceNamespace, Constants.PublicServiceResourceNamespace);
            }

            TokenMapper.RegisterTypesInAssembly(Assembly.GetAssembly(typeof(ApplicationsResource)));
            m_tokenProvider        = tokenProvider;
            m_oauthTokenIdentifier = oauthTokenIdentitifier;

            m_restfulClient = ((ClientPlatform)ClientPlatform).RestfulClientFactory.GetRestfulClient(m_oauthTokenIdentifier, m_tokenProvider);

            Logger.Instance.Information("ApplicationEndpoint Initialized!");
        }
Beispiel #2
0
        public static void InitializeTokenMapper()
        {
            if (!TestHelper.IsInternalApp)
            {
                TokenMapper.RegisterNameSpaceHandling(Constants.DefaultResourceNamespace, Constants.PublicServiceResourceNamespace);
            }

            TokenMapper.RegisterTypesInAssembly(Assembly.GetAssembly(typeof(ApplicationsResource)));
        }
Beispiel #3
0
        public async Task MapToToken_uuid_UuidToken()
        {
            // Arrange
            Mock <ILogger <TokenMapper> > logger = new Mock <ILogger <TokenMapper> >();
            ITokenMapper mapper = new TokenMapper(logger.Object);

            // Act
            Token token = await mapper.MapToTokenAsync("uuid");

            // Assert
            UuidToken uuidToken = Assert.IsAssignableFrom <UuidToken>(token);
        }
Beispiel #4
0
        public async Task MapToToken_utcnow_UtcNowTokenWithDefaultFormat()
        {
            // Arrange
            Mock <ILogger <TokenMapper> > logger = new Mock <ILogger <TokenMapper> >();
            ITokenMapper mapper = new TokenMapper(logger.Object);

            // Act
            Token token = await mapper.MapToTokenAsync("utcnow()");

            // Assert
            UtcNowToken uuidToken = Assert.IsAssignableFrom <UtcNowToken>(token);
        }
Beispiel #5
0
        public async Task MapToToken_variable_VariableToken()
        {
            // Arrange
            Mock <ILogger <TokenMapper> > logger = new Mock <ILogger <TokenMapper> >();
            ITokenMapper mapper = new TokenMapper(logger.Object);

            // Act
            Token token = await mapper.MapToTokenAsync("variable(myid)");

            // Assert
            Assert.IsAssignableFrom <VariableToken>(token);
        }
Beispiel #6
0
        public async Task <ActionResult> Index()
        {
            ViewData["IsUserLogged"] = HttpContext.Session.GetString("IsUserLogged");

            usersService.TokenDto = TokenMapper.ToDto(JsonConvert.DeserializeObject <TokenData>(HttpContext.Session.GetString("TokenData")));

            IList <UserDto> users = await usersService.GetUsers();

            List <User> userList = users.Select(userDto => UserMapper.ToEntity(userDto)).ToList();

            return(View(userList));
        }
Beispiel #7
0
        internal TfIdfVector CreateClassificationVector(TokenMapper mapper)
        {
            var result = ContentVector;

            if (TitleVector != null)
            {
                result = TitleVector.Add(ContentVector, 2);
            }

            result.ConvertTokenToId(mapper);

            return(result);
        }
        /// <summary>
        /// process conversation bridge participant events
        /// </summary>
        /// <param name="eventcontext"></param>
        /// <returns></returns>
        internal override bool ProcessAndDispatchEventsToChild(EventContext eventcontext)
        {
            //No child to dispatch any more, need to dispatch to child , process locally for message type
            if (string.Equals(eventcontext.EventEntity.Link.Token, TokenMapper.GetTokenName(typeof(BridgedParticipantResource))))
            {
                if (eventcontext.EventEntity.Relationship == EventOperation.Added)
                {
                    BridgedParticipantResource resource = this.ConvertToPlatformServiceResource <BridgedParticipantResource>(eventcontext);
                    if (resource != null)
                    {
                        BridgedParticipant newBridgedParticipant = new BridgedParticipant(this.RestfulClient, resource, this.BaseUri,
                                                                                          UriHelper.CreateAbsoluteUri(eventcontext.BaseUri, resource.SelfUri), this);
                        TaskCompletionSource <BridgedParticipant> tcs = null;
                        newBridgedParticipant.HandleResourceEvent(eventcontext);
                        m_bridgedParticipants.TryAdd(UriHelper.NormalizeUri(resource.SelfUri, this.BaseUri), newBridgedParticipant);
                        if (m_bridgedParticipantTcses.TryRemove(resource.Uri.ToLower(), out tcs))
                        {
                            tcs.SetResult(newBridgedParticipant);
                        }
                    }
                }

                if (eventcontext.EventEntity.Relationship == EventOperation.Updated)
                {
                    BridgedParticipantResource resource = this.ConvertToPlatformServiceResource <BridgedParticipantResource>(eventcontext);
                    if (resource != null)
                    {
                        BridgedParticipant newBridgedParticipant = null;

                        if (m_bridgedParticipants.TryGetValue(UriHelper.NormalizeUri(resource.SelfUri, this.BaseUri), out newBridgedParticipant))
                        {
                            newBridgedParticipant.HandleResourceEvent(eventcontext);
                        }
                    }
                }

                if (eventcontext.EventEntity.Relationship == EventOperation.Deleted)
                {
                    BridgedParticipant newBridgedParticipant = null;
                    if (m_bridgedParticipants.TryRemove(UriHelper.NormalizeUri(eventcontext.EventEntity.Link.Href, this.BaseUri), out newBridgedParticipant))
                    {
                        newBridgedParticipant.HandleResourceEvent(eventcontext);
                    }
                }
                return(true);
            }
            else
            {
                return(false);
            }
        }
Beispiel #9
0
        public async Task MapToToken_randomitem_RandomItem()
        {
            // Arrange
            Mock <ILogger <TokenMapper> > logger = new Mock <ILogger <TokenMapper> >();
            ITokenMapper mapper = new TokenMapper(logger.Object);

            // Act
            Token token = await mapper.MapToTokenAsync("randomitem(info,warn,error)");

            // Assert
            RandomItemToken randomItemToken = Assert.IsAssignableFrom <RandomItemToken>(token);

            Assert.Equal(new [] { "info", "warn", "error" }, randomItemToken.Items);
        }
Beispiel #10
0
        public async Task MapToToken_randombetween_RandomBetweenToken()
        {
            // Arrange
            Mock <ILogger <TokenMapper> > logger = new Mock <ILogger <TokenMapper> >();
            ITokenMapper mapper = new TokenMapper(logger.Object);

            // Act
            Token token = await mapper.MapToTokenAsync("randombetween(1,10)");

            // Assert
            RandomBetweenToken randomBetweenToken = Assert.IsAssignableFrom <RandomBetweenToken>(token);

            Assert.Equal(1, randomBetweenToken.Lower);
            Assert.Equal(10, randomBetweenToken.Upper);
        }
Beispiel #11
0
        private async Task <bool> IsValidUser(Login login)
        {
            var tokenDto = await loginService.ValidUser(LoginMapper.ToDto(login));

            if (tokenDto == null)
            {
                HttpContext.Session.SetString("IsUserLogged", "false");
                return(false);
            }
            HttpContext.Session.SetString("IsUserLogged", "true");
            HttpContext.Session.SetString("User", tokenDto.Name);
            HttpContext.Session.SetString("TokenData", JsonConvert.SerializeObject(TokenMapper.ToEntity(tokenDto)));

            return(true);
        }
        public async Task Extract_TemplatesWithSpecialCharacters_ExtractionSuccessfull()
        {
            // Arrange
            Mock <ILogger <TokenMapper> >    logger           = new Mock <ILogger <TokenMapper> >();
            Mock <ILogger <TokenExtractor> > extractionLogger = new Mock <ILogger <TokenExtractor> >();
            ITokenMapper    mapper         = new TokenMapper(logger.Object);
            ITokenExtractor tokenExtractor = new TokenExtractor(mapper, extractionLogger.Object);

            // Act
            List <Extraction> extractions = await tokenExtractor.Extract("Hello\n${uuid}");

            // Assert
            Assert.Single(extractions);
            Assert.Equal("Hello\n{0}", extractions[0].Template);
            Assert.Equal("uuid", extractions[0].Tokens[0].Key);
        }
        public async Task Extract_TemplatesWithJson_ExtractionSuccessfull()
        {
            // Arrange
            Mock <ILogger <TokenMapper> >    logger           = new Mock <ILogger <TokenMapper> >();
            Mock <ILogger <TokenExtractor> > extractionLogger = new Mock <ILogger <TokenExtractor> >();
            ITokenMapper    mapper         = new TokenMapper(logger.Object);
            ITokenExtractor tokenExtractor = new TokenExtractor(mapper, extractionLogger.Object);

            // Act
            List <Extraction> extractions = await tokenExtractor.Extract("{\"Hello\": \"World\", \"id\": \"${uuid}\"}");

            // Assert
            Assert.Single(extractions);
            Assert.Equal("{{\"Hello\": \"World\", \"id\": \"{0}\"}}", extractions[0].Template);
            Assert.Equal("uuid", extractions[0].Tokens[0].Key);
        }
Beispiel #14
0
        public async Task <ActionResult> Edit(int id)
        {
            usersService.TokenDto = TokenMapper.ToDto(JsonConvert.DeserializeObject <TokenData>(HttpContext.Session.GetString("TokenData")));
            var userFound = await usersService.GetUserById(id);

            if (userFound == null)
            {
                return(NotFound());
            }

            ViewData["IsUserLogged"] = HttpContext.Session.GetString("IsUserLogged");

            var user = UserMapper.ToEntity(userFound);

            return(View(user));
        }
        public void ToComplexEntity_WhenSimpleEntity_ExpectCorrectMap()
        {
            // Arrange
            var mockPropertyMapper = new Mock<IPropertyGetSettersTyped<Token>>();
            var mockClaimsMapper = new Mock<IMapper<SimpleClaim, Claim>>();
            var mockClientMapper = new Mock<IMapper<SimpleClient, Client>>();

            mockClaimsMapper.Setup(r => r.ToComplexEntity(It.IsAny<SimpleClaim>())).Returns(new Claim("Val1", "Val2"));
            mockClientMapper.Setup(r => r.ToComplexEntity(It.IsAny<SimpleClient>())).Returns(new Client());

            mockPropertyMapper.Setup(r => r.GetSetters(It.IsAny<Type>()))
                .Returns(new Dictionary<string, TypedSetter<Token>>());

            var tokenMappers = new TokenMapper<Token>(mockPropertyMapper.Object, mockClaimsMapper.Object, mockClientMapper.Object);

            var simpleEntity = new SimpleToken
            {
                Claims = new List<SimpleClaim>(),
                Client = new SimpleClient(),
                Type = "Type",
                CreationTime = new DateTimeOffset(new DateTime(2016, 1, 1)),
                Issuer = "Issuer",
                Version = 1,
                Audience = "Audience",
                Lifetime = 1,
            };

            // Act
            var stopwatch = Stopwatch.StartNew();
            var complexEntity = tokenMappers.ToComplexEntity(simpleEntity);
            stopwatch.Stop();

            // Assert
            this.WriteTimeElapsed(stopwatch);

            Assert.That(complexEntity, Is.Not.Null);

            Assert.That(complexEntity.Claims, Is.Not.Null);
            Assert.That(complexEntity.Client, Is.Not.Null);
            Assert.That(complexEntity.Type, Is.EqualTo("Type"));
            Assert.That(complexEntity.CreationTime, Is.EqualTo(new DateTimeOffset(new DateTime(2016, 1, 1))));
            Assert.That(complexEntity.Issuer, Is.EqualTo("Issuer"));
            Assert.That(complexEntity.Version, Is.EqualTo(1));
            Assert.That(complexEntity.Audience, Is.EqualTo("Audience"));
            Assert.That(complexEntity.Lifetime, Is.EqualTo(1));
        }
Beispiel #16
0
        public async Task <ActionResult> Create(User user)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    usersService.TokenDto = TokenMapper.ToDto(JsonConvert.DeserializeObject <TokenData>(HttpContext.Session.GetString("TokenData")));
                    await usersService.AddUser(UserMapper.ToDto(user));
                }

                return(RedirectToAction(nameof(Index)));
            }
            catch
            {
                return(View());
            }
        }
        public async Task Extract_TemplateWithOneToken_TokenExtracted()
        {
            // Arrange
            Mock <ILogger <TokenMapper> >    logger           = new Mock <ILogger <TokenMapper> >();
            Mock <ILogger <TokenExtractor> > extractionLogger = new Mock <ILogger <TokenExtractor> >();
            ITokenMapper    mapper         = new TokenMapper(logger.Object);
            ITokenExtractor tokenExtractor = new TokenExtractor(mapper, extractionLogger.Object);

            // Act
            List <Extraction> extractions = await tokenExtractor.Extract("I am a log for ${uuid}");

            // Assert
            Extraction extraction = extractions.First();

            Assert.Equal("I am a log for {0}", extraction.Template);
            Assert.Equal("uuid", extraction.Tokens.First().Key);
        }
        public async Task Extract_TemplateWithTwoTokenInJson_TokensExtracted()
        {
            // Arrange
            Mock <ILogger <TokenMapper> >    logger           = new Mock <ILogger <TokenMapper> >();
            Mock <ILogger <TokenExtractor> > extractionLogger = new Mock <ILogger <TokenExtractor> >();
            ITokenMapper    mapper         = new TokenMapper(logger.Object);
            ITokenExtractor tokenExtractor = new TokenExtractor(mapper, extractionLogger.Object);

            // Act
            List <Extraction> extractions = await tokenExtractor.Extract("{\"Hello\":\"${randomitem(world,universe)}\", \"id\": \"${uuid}\"}");

            // Assert
            Extraction extraction = extractions.First();

            Assert.Equal("{{\"Hello\":\"{0}\", \"id\": \"{1}\"}}", extraction.Template);
            Assert.Equal("randomitem", extraction.Tokens[0].Key);
            Assert.Equal("uuid", extraction.Tokens[1].Key);
        }
Beispiel #19
0
        internal override bool ProcessAndDispatchEventsToChild(EventContext eventContext)
        {
            bool processed = false;

            if (eventContext.EventEntity.Link.Token == TokenMapper.GetTokenName(typeof(AudioVideoFlowResource)))
            {
                if (eventContext.EventEntity.Relationship == EventOperation.Added)
                {
                    var audioVideoFlowResource = ConvertToPlatformServiceResource <AudioVideoFlowResource>(eventContext);
                    AudioVideoFlow = new AudioVideoFlow(RestfulClient, audioVideoFlowResource, BaseUri, UriHelper.CreateAbsoluteUri(BaseUri, audioVideoFlowResource.SelfUri), this);

                    // Raise event when flow state changes to connected
                    AudioVideoFlow.HandleResourceUpdated += RaiseAudioVideoFlowConnectedEventIfConnected;

                    // Raise event if the flow is already connected
                    RaiseAudioVideoFlowConnectedEventIfConnected(null, null);
                }

                ((AudioVideoFlow)AudioVideoFlow).HandleResourceEvent(eventContext);

                if (eventContext.EventEntity.Relationship == EventOperation.Deleted)
                {
                    AudioVideoFlow = null;
                }

                processed = true;
            }
            else if (eventContext.EventEntity.Link.Token == TokenMapper.GetTokenName(typeof(TransferResource)))
            {
                this.HandleTransferEvent(eventContext);
                processed = true;
            }

            var flow = AudioVideoFlow;

            if (!processed && flow != null)
            {
                processed = ((AudioVideoFlow)flow).ProcessAndDispatchEventsToChild(eventContext);
            }

            //add any new child resource under audioVideo processing here
            return(processed);
        }
        /// <summary>
        /// ProcessAndDispatchEventsToChild : For child resources here
        /// </summary>
        /// <param name="eventContext"></param>
        /// <returns></returns>
        internal override bool ProcessAndDispatchEventsToChild(EventContext eventContext)
        {
            //No child to dispatch any more, need to dispatch to child , process locally for message type
            if (string.Equals(eventContext.EventEntity.Link.Token, TokenMapper.GetTokenName(typeof(ParticipantMessagingResource))))
            {
                if (eventContext.EventEntity.Relationship == EventOperation.Added)
                {
                    ParticipantMessagingResource participantMessaging = this.ConvertToPlatformServiceResource <ParticipantMessagingResource>(eventContext);
                    if (participantMessaging != null)
                    {
                        ParticipantMessaging = new ParticipantMessaging(this.RestfulClient, participantMessaging, this.BaseUri,
                                                                        UriHelper.CreateAbsoluteUri(eventContext.BaseUri, participantMessaging.SelfUri), this);
                    }

                    m_handleParticipantModalityChange?.Invoke(this, new ParticipantModalityChangeEventArgs
                    {
                        AddedModalities = new List <EventableEntity> {
                            ParticipantMessaging as ParticipantMessaging
                        }
                    });
                }

                if (eventContext.EventEntity.Relationship == EventOperation.Deleted)
                {
                    m_handleParticipantModalityChange?.Invoke(this, new ParticipantModalityChangeEventArgs
                    {
                        RemovedModalities = new List <EventableEntity> {
                            ParticipantMessaging as ParticipantMessaging
                        }
                    });

                    ParticipantMessaging = null;
                }

                return(true);
            }
            else
            {
                return(false);
            }
        }
Beispiel #21
0
        public async Task <ActionResult> Delete(User user)
        {
            try
            {
                usersService.TokenDto = TokenMapper.ToDto(JsonConvert.DeserializeObject <TokenData>(HttpContext.Session.GetString("TokenData")));
                var userFound = await usersService.GetUserById(user.Id);

                if (userFound == null)
                {
                    return(View());
                }

                await usersService.DeleteUser(user.Id);

                return(RedirectToAction(nameof(Index)));
            }
            catch
            {
                return(View());
            }
        }
Beispiel #22
0
        internal override bool ProcessAndDispatchEventsToChild(EventContext eventContext)
        {
            if (eventContext.EventEntity.Link.Token == TokenMapper.GetTokenName(typeof(ToneResource)))
            {
                var toneResource       = ConvertToPlatformServiceResource <ToneResource>(eventContext);
                Uri audioVideoFlowLink = UriHelper.CreateAbsoluteUri(this.BaseUri, toneResource.AudioVideoFlowLink.Href);

                if (string.Equals(audioVideoFlowLink.ToString(), this.ResourceUri.ToString(), StringComparison.OrdinalIgnoreCase))
                {
                    var eventArgs = new ToneReceivedEventArgs(toneResource.ToneValue);
                    m_toneReceivedEvent?.Invoke(this, eventArgs);
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            //No child to dispatch any more, need to dispatch to child , process locally for message type
            else if (string.Equals(eventContext.EventEntity.Link.Token, TokenMapper.GetTokenName(typeof(PromptResource))))
            {
                PromptResource prompt = this.ConvertToPlatformServiceResource <PromptResource>(eventContext);
                if (prompt != null)
                {
                    if (eventContext.EventEntity.Relationship == EventOperation.Completed)
                    {
                        TaskCompletionSource <Prompt> tcs = null;
                        Uri resourceAbsoluteUri           = UriHelper.CreateAbsoluteUri(this.BaseUri, eventContext.EventEntity.Link.Href);
                        m_onGoingPromptTcses.TryGetValue(resourceAbsoluteUri.ToString().ToLower(), out tcs);
                        if (tcs != null)
                        {
                            Prompt p = new Prompt(this.RestfulClient, prompt, this.BaseUri, resourceAbsoluteUri, this);

                            if (eventContext.EventEntity.Status == EventStatus.Success)
                            {
                                tcs.TrySetResult(p);
                            }
                            else if (eventContext.EventEntity.Status == EventStatus.Failure)
                            {
                                var    errorInformation = eventContext.EventEntity.Error;
                                string errorString      = errorInformation?.GetErrorInformationString();
                                tcs.TrySetException(
                                    new RemotePlatformServiceException(
                                        "PlayPrompt failed with error " + errorString + eventContext.LoggingContext.ToString(),
                                        errorInformation
                                        ));
                            }
                            else
                            {
                                Logger.Instance.Error("Received invalid status code for prompt completed event");
                                tcs.TrySetException(new RemotePlatformServiceException("PlayPrompt failed"));
                            }
                            m_onGoingPromptTcses.TryRemove(eventContext.EventEntity.Link.Href.ToLower(), out tcs);
                        }
                    }
                }

                return(true);
            }
            else
            {
                return(false);
            }
        }
Beispiel #23
0
        /// <summary>
        /// Handle current conversation events
        /// </summary>
        /// <param name="eventContext">Events to be processed</param>
        internal override bool ProcessAndDispatchEventsToChild(EventContext eventContext)
        {
            bool processed = false;

            Logger.Instance.Information(string.Format("[Conversation] get incoming communication event, sender: {0}, senderHref: {1}, EventResourceName: {2} EventFullHref: {3}, EventType: {4} ,LoggingContext: {5}",
                                                      eventContext.SenderResourceName, eventContext.SenderHref, eventContext.EventResourceName, eventContext.EventFullHref, eventContext.EventEntity.Relationship.ToString(), eventContext.LoggingContext == null ? string.Empty : eventContext.LoggingContext.ToString()));

            // Messaging
            processed = this.HandleConversationChildEvents <MessagingCall, MessagingResource>(eventContext, ref m_messagingCall, TokenMapper.GetTokenName(typeof(MessagingResource)),
                                                                                              (messagingResource) => new MessagingCall(this.RestfulClient, messagingResource, this.BaseUri, UriHelper.CreateAbsoluteUri(this.BaseUri, messagingResource.SelfUri), this));

            // AudioVideo
            if (!processed)
            {
                processed = this.HandleConversationChildEvents <AudioVideoCall, AudioVideoResource>(eventContext, ref m_audioVideoCall, TokenMapper.GetTokenName(typeof(AudioVideoResource)),
                                                                                                    (AudioVideoResource) => new AudioVideoCall(this.RestfulClient, AudioVideoResource, this.BaseUri, UriHelper.CreateAbsoluteUri(this.BaseUri, AudioVideoResource.SelfUri), this));
            }

            // ConversationConference
            if (!processed)
            {
                processed = this.HandleConversationChildEvents <ConversationConference, ConversationConferenceResource>(eventContext, ref m_conversationConference, TokenMapper.GetTokenName(typeof(ConversationConferenceResource)),
                                                                                                                        (ConversationConferenceResource) => new ConversationConference(this.RestfulClient, ConversationConferenceResource, this.BaseUri, UriHelper.CreateAbsoluteUri(this.BaseUri, ConversationConferenceResource.SelfUri), this));
            }

            // ConversationBridge
            if (!processed)
            {
                processed = this.HandleConversationChildEvents <ConversationBridge, ConversationBridgeResource>(eventContext, ref m_conversationBridge, TokenMapper.GetTokenName(typeof(ConversationBridgeResource)),
                                                                                                                (ConversationBridgeResource) => new ConversationBridge(this.RestfulClient, ConversationBridgeResource, this.BaseUri, UriHelper.CreateAbsoluteUri(this.BaseUri, ConversationBridgeResource.SelfUri), this));
            }

            // Participants
            if (!processed)
            {
                //Here is a hack for participant. Basically we will never get the participantsResource in event, we need to leverage ParticipantsInternal to handle the participant related events
                processed = this.HandleConversationChildEvents <ParticipantsInternal, ParticipantsResource>(eventContext, ref m_participants, TokenMapper.GetTokenName(typeof(ParticipantsResource)),
                                                                                                            (a) => new ParticipantsInternal(this.RestfulClient, this.BaseUri, null, this));
            }

            return(processed);
        }
        internal override bool ProcessAndDispatchEventsToChild(EventContext eventContext)
        {
            //No child to dispatch any more, need to dispatch to child , process locally for message type
            if (string.Equals(eventContext.EventEntity.Link.Token, TokenMapper.GetTokenName(typeof(MessageResource))))
            {
                MessageResource message = this.ConvertToPlatformServiceResource <MessageResource>(eventContext);
                if (message != null)
                {
                    if (message.Direction == Direction.Incoming)
                    {
                        // File incoming message received event
                        IncomingMessageEventArgs args = new IncomingMessageEventArgs
                        {
                            HtmlMessage  = message.HtmlMessage == null? null : message.HtmlMessage.Value as TextHtmlMessage,
                            PlainMessage = message.TextMessage == null ? null : message.TextMessage.Value as TextPlainMessage
                        };
                        Conversation conv = this.Parent as Conversation;

                        Participant fromParticipant = conv.TryGetParticipant(message.ParticipantResourceLink.Href) as Participant;
                        if (fromParticipant == null)
                        {
                            Logger.Instance.Warning("Get message from an unknown participant, probably client code bug or server bug");
                        }
                        else
                        {
                            args.FromParticipantName = fromParticipant.Name;
                        }

                        IncomingMessageReceived?.Invoke(this, args);
                    }
                    else //For out going, just detect the completed event
                    {
                        if (eventContext.EventEntity.Relationship == EventOperation.Completed)
                        {
                            TaskCompletionSource <string> tcs;
                            m_outGoingmessageTcses.TryGetValue(UriHelper.CreateAbsoluteUri(this.BaseUri, eventContext.EventEntity.Link.Href).ToString().ToLower(), out tcs);
                            if (tcs != null)
                            {
                                if (eventContext.EventEntity.Status == EventStatus.Success)
                                {
                                    tcs.TrySetResult(string.Empty);
                                }
                                else if (eventContext.EventEntity.Status == EventStatus.Failure)
                                {
                                    string error = eventContext.EventEntity.Error?.GetErrorInformationString();
                                    tcs.TrySetException(new RemotePlatformServiceException("Send Message failed with error" + error + eventContext.LoggingContext.ToString()));
                                }
                                else
                                {
                                    Logger.Instance.Error("Do not get a valid status code for message complete event!");
                                    tcs.TrySetException(new RemotePlatformServiceException("Send Message failed !"));
                                }
                                m_outGoingmessageTcses.TryRemove(eventContext.EventEntity.Link.Href.ToLower(), out tcs);
                            }
                        }
                    }
                }

                return(true);
            }
            else
            {
                return(false);
            }
        }
        private void ProcessEvents(EventsChannelContext events)
        {
            Logger.Instance.Information("[ApplicationEndpoint] Receice incoming event callback Initialized!");
            Uri baseUri = null;

            if (!Uri.TryCreate(events.EventsEntity.BaseUri, UriKind.Absolute, out baseUri))
            {
                Logger.Instance.Error("[ApplicationEndpoint] " + events.EventsEntity.BaseUri + "is not valid absolute url ");
                return;
            }

            if (Application?.Communication == null)
            {
                try
                {
                    Logger.Instance.Information("[ApplicationEndpoint] application is not initilized, initialize it");
                    InitializeApplicationAsync(new LoggingContext()).Wait();
                }
                catch (Exception ex)
                {
                    Logger.Instance.Error(ex, "[ApplicationEndpoint] application initilized failure, ignore incoming event call back");
                }
            }

            var communication = Application?.Communication as Communication;

            if (communication != null)
            {
                foreach (EventSenderEntity eventsender in events.EventsEntity.Senders)
                {
                    List <EventContext> conversationEvents = null;
                    foreach (EventEntity e in eventsender.Events)
                    {
                        EventContext eventContext = new EventContext
                        {
                            SenderResourceName = eventsender.Token,
                            BaseUri            = baseUri,
                            SenderHref         = eventsender.Href,
                            EventResourceName  = e.Link.Token,
                            EventFullHref      = UriHelper.CreateAbsoluteUri(baseUri, e.Link.Href),
                            EventEntity        = e,
                            LoggingContext     = events.LoggingContext == null ? null : events.LoggingContext.Clone() as LoggingContext
                        };

                        Logger.Instance.Information(string.Format("[ApplicationEndpoint] get incoming event, sender: {0}, senderHref: {1}, EventResourceName: {2} EventFullHref: {3}, EventType {4}, LoggingContext: {5}",
                                                                  eventContext.SenderResourceName, eventContext.SenderHref, eventContext.EventResourceName, eventContext.EventFullHref, eventContext.EventEntity.Relationship.ToString(), eventContext.LoggingContext == null ? string.Empty : eventContext.LoggingContext.ToString()));

                        if (string.Equals(eventContext.SenderResourceName, TokenMapper.GetTokenName(typeof(CommunicationResource)), StringComparison.CurrentCultureIgnoreCase))
                        {
                            communication.ProcessAndDispatchEventsToChild(eventContext);
                        }
                        else if (string.Equals(eventContext.SenderResourceName, TokenMapper.GetTokenName(typeof(ConversationResource)), StringComparison.CurrentCultureIgnoreCase))
                        {
                            // We send conversation updated and deleted events with conversation as sender now.
                            // Since the logic to process those are in communication we will send these events to
                            // communication.ProcessAndDispatchEventsToChild
                            if (string.Equals(eventContext.EventEntity.Link.Token, TokenMapper.GetTokenName(typeof(ConversationResource))))
                            {
                                communication.ProcessAndDispatchEventsToChild(eventContext);
                            }
                            else
                            {
                                if (conversationEvents == null)
                                {
                                    conversationEvents = new List <EventContext>();
                                }
                                conversationEvents.Add(eventContext);
                            }
                        }
                    }

                    if (conversationEvents != null && conversationEvents.Count > 0)
                    {
                        communication.DispatchConversationEvents(conversationEvents);
                    }
                }
            }
        }
Beispiel #26
0
        internal override bool ProcessAndDispatchEventsToChild(EventContext eventcontext)
        {
            ParticipantChangeEventArgs participantChangeEventArgs = null;

            //No child to dispatch any more, need to dispatch to child , process locally for message type
            if (string.Equals(eventcontext.EventEntity.Link.Token, TokenMapper.GetTokenName(typeof(ParticipantResource))))
            {
                if (eventcontext.EventEntity.In != null)
                {
                    //TODO: currently we do not handle in link
                    return(true);
                }

                string normalizedUri = UriHelper.NormalizeUri(eventcontext.EventEntity.Link.Href, this.BaseUri);
                ParticipantResource participantResource = this.ConvertToPlatformServiceResource <ParticipantResource>(eventcontext);
                switch (eventcontext.EventEntity.Relationship)
                {
                case EventOperation.Added:
                {
                    Participant tempParticipant = null;
                    if (!m_participantsCache.TryGetValue(normalizedUri, out tempParticipant))
                    {
                        tempParticipant = new Participant(this.RestfulClient, participantResource, this.BaseUri, UriHelper.CreateAbsoluteUri(this.BaseUri, eventcontext.EventEntity.Link.Href), this.Parent as Conversation);
                        m_participantsCache.TryAdd(normalizedUri, tempParticipant);
                        participantChangeEventArgs = new ParticipantChangeEventArgs();
                        participantChangeEventArgs.AddedParticipants = new List <IParticipant> {
                            tempParticipant
                        };
                    }
                    else
                    {
                        //Should get some participant added In event , ignore currently
                    }
                    break;
                }

                case EventOperation.Updated:
                {
                    Participant tempParticipant = null;
                    if (!m_participantsCache.TryGetValue(normalizedUri, out tempParticipant))
                    {
                        Logger.Instance.Warning("Get a participant updated event for a participant not in cache, any error happened ?");
                        tempParticipant = new Participant(this.RestfulClient, participantResource, this.BaseUri, UriHelper.CreateAbsoluteUri(this.BaseUri, eventcontext.EventEntity.Link.Href), this.Parent as Conversation);
                        m_participantsCache.TryAdd(normalizedUri, tempParticipant);
                    }
                    tempParticipant.HandleResourceEvent(eventcontext);
                    participantChangeEventArgs = new ParticipantChangeEventArgs();
                    participantChangeEventArgs.UpdatedParticipants = new List <IParticipant> {
                        tempParticipant
                    };
                    break;
                }

                case EventOperation.Deleted:
                {
                    Participant tempParticipant = null;
                    if (m_participantsCache.TryRemove(normalizedUri, out tempParticipant))
                    {
                        tempParticipant.HandleResourceEvent(eventcontext);
                        participantChangeEventArgs = new ParticipantChangeEventArgs();
                        participantChangeEventArgs.RemovedParticipants = new List <IParticipant> {
                            tempParticipant
                        };
                    }
                    break;
                }
                }

                if (participantChangeEventArgs != null)
                {
                    var conv = this.Parent as Conversation;
                    conv.OnParticipantChange(participantChangeEventArgs);
                }

                return(true);
            }
            else if (string.Equals(eventcontext.EventEntity.Link.Token, TokenMapper.GetTokenName(typeof(ParticipantMessagingResource))) ||
                     string.Equals(eventcontext.EventEntity.Link.Token, TokenMapper.GetTokenName(typeof(ParticipantAudioResource))) ||
                     string.Equals(eventcontext.EventEntity.Link.Token, TokenMapper.GetTokenName(typeof(ParticipantApplicationSharingResource))))
            {
                if (eventcontext.EventEntity.In != null)
                {
                    string      normalizedParticipantUri = UriHelper.NormalizeUri(eventcontext.EventEntity.In.Href, this.BaseUri);
                    Participant tempParticipant          = null;
                    if (m_participantsCache.TryGetValue(normalizedParticipantUri, out tempParticipant))
                    {
                        tempParticipant.ProcessAndDispatchEventsToChild(eventcontext);
                    }
                }

                return(true); //We do not rely on the response of tempParticipant.ProcessAndDispatchEventsToChild since we already know this is participant modality event
            }
            else
            {
                return(false);
            }
        }
        public void ToSimpleEntity_WhenComplexEntityAndExtendedComplex_ExpectCorrectMap()
        {
            // Arrange
            var mockPropertyMapper = new Mock<IPropertyGetSettersTyped<ExtendedToken>>();

            var mockClaimsMapper = new Mock<IMapper<SimpleClaim, Claim>>();
            var mockClientMapper = new Mock<IMapper<SimpleClient, Client>>();

            var mockGetters = new Dictionary<string, Func<ExtendedToken, object>>
            {
                {
                    "CustomDecimal",
                    typeof(ExtendedToken).GetProperty("CustomDecimal").GetGetter<ExtendedToken>()
                }
            };

            mockPropertyMapper.Setup(r => r.GetGetters(It.IsAny<Type>()))
                .Returns(mockGetters);

            mockClaimsMapper.Setup(r => r.ToSimpleEntity(It.IsAny<Claim>())).Returns(new SimpleClaim());
            mockClientMapper.Setup(r => r.ToSimpleEntity(It.IsAny<Client>())).Returns(new SimpleClient());

            var tokenMappers = new TokenMapper<ExtendedToken>(
                mockPropertyMapper.Object,
                mockClaimsMapper.Object,
                mockClientMapper.Object);

            var complexEntity = new ExtendedToken
            {
                Claims = new List<Claim>(),
                Client = new Client(),
                Type = "Type",
                CreationTime = new DateTimeOffset(new DateTime(2016, 1, 1)),
                Issuer = "Issuer",
                Version = 1,
                Audience = "Audience",
                Lifetime = 1,
                CustomDecimal = 1.25m
            };

            // Act
            var stopwatch = Stopwatch.StartNew();
            var simpleRefreshToken = tokenMappers.ToSimpleEntity(complexEntity);
            stopwatch.Stop();

            // Assert
            this.WriteTimeElapsed(stopwatch);

            Assert.That(simpleRefreshToken.Claims, Is.Not.Null);
            Assert.That(simpleRefreshToken.Client, Is.Not.Null);
            Assert.That(simpleRefreshToken.Type, Is.EqualTo("Type"));
            Assert.That(simpleRefreshToken.CreationTime, Is.EqualTo(new DateTimeOffset(new DateTime(2016, 1, 1))));
            Assert.That(simpleRefreshToken.Issuer, Is.EqualTo("Issuer"));
            Assert.That(simpleRefreshToken.Version, Is.EqualTo(1));
            Assert.That(simpleRefreshToken.Audience, Is.EqualTo("Audience"));
            Assert.That(simpleRefreshToken.Lifetime, Is.EqualTo(1));

            Assert.That(simpleRefreshToken.DataBag["CustomDecimal"], Is.EqualTo(1.25m));
        }
        /// <summary>
        /// ProcessAndDispatchEventsToChild implementation
        /// </summary>
        /// <param name="eventcontext"></param>
        /// <returns></returns>
        internal override bool ProcessAndDispatchEventsToChild(EventContext eventcontext)
        {
            //There is no child for events with sender = communication
            Logger.Instance.Information(string.Format("[Communication] get incoming communication event, sender: {0}, senderHref: {1}, EventResourceName: {2} EventFullHref: {3}, EventType: {4} ,LoggingContext: {5}",
                                                      eventcontext.SenderResourceName, eventcontext.SenderHref, eventcontext.EventResourceName, eventcontext.EventFullHref, eventcontext.EventEntity.Relationship.ToString(), eventcontext.LoggingContext == null ? string.Empty : eventcontext.LoggingContext.ToString()));

            if (string.Equals(eventcontext.EventEntity.Link.Token, TokenMapper.GetTokenName(typeof(ConversationResource))))
            {
                string       conversationNormalizedUri = UriHelper.NormalizeUriWithNoQueryParameters(eventcontext.EventEntity.Link.Href, eventcontext.BaseUri);
                Conversation currentConversation       = m_conversations.GetOrAdd(conversationNormalizedUri,
                                                                                  (a) =>
                {
                    Logger.Instance.Information(string.Format("[Communication] Add conversation {0} LoggingContext: {1}",
                                                              conversationNormalizedUri, eventcontext.LoggingContext == null ? string.Empty : eventcontext.LoggingContext.ToString()));

                    ConversationResource localResource = this.ConvertToPlatformServiceResource <ConversationResource>(eventcontext);
                    //For every conversation resource, we want to make sure it is using latest rest ful client
                    return(new Conversation(this.RestfulClient, localResource, eventcontext.BaseUri, eventcontext.EventFullHref, this));
                }
                                                                                  );

                //Remove from cache if it is a delete operation
                if (eventcontext.EventEntity.Relationship == EventOperation.Deleted)
                {
                    Conversation removedConversation = null;
                    Logger.Instance.Information(string.Format("[Communication] Remove conversation {0} LoggingContext: {1}",
                                                              conversationNormalizedUri, eventcontext.LoggingContext == null ? string.Empty : eventcontext.LoggingContext.ToString()));
                    m_conversations.TryRemove(conversationNormalizedUri, out removedConversation);
                }

                currentConversation.HandleResourceEvent(eventcontext);

                return(true);
            }

            else if (string.Equals(eventcontext.EventEntity.Link.Token, TokenMapper.GetTokenName(typeof(MessagingInvitationResource))))
            {
                this.HandleInvitationEvent <MessagingInvitationResource>(
                    eventcontext,
                    (localResource) => new MessagingInvitation(this.RestfulClient, localResource, eventcontext.BaseUri, eventcontext.EventFullHref, this)
                    );
                return(true);
            }
            else if (string.Equals(eventcontext.EventEntity.Link.Token, TokenMapper.GetTokenName(typeof(AudioVideoInvitationResource))))
            {
                this.HandleInvitationEvent <AudioVideoInvitationResource>(
                    eventcontext,
                    (localResource) => new AudioVideoInvitation(this.RestfulClient, localResource, eventcontext.BaseUri, eventcontext.EventFullHref, this)
                    );
                return(true);
            }
            else if (string.Equals(eventcontext.EventEntity.Link.Token, TokenMapper.GetTokenName(typeof(OnlineMeetingInvitationResource))))
            {
                this.HandleInvitationEvent <OnlineMeetingInvitationResource>(
                    eventcontext,
                    (localResource) => new OnlineMeetingInvitation(this.RestfulClient, localResource, eventcontext.BaseUri, eventcontext.EventFullHref, this)
                    );
                return(true);
            }
            else if (string.Equals(eventcontext.EventEntity.Link.Token, TokenMapper.GetTokenName(typeof(ParticipantInvitationResource))))
            {
                this.HandleInvitationEvent <ParticipantInvitationResource>(
                    eventcontext,
                    (localResource) => new ParticipantInvitation(this.RestfulClient, localResource, eventcontext.BaseUri, eventcontext.EventFullHref, this)
                    );
                return(true);
            }
            //TODO: Process , audioVideoInvitation, ...
            else
            {
                return(false);
            }
        }