예제 #1
0
        public void T02_Load()
        {
            Thread.Sleep(5000);
            ChannelResponse cr = _ua.Channel(_ta.IosChannel);

            GetTest(cr, () => new[] { _remlist.First() });
        }
예제 #2
0
        public CreateJoinRoom()
        {
            var response = new ChannelResponse().Get(new Error()
            {
                ErrorCode = (int)ErrorCode.UnsupportedMethod
            });

            this.Post[$"/api/{Channel}"] = _ => {
                var createJoinRoomArgs   = Serializer.Deserialize <CreateJoinRoomArgs>(this.Request.Body);
                var createJoinRoomOutput = new CreateJoinRoomOutput();

                var playerToken = PlayerToken.Decode(this.Request.Headers["playertoken"].FirstOrDefault());
                switch (playerToken.State)
                {
                case PlayerTokenState.Invalid: return(new ChannelResponse().Get(new Error()
                    {
                        ErrorCode = (int)ErrorCode.InternalError, Message = "The specified PlayerToken is invalid."
                    }));

                case PlayerTokenState.Expired: return(new ChannelResponse().Get(new Error()
                    {
                        ErrorCode = (int)ErrorCode.InternalError, Message = "The specified PlayerToken has expired."
                    }));
                }

                createJoinRoomOutput.JoinKey   = new JoinKey(playerToken.ConnectUserId, createJoinRoomArgs.ServerType, createJoinRoomArgs.RoomId).Encode();
                createJoinRoomOutput.Endpoints = new[] { new ServerEndpoint()
                                                         {
                                                             Address = "127.0.0.1", Port = 8184
                                                         } };

                return(new ChannelResponse().Get(createJoinRoomOutput, this.Request.Headers["playertoken"].First()));
            };
        }
예제 #3
0
        public async Task ShouldReturnChannelResponses()
        {
            // Arrange
            var channels = new List<Channel>();
            _channelRepositoryMock.Setup(x => x.GetAllChannelsAsync())
                .ReturnsAsync(channels)
                .Verifiable();

            var channelResponses = new List<ChannelResponse>();
            foreach (var channel in channels)
            {
                var channelResponse = new ChannelResponse();
                _domainModelsMapperMock.Setup(x => x.MapToChannelResponse(It.Is<Channel>(c => c.Equals(channel))))
                    .Returns(channelResponse)
                    .Verifiable();

                channelResponses.Add(channelResponse);
            }

            // Act
           var act = await _channelService.GetAllChannelsAsync();

            // Assert
            VerifyMocks();

            act.Should().AllBeEquivalentTo(channelResponses);
        }
예제 #4
0
        public async Task should_create_channel()
        {
            // given
            const string slackKey    = "I-is-another-key";
            const string channelName = "my-channel";

            var expectedResponse = new ChannelResponse()
            {
                Channel = new Channel
                {
                    Id        = "some-channel",
                    IsChannel = true
                }
            };

            _httpTest.RespondWithJson(expectedResponse);

            // when
            var result = await _channelClient.CreateChannel(slackKey, channelName);

            // then
            _responseVerifierMock.Verify(x => x.VerifyResponse(Looks.Like(expectedResponse)), Times.Once);
            _httpTest
            .ShouldHaveCalled(ClientConstants.SlackApiHost.AppendPathSegment(FlurlChannelClient.CHANNEL_CREATE_PATH))
            .WithQueryParamValue("token", slackKey)
            .WithQueryParamValue("name", channelName)
            .Times(1);

            result.ToExpectedObject().ShouldEqual(expectedResponse.Channel);
        }
예제 #5
0
        public SimpleConnect()
        {
            var response = new ChannelResponse().Get(new Error()
            {
                ErrorCode = (int)ErrorCode.UnsupportedMethod
            });

            this.Post[$"/api/{Channel}"] = _ => {
                var simpleConnectArgs   = Serializer.Deserialize <SimpleConnectArgs>(this.Request.Body);
                var simpleConnectOutput = new SimpleConnectOutput();

                var database   = DatabaseHost.Client.GetDatabase(simpleConnectArgs.GameId);
                var collection = database.GetCollection <UserAccount>("_accounts");

                // retrieve the account from the database or return null if none found.
                var account = collection.AsQueryable().Where(acc =>
                                                             (acc.Email == simpleConnectArgs.UsernameOrEmail || acc.ConnectUserId == simpleConnectArgs.UsernameOrEmail) && acc.Password == simpleConnectArgs.Password).FirstOrDefault();

                // ensure the proper authentication details have been provided
                if (account == null)
                {
                    return(new ChannelResponse().Get(new Error()
                    {
                        ErrorCode = (int)ErrorCode.UnknownUser
                    }));
                }

                simpleConnectOutput.UserId = account.ConnectUserId;
                simpleConnectOutput.Token  = new PlayerToken(simpleConnectArgs.GameId, simpleConnectOutput.UserId, DateTimeOffset.UtcNow.AddHours(24)).Encode();

                return(new ChannelResponse().Get(simpleConnectOutput, null, false));
            };
        }
예제 #6
0
        /// <summary>
        /// Gets the channels async.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task{IEnumerable{ChannelInfo}}.</returns>
        public async Task <IEnumerable <ChannelInfo> > GetChannelsAsync(CancellationToken cancellationToken)
        {
            _logger.Info("[MythTV] Start GetChannels Async, retrieve all channels");

            var sources = await GetVideoSourceList(cancellationToken);

            var channels = new List <ChannelInfo>();

            foreach (var sourceId in sources)
            {
                var options = GetOptions(cancellationToken,
                                         "/Channel/GetChannelInfoList?SourceID={0}&Details=true&OnlyVisible=true",
                                         sourceId);

                using (var stream = await _httpClient.Get(options).ConfigureAwait(false))
                {
                    channels.AddRange(ChannelResponse.GetChannels(stream, _jsonSerializer, _logger,
                                                                  Plugin.Instance.Configuration.LoadChannelIcons));
                }
            }

            using (var releaser = await _channelLock.LockAsync()) {
                channelNums = channels.ToDictionary(i => i.Id, i => i.Number);
            }

            return(channels);
        }
예제 #7
0
        public void T04_Reload()
        {
            Thread.Sleep(5000);
            ChannelResponse cr = _ua.Channel(_ta.IosChannel);

            GetTest(cr, () => _remlist);
        }
예제 #8
0
        public Connect()
        {
            var response = new ChannelResponse().Get(new Error()
            {
                ErrorCode = (int)ErrorCode.UnsupportedMethod
            });

            this.Post[$"/api/{Channel}"] = _ => {
                var connectArgs   = Serializer.Deserialize <ConnectArgs>(this.Request.Body);
                var connectOutput = new ConnectOutput();

                var database   = DatabaseHost.Client.GetDatabase(connectArgs.GameId);
                var collection = database.GetCollection <UserAccount>("_accounts");

                // ensure the proper authentication details have been provided
                if (collection.AsQueryable().Where(account => account.ConnectUserId == connectArgs.UserId && account.Password == connectArgs.Auth).Any())
                {
                    connectOutput.UserId = connectArgs.UserId;
                    connectOutput.Token  = new PlayerToken(connectArgs.GameId, connectOutput.UserId, DateTimeOffset.UtcNow.AddHours(24)).Encode();

                    return(new ChannelResponse().Get(connectOutput, connectOutput.Token));
                }

                return(new ChannelResponse().Get(new Error()
                {
                    ErrorCode = (int)ErrorCode.InvalidAuth
                }));
            };
        }
예제 #9
0
        public SimpleRegister()
        {
            var response = new ChannelResponse().Get(new Error()
            {
                ErrorCode = (int)ErrorCode.UnsupportedMethod
            });

            this.Post[$"/api/{Channel}"] = _ => {
                var simpleRegisterArgs   = Serializer.Deserialize <SimpleRegisterArgs>(this.Request.Body);
                var simpleRegisterOutput = new SimpleRegisterOutput();

                var database   = DatabaseHost.Client.GetDatabase(simpleRegisterArgs.GameId);
                var collection = database.GetCollection <UserAccount>("_accounts");

                // ensure the email address is valid (disregarding the TLD)
                var validEmailRegex = @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z";
                if (!Regex.IsMatch(simpleRegisterArgs.Email, validEmailRegex, RegexOptions.IgnoreCase))
                {
                    return(new ChannelResponse().Get(new Error()
                    {
                        ErrorCode = (int)ErrorCode.InvalidRegistrationData, Message = "The specified email address is invalid."
                    }));
                }

                if (collection.AsQueryable().Where(x => x.Name == simpleRegisterArgs.Username).Any())
                {
                    return(new ChannelResponse().Get(new Error()
                    {
                        ErrorCode = (int)ErrorCode.InvalidRegistrationData, Message = "The specified name is already in use."
                    }));
                }

                if (collection.AsQueryable().Where(x => x.Email == simpleRegisterArgs.Email).Any())
                {
                    return(new ChannelResponse().Get(new Error()
                    {
                        ErrorCode = (int)ErrorCode.InvalidRegistrationData, Message = "The specified email address is already in use."
                    }));
                }

                var registrationDate      = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                var registeredUserAccount = new UserAccount()
                {
                    Type          = AccountType.Simple,
                    ConnectUserId = $"simple{registrationDate}x{PlayerIOEncrypt.CRNG.Next(0, 99)}",
                    Name          = simpleRegisterArgs.Username,
                    Email         = simpleRegisterArgs.Email,
                    Password      = simpleRegisterArgs.Password,
                    Registered    = registrationDate
                };

                collection.InsertOne(registeredUserAccount);

                simpleRegisterOutput.UserId = registeredUserAccount.ConnectUserId;
                simpleRegisterOutput.Token  = new PlayerToken(simpleRegisterArgs.GameId, registeredUserAccount.ConnectUserId).Encode();

                return(new ChannelResponse().Get(simpleRegisterOutput, simpleRegisterOutput.Token));
            };
        }
예제 #10
0
        protected void grdListNews_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                int             idCourse = DFISYS.CoreBO.Common.function.Obj2Int(Request.QueryString["courseID"]);
                Question        data     = e.Row.DataItem as Question;
                ChannelResponse obj      = new ChannelResponse();
                Literal         userSay  = e.Row.FindControl("userSay") as Literal;
                if (data.Question_Answer.Length > 0)
                {
                    obj.ChannelResponse_ID = data.Channel_ID;
                    obj          = obj.SelectOne();
                    userSay.Text = string.Format("<b>{0}</b> ({1}) trả lời:", obj.UserID, obj.ChannelResponse_NameManager);// "<b>" + obj.UserID + "()" + "</b> Trả lời:";
                }


                DropDownList cboUser = e.Row.FindControl("cboUser") as DropDownList;
                cboUser.DataTextField  = "ChannelResponse_NameManager";
                cboUser.DataValueField = "ChannelResponse_ID";
                cboUser.DataSource     = obj.SelectAllBySourseIDActive(idCourse);
                cboUser.DataBind();

                var item = cboUser.Items.FindByValue(data.Channel_ID.ToString());//.Selected = true;
                if (item != null)
                {
                    item.Selected = true;
                }


                Literal status = e.Row.FindControl("ltStatus") as Literal;


                Literal sex = e.Row.FindControl("ltSex") as Literal;

                if (data.User_Sex == Sex.NAM)
                {
                    sex.Text = "Nam";
                }
                else
                {
                    sex.Text = "Nữ";
                }
                switch (data.Status)
                {
                case QuestionStatus.DA_TRA_LOI:
                    status.Text     = "<b><span style='color:red;'>Đã trả lời</span></b><br/>";
                    cboUser.Visible = false;
                    break;

                case QuestionStatus.DA_DIEU_PHOI:
                    status.Text = "<b><span style='color:red;'>Đã điều phối cho</span></b><br/>";
                    break;

                case QuestionStatus.CHUA_DIEU_PHOI:
                    status.Text = "<b><span style='color:red;'>Chưa điều phối</span></b><br/>";
                    break;
                }
            }
        }
예제 #11
0
 private void ProcessPostFilters(ChannelRequest channelRequest, ChannelResponse channelResponse)
 {
     foreach (IChannelFilter filter in _postFilters)
      {
     filter.ChannelRequest = channelRequest;
     filter.ChannelResponse = channelResponse;
     filter.Process();
      }
 }
예제 #12
0
        public async Task <StockItem> GetStock(string productCode)
        {
            ChannelResponse <StockLocation> stockLocation = await _stockClient.GetStockLocations();

            StockLocation location = stockLocation?.Content.First();
            var           response = await _stockClient.GetStock(productCode, location.Id);

            return(response?.Content?.First());
        }
예제 #13
0
 public static void ClassInitialize(TestContext context)
 {
     OkChannelResponse           = JsonLoader.LoadJson <ChannelResponse>(@"Channels/Data/channel_info.json");
     OkBaseResponse              = JsonLoader.LoadJson <BaseResponse>(@"Data/base.json");
     OkMessagesResponse          = JsonLoader.LoadJson <MessagesResponse>(@"Data/messages.json");
     OkChannelLeaveResponse      = JsonLoader.LoadJson <ChannelLeaveResponse>(@"Channels/Data/channel_leave.json");
     OkChannelListResponse       = JsonLoader.LoadJson <ChannelListResponse>(@"Channels/Data/channel_list.json");
     OkChannelSetPurposeResponse = JsonLoader.LoadJson <ChannelSetPurposeResponse>(@"Channels/Data/channel_setPurpose.json");
     OkChannelSetTopicResponse   = JsonLoader.LoadJson <ChannelSetTopicResponse>(@"Channels/Data/channel_setTopic.json");
 }
예제 #14
0
        public static void ChannelResponse_Success_Serialization()
        {
            var response = new ChannelResponse< EbaySubmissionResult > {
                Result = new EbaySubmissionResult()
            };

            var str = response.ToYamlString();
            Console.WriteLine( str );

            Assert.That( str.Contains( "IsSuccess" ), "Contains IsSuccess" );
        }
예제 #15
0
        private async Task <IEnumerable <string> > GetVideoSourceList(CancellationToken cancellationToken)
        {
            _logger.Info("[MythTV] Start GetVideoSourceList");

            var options = GetOptions(cancellationToken,
                                     "/Channel/GetVideoSourceList");

            using (var sourcesstream = await _httpClient.Get(options).ConfigureAwait(false))
            {
                return(ChannelResponse.GetVideoSourceList(sourcesstream, _jsonSerializer, _logger));
            }
        }
예제 #16
0
 /// <inheritdoc />
 public void OnChannelResponse(ChannelResponse response)
 {
     lock (this)
     {
         if (response.DataList != null)
         {
             foreach (var data in response.DataList)
             {
                 WriteRecord(data);
             }
         }
     }
 }
예제 #17
0
        public void T05_Delete()
        {
            var to = new TagAddRemove(_ta);

            to.Remove.Add(TAG_GROUP, _remlist);
            OpTest(_ua.ChannelTags(to));

            Thread.Sleep(5000);
            ChannelResponse cr = _ua.Channel(_ta.IosChannel);

            OpTest(cr);
            Assert.IsNotNull(cr.Channel);
            Assert.That(!cr.Channel.TagGroups.ContainsKey(TAG_GROUP) || cr.Channel.TagGroups[TAG_GROUP].Count == 0);
        }
예제 #18
0
        public async Task ShouldReturnChannelResponse()
        {
            // Arrange
            var channel = new Channel
            {
                Id       = new Guid("02A86CF8-2A22-4381-97D3-5EB0C0F387F0"),
                IsClosed = false
            };
            var member = new Member {
                Id = new Guid("0AAB1E31-F907-4EEB-808D-77B7E2BFA66B")
            };

            _channelRepositoryMock.Setup(x => x.GetChannelAsync(It.IsAny <Guid>()))
            .ReturnsAsync(channel)
            .Verifiable();

            _memberRepositoryMock.Setup(x => x.GetMemberByIdAsync(It.Is <Guid>(m => m.Equals(member.Id))))
            .ReturnsAsync(member)
            .Verifiable();

            _channelRepositoryMock.Setup(x => x.IsMemberExistsInChannelAsync(It.Is <Guid>(m => m.Equals(member.Id)), It.Is <Guid>(c => c.Equals(channel.Id))))
            .ReturnsAsync(false)
            .Verifiable();

            _channelMemberRepositoryMock.Setup(x => x.AddChannelMemberAsync(It.IsAny <ChannelMember>()))
            .Returns(Task.CompletedTask)
            .Verifiable();

            _channelRepositoryMock.Setup(x => x.IncrementChannelMembersCountAsync(It.Is <Guid>(c => c.Equals(channel.Id))))
            .Returns(Task.CompletedTask)
            .Verifiable();

            _channelRepositoryMock.Setup(x => x.GetChannelAsync(It.Is <Guid>(c => c.Equals(channel.Id))))
            .ReturnsAsync(channel)
            .Verifiable();

            var channelResponse = new ChannelResponse();

            _domainModelsMapperMock.Setup(x => x.MapToChannelResponse(It.Is <Channel>(c => c.Equals(channel))))
            .Returns(channelResponse)
            .Verifiable();

            // Act
            var act = await _memberService.InviteMemberAsync(member.Id, channel.Id);

            // Assert
            act.Should().BeEquivalentTo(channelResponse);
        }
        protected void grdListPhongVan_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ChannelResponse data               = e.Row.DataItem as ChannelResponse;
                DropDownList    cboUser            = e.Row.FindControl("lsUser") as DropDownList;
                DFISYS.GUI.Users.Business.User obj = new GUI.Users.Business.User();
                cboUser.DataTextField  = "User_ID";
                cboUser.DataValueField = "User_ID";
                cboUser.DataSource     = obj.GetAllUser(RoleConst.GiaoLuuTrucTuyen);
                cboUser.DataBind();

                var item = cboUser.Items.FindByValue(data.UserID);//.Selected = true;
                if (item != null)
                {
                    item.Selected = true;
                }
            }
        }
예제 #20
0
        public static ChannelResponse ToChannelResponse(this Domain.Channel.Channel channel, CloudStorageConfiguration configuration)
        {
            var channelResponse = new ChannelResponse();

            if (channel != null)
            {
                channelResponse.Id             = channel.Id;
                channelResponse.IsClosed       = channel.IsClosed;
                channelResponse.Updated        = channel.Updated;
                channelResponse.Created        = channel.Created;
                channelResponse.MembersCount   = channel.MembersCount;
                channelResponse.Name           = channel.Name;
                channelResponse.Description    = channel.Description;
                channelResponse.WelcomeMessage = channel.WelcomeMessage;
                channelResponse.Type           = channel.Type;
                channelResponse.CreatorId      = channel.CreatorId;
            }
            return(channelResponse);
        }
예제 #21
0
        public void Intercept(IInvocation invocation)
        {
            ChannelRequest channelRequest = new ChannelRequest();
             ChannelResponse channelResponse = new ChannelResponse();

             channelRequest.Invocation = invocation;
             channelRequest.ServiceName = ServiceName;
             ProcessPreFilters(channelRequest, channelResponse);

             try
             {
            channelResponse.Content = _transport.SendChannelRequest(channelRequest.Content);
             }
             catch (Exception)
             {
            throw;
             }

             ProcessPostFilters(channelRequest, channelResponse);
        }
예제 #22
0
        void GetTest(ChannelResponse cr, Func <ICollection <string> > getTags)
        {
            Assert.IsNotNull(cr);
            Assert.IsTrue(cr.Ok, "{0} {1} | {2} {3}", cr.ErrorCode, cr.Error, cr.HttpResponseCode, cr.Message);
            Assert.IsNotNull(cr.Channel);
            StringAssert.AreEqualIgnoringCase(_ta.IosChannel, cr.Channel.ChannelId);
            CollectionAssert.IsNotEmpty(cr.Channel.TagGroups);
            CollectionAssert.Contains(cr.Channel.TagGroups.Keys, TAG_GROUP);

            ICollection <string> tags = cr.Channel.TagGroups[TAG_GROUP];

            CollectionAssert.IsNotEmpty(tags);

            ICollection <string> reloads = getTags();

            foreach (string t in tags)
            {
                CollectionAssert.Contains(reloads, t);
            }
        }
        protected void grdListNews_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                int          idCourse = DFISYS.CoreBO.Common.function.Obj2Int(Request.QueryString["courseID"]);
                Question     data     = e.Row.DataItem as Question;
                DropDownList cboUser  = e.Row.FindControl("cboUser") as DropDownList;

                ChannelResponse obj = new ChannelResponse();
                cboUser.DataTextField  = "ChannelResponse_NameManager";
                cboUser.DataValueField = "ChannelResponse_ID";
                cboUser.DataSource     = obj.SelectAllBySourseIDActive(idCourse);
                cboUser.DataBind();

                var item = cboUser.Items.FindByValue(data.Channel_ID.ToString());//.Selected = true;
                if (item != null)
                {
                    item.Selected = true;
                }
            }
        }
        public new static RealtimeChannelResponse Deserialize(string serialized)
        {
            if (!serialized.StartsWith("["))
            {
                return(null);
            }
            var response = JsonConvert.DeserializeObject <object[]>(serialized);
            int channelId;

            if (!int.TryParse(response[0].ToString(), out channelId))
            {
                return(null);
            }
            if (response[1].ToString().Equals("hb", StringComparison.InvariantCultureIgnoreCase))
            {
                return(new RealtimeChannelResponse(channelId, null));
            }
            var channelResponse = ChannelResponse.Deserialize(response[1].ToString());

            return(channelResponse != null ? new RealtimeChannelResponse(channelId, channelResponse.DataList) : null);
        }
예제 #25
0
        public async Task ShouldReturnChannel()
        {
            // Arrange
            var channel = new Channel {
                Id = new Guid("3B16890F-4D6E-445D-BF6C-C293F3AF68FE")
            };

            _channelRepositoryMock.Setup(x => x.GetChannelAsync(It.Is <Guid>(id => id.Equals(channel.Id))))
            .ReturnsAsync(channel)
            .Verifiable();

            var channelResponse = new ChannelResponse();

            _domainModelsMapperMock.Setup(x => x.MapToChannelResponse(It.Is <Channel>(ch => ch.Equals(channel))))
            .Returns(channelResponse);

            // Act
            var result = await _channelService.GetChannelByIdAsync(channel.Id);

            // Assert
            result.Should().BeEquivalentTo(channelResponse);
        }
예제 #26
0
        public async Task ShouldReturnChannelResponse()
        {
            // Arrange
            var saasUserId = "BAFDCFAA-267D-4D16-98B0-6D516D9193ED";
            var channel    = new Channel
            {
                Id        = new Guid("7A5006DC-B5DC-4D98-AE4B-D4518D149A5A"),
                CreatorId = new Guid("8F5A162D-2A47-4871-9608-9BFF627DFC72"),
                IsClosed  = false
            };

            var member = new Member {
                Id = new Guid("8F5A162D-2A47-4871-9608-9BFF627DFC72")
            };

            _channelRepositoryMock.Setup(x => x.GetChannelAsync(It.Is <Guid>(idChannel => idChannel.Equals(channel.Id))))
            .ReturnsAsync(channel)
            .Verifiable();

            _memberRepositoryMock.Setup(x => x.GetMemberBySaasUserIdAsync(It.Is <string>(saasId => saasId.Equals(saasUserId))))
            .ReturnsAsync(member)
            .Verifiable();

            _channelRepositoryMock.Setup(x => x.UpdateChannelAsync(It.Is <Channel>(ch => ch.Equals(channel)))).Returns(Task.CompletedTask);

            var mappedChannel = new ChannelResponse();

            _domainModelsMapperMock.Setup(x => x.MapToChannelResponse(It.Is <Channel>(c => c.Equals(channel))))
            .Returns(mappedChannel)
            .Verifiable();

            // Act
            var act = await _channelService.CloseChannelAsync(saasUserId, channel.Id);

            // Assert
            act.Should().BeEquivalentTo(mappedChannel);

            VerifyMocks();
        }
예제 #27
0
        private async Task <string> GetCallsign(string channelId, CancellationToken cancellationToken)
        {
            using (var releaser = await _channelsLock.LockAsync())
            {
                if (_channelCache.Count == 0)
                {
                    EnsureSetup();

                    using (var sourcesstream = await _httpClient.Get(GetOptions(cancellationToken, "/Channel/GetVideoSourceList")).ConfigureAwait(false))
                    {
                        var sources = ChannelResponse.ParseVideoSourceList(sourcesstream, _jsonSerializer, _logger);
                        foreach (var source in sources.VideoSources)
                        {
                            using (var stream = await _httpClient.Get(GetOptions(cancellationToken, "/Channel/GetChannelInfoList?SourceID={0}", source.Id)).ConfigureAwait(false))
                            {
                                var channels = ChannelResponse.ParseChannelInfoList(stream, _jsonSerializer, _logger);
                                foreach (var channel in channels.ChannelInfos)
                                {
                                    if (channel.Visible)
                                    {
                                        _channelCache[channel.ChanId.ToString()] = channel;
                                    }
                                }
                            }
                        }
                    }
                }

                if (_channelCache.ContainsKey(channelId))
                {
                    return(_channelCache[channelId].CallSign);
                }
                else
                {
                    return(string.Empty);
                }
            }
        }
예제 #28
0
        public LoadObjects()
        {
            var response = new ChannelResponse().Get(new Error()
            {
                ErrorCode = (int)ErrorCode.UnsupportedMethod
            });

            this.Post[$"/api/{Channel}"] = _ => {
                var playerToken       = PlayerToken.Decode(this.Request.Headers["playertoken"].FirstOrDefault());
                var loadObjectsArgs   = Serializer.Deserialize <LoadObjectsArgs>(this.Request.Body);
                var loadObjectsOutput = new LoadObjectsOutput();

                switch (playerToken.State)
                {
                case PlayerTokenState.Invalid:
                    return(new ChannelResponse().Get(new Error()
                    {
                        ErrorCode = (int)ErrorCode.InternalError, Message = "The specified PlayerToken is invalid."
                    }));

                case PlayerTokenState.Expired:
                    return(new ChannelResponse().Get(new Error()
                    {
                        ErrorCode = (int)ErrorCode.InternalError, Message = "The specified PlayerToken has expired."
                    }));
                }

                // prevent loading an internal table from the BigDB database
                if (!loadObjectsArgs.ObjectIds.Table.All(char.IsLetterOrDigit))
                {
                    return(new ChannelResponse().Get(new Error()
                    {
                        ErrorCode = (int)ErrorCode.AccessDenied, Message = "Table names cannot contain non-alphanumeric characters."
                    }));
                }

                // collection names may only contain no more than 64 characters and no less than 1 character
                if (loadObjectsArgs.ObjectIds.Table.Length < 1 || loadObjectsArgs.ObjectIds.Table.Length > 64)
                {
                    return(new ChannelResponse().Get(new Error()
                    {
                        ErrorCode = (int)ErrorCode.AccessDenied, Message = "Table names must be between 1-64 characters in length."
                    }));
                }

                // retrieve the relevant database objects from the BigDB database
                var collection      = DatabaseHost.Client.GetDatabase(playerToken.GameId).GetCollection <BsonDocument>(loadObjectsArgs.ObjectIds.Table);
                var databaseObjects = new List <DatabaseObject>();

                foreach (var objectKey in loadObjectsArgs.ObjectIds.Keys)
                {
                    // prevent creating objects with invalid characters within the keys
                    if (!objectKey.All(char.IsLetterOrDigit))
                    {
                        return(new ChannelResponse().Get(new Error()
                        {
                            ErrorCode = (int)ErrorCode.AccessDenied, Message = "DatabaseObject keys cannot contain non-alphanumeric characters."
                        }));
                    }

                    // database object keys may only contain no more than 64 characters and no less than 1 character
                    if (objectKey.Length < 1 || objectKey.Length > 64)
                    {
                        return(new ChannelResponse().Get(new Error()
                        {
                            ErrorCode = (int)ErrorCode.AccessDenied, Message = "DatabaseObject keys must be between 1-64 characters in length."
                        }));
                    }

                    // query the database for keys matching the key specified
                    var document = collection.Find(Builders <BsonDocument> .Filter.Eq("Key", objectKey)).FirstOrDefault();

                    if (document != null)
                    {
                        var databaseObject = new DatabaseObject();

                        // retrieve the document version if available
                        if (document.TryGetValue("_version", out var value))
                        {
                            databaseObject.Version = value.AsString;
                        }

                        // remove any lingering artifacts before deserialization
                        foreach (var element in document.Elements.ToArray())
                        {
                            if (element.Name.StartsWith("_"))
                            {
                                document.RemoveElement(element);
                            }
                        }

                        var _databaseObject = JsonConvert.DeserializeObject <SentDatabaseObject>(document.ToJson());

                        databaseObject.Table      = _databaseObject.Table;
                        databaseObject.Key        = _databaseObject.Key;
                        databaseObject.Properties = _databaseObject.Properties;

                        databaseObjects.Add(databaseObject);
                    }
                }

                loadObjectsOutput.Objects = databaseObjects.ToArray();

                return(new ChannelResponse().Get(loadObjectsOutput, this.Request.Headers["playertoken"].First()));
            };
        }
예제 #29
0
        public CreateObjects()
        {
            var response = new ChannelResponse().Get(new Error()
            {
                ErrorCode = (int)ErrorCode.UnsupportedMethod
            });

            this.Post[$"/api/{Channel}"] = _ => {
                var createObjectsArgs   = Serializer.Deserialize <CreateObjectsArgs>(this.Request.Body);
                var createObjectsOutput = new CreateObjectsOutput();

                var playerToken = PlayerToken.Decode(this.Request.Headers["playertoken"].FirstOrDefault());
                switch (playerToken.State)
                {
                case PlayerTokenState.Invalid: return(new ChannelResponse().Get(new Error()
                    {
                        ErrorCode = (int)ErrorCode.InternalError, Message = "The specified PlayerToken is invalid."
                    }));

                case PlayerTokenState.Expired: return(new ChannelResponse().Get(new Error()
                    {
                        ErrorCode = (int)ErrorCode.InternalError, Message = "The specified PlayerToken has expired."
                    }));
                }

                // if they request no objects, return no objects
                if (createObjectsArgs.Objects.Length < 1)
                {
                    createObjectsOutput.Objects = new DatabaseObject[0];

                    return(new ChannelResponse().Get(createObjectsOutput, this.Request.Headers["playertoken"].First()));
                }

                // To-Do: check for permissions to create objects
                var database   = DatabaseHost.Client.GetDatabase(playerToken.GameId);
                var collection = database.GetCollection <BsonDocument>(createObjectsArgs.Objects[0].Table);

                var databaseObjects = new List <DatabaseObject>();
                foreach (var databaseObject in createObjectsArgs.Objects.OrderByDescending(x => x.Table))
                {
                    // load collection once per unique table for performance reasons
                    if (databaseObject.Table != collection.CollectionNamespace.CollectionName)
                    {
                        collection = database.GetCollection <BsonDocument>(databaseObject.Table);
                    }

                    // prevent creating objects in an internal table from the BigDB database
                    if (!databaseObject.Table.All(char.IsLetterOrDigit))
                    {
                        return(new ChannelResponse().Get(new Error()
                        {
                            ErrorCode = (int)ErrorCode.AccessDenied, Message = "Table names cannot contain non-alphanumeric characters."
                        }));
                    }

                    // prevent creating objects with invalid characters within the keys
                    if (!databaseObject.Key.All(char.IsLetterOrDigit))
                    {
                        return(new ChannelResponse().Get(new Error()
                        {
                            ErrorCode = (int)ErrorCode.AccessDenied, Message = "DatabaseObject keys cannot contain non-alphanumeric characters."
                        }));
                    }

                    // table names may only contain no more than 64 characters and no less than 1 character
                    if (databaseObject.Table.Length < 1 || databaseObject.Table.Length > 64)
                    {
                        return(new ChannelResponse().Get(new Error()
                        {
                            ErrorCode = (int)ErrorCode.AccessDenied, Message = "Table names must be between 1-64 characters in length."
                        }));
                    }

                    // database object keys may only contain no more than 64 characters and no less than 1 character
                    if (databaseObject.Key.Length < 1 || databaseObject.Key.Length > 64)
                    {
                        return(new ChannelResponse().Get(new Error()
                        {
                            ErrorCode = (int)ErrorCode.AccessDenied, Message = "DatabaseObject keys must be between 1-64 characters in length."
                        }));
                    }

                    // check if the collection exists in the respecctful database
                    if (!database.ListCollections(new ListCollectionsOptions()
                    {
                        Filter = new BsonDocument("name", databaseObject.Table)
                    }).Any())
                    {
                        return(new ChannelResponse().Get(new Error()
                        {
                            ErrorCode = (int)ErrorCode.UnknownTable
                        }));
                    }

                    var document = collection.Find(Builders <BsonDocument> .Filter.Eq("Key", playerToken.ConnectUserId)).FirstOrDefault();

                    // load existing database objects if required
                    if (createObjectsArgs.LoadExisting && document != null)
                    {
                        var existingDatabaseObject = new DatabaseObject();

                        if (document.TryGetValue("_version", out var value))
                        {
                            existingDatabaseObject.Version = value.AsString;
                        }

                        // remove any lingering artifacts before deserialization
                        foreach (var element in document.Elements.ToArray())
                        {
                            if (element.Name.StartsWith("_"))
                            {
                                document.RemoveElement(element);
                            }
                        }

                        var _existingDatabaseObject = JsonConvert.DeserializeObject <SentDatabaseObject>(document.ToJson());
                        existingDatabaseObject.Table      = _existingDatabaseObject.Table;
                        existingDatabaseObject.Key        = _existingDatabaseObject.Key;
                        existingDatabaseObject.Properties = _existingDatabaseObject.Properties;

                        databaseObjects.Add(existingDatabaseObject);

                        // skip inserting the existing database object into the database
                        continue;
                    }

                    // insert the new database object into the database
                    collection.InsertOne(BsonDocument.Parse(JsonConvert.SerializeObject(databaseObject)).Add("_version", "1"));

                    // insert the database object into the the output
                    databaseObjects.Add(new DatabaseObject()
                    {
                        Table      = databaseObject.Table,
                        Key        = databaseObject.Key,
                        Properties = databaseObject.Properties,
                        Version    = "1"
                    });
                }

                createObjectsOutput.Objects = databaseObjects.ToArray();

                return(new ChannelResponse().Get(createObjectsOutput, this.Request.Headers["playertoken"].First(), false));
            };
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (String.IsNullOrWhiteSpace(this.Page.User.Identity.Name))
            {
                return;
            }
            if (!IsPostBack)
            {
                DFISYS.GUI.Users.Business.User obj = new GUI.Users.Business.User();
                lsUserNew.DataTextField  = "User_ID";
                lsUserNew.DataValueField = "User_ID";
                lsUserNew.DataSource     = obj.GetAllUser(RoleConst.GiaoLuuTrucTuyen);
                lsUserNew.DataBind();
                sourseID = DFISYS.CoreBO.Common.function.Obj2Int(Request.QueryString["sourseID"]);
                btInsert.OnClientClick = string.Format("InsertItem({0})", sourseID);
            }



            if (Request.QueryString["sourseID"] != null && Request.QueryString["post"] == null)
            {
                sourseID = DFISYS.CoreBO.Common.function.Obj2Int(Request.QueryString["sourseID"]);
                ChannelResponse        obj       = new ChannelResponse();
                List <ChannelResponse> lsChannel = new List <ChannelResponse>();
                lsChannel = obj.SelectAllBySourseID(sourseID);
                this.grdListPhongVan.DataSource = lsChannel;
                this.grdListPhongVan.DataBind();
                return;
            }

            if (Request.QueryString["action"] == "deleteitem")
            {
                var objdel = new ChannelResponse();
                int iddel  = DFISYS.CoreBO.Common.function.Obj2Int(Request.QueryString["id"]);
                objdel.ChannelResponse_ID = iddel;
                objdel.Delete();
            }
            if (Request.QueryString["action"] == "insert")
            {
                var    objInsert = new ChannelResponse();
                String name      = Request.QueryString["name"].ToString();
                String user      = Request.QueryString["user"].ToString();
                bool   active    = DFISYS.CoreBO.Common.function.Obj2Boolean(Request.QueryString["active"]);
                sourseID = DFISYS.CoreBO.Common.function.Obj2Int(Request.QueryString["sourseID"]);

                objInsert.Sourse_ID = sourseID;
                objInsert.ChannelResponse_NameManager = name;
                objInsert.UserID   = user;
                objInsert.IsActive = active;
                objInsert.Insert();
            }



            if (Request.Form.Count > 0)
            {
                int id  = DFISYS.CoreBO.Common.function.Obj2Int(Request.QueryString["id"]);
                var obj = new ChannelResponse();
                if (Request.QueryString["action"] == "deleteitem")
                {
                    obj.ChannelResponse_ID = id;
                    obj.Delete();
                }

                String name   = Request.QueryString["name"].ToString();
                String user   = Request.QueryString["user"].ToString();
                bool   active = DFISYS.CoreBO.Common.function.Obj2Boolean(Request.QueryString["active"]);
                if (id > 0)
                {
                    obj.ChannelResponse_ID = id;
                    obj = obj.SelectOne();
                    obj.ChannelResponse_NameManager = name;
                    obj.UserID   = user;
                    obj.IsActive = active;
                    obj.Update();
                }
            }
        }
예제 #31
0
        public LoadMyPlayerObject()
        {
            var response = new ChannelResponse().Get(new Error()
            {
                ErrorCode = (int)ErrorCode.UnsupportedMethod
            });

            this.Post[$"/api/{Channel}"] = _ => {
                var loadMyPlayerObjectOutput = new LoadMyPlayerObjectOutput()
                {
                    PlayerObject = new DatabaseObject()
                };

                // return an error if the specified PlayerToken is invalid
                var playerToken = PlayerToken.Decode(this.Request.Headers["playertoken"].FirstOrDefault());
                switch (playerToken.State)
                {
                case PlayerTokenState.Invalid: return(new ChannelResponse().Get(new Error()
                    {
                        ErrorCode = (int)ErrorCode.InternalError, Message = "The specified PlayerToken is invalid."
                    }));

                case PlayerTokenState.Expired: return(new ChannelResponse().Get(new Error()
                    {
                        ErrorCode = (int)ErrorCode.InternalError, Message = "The specified PlayerToken has expired."
                    }));
                }

                var collection = DatabaseHost.Client.GetDatabase(playerToken.GameId).GetCollection <BsonDocument>("PlayerObjects");
                var document   = collection.Find(Builders <BsonDocument> .Filter.Eq("Key", playerToken.ConnectUserId)).FirstOrDefault();

                if (document == null)
                {
                    return(new ChannelResponse().Get(new Error()
                    {
                        ErrorCode = (int)ErrorCode.BigDBObjectDoesNotExist
                    }));
                }

                // retrieve the document version if available
                if (document.TryGetValue("_version", out var value))
                {
                    loadMyPlayerObjectOutput.PlayerObject.Version = value.AsString;
                }

                // remove any lingering artifacts before deserialization
                foreach (var element in document.Elements.ToArray())
                {
                    if (element.Name.StartsWith("_"))
                    {
                        document.RemoveElement(element);
                    }
                }

                var _databaseObject = JsonConvert.DeserializeObject <SentDatabaseObject>(document.ToJson());

                loadMyPlayerObjectOutput.PlayerObject.Table      = _databaseObject.Table;
                loadMyPlayerObjectOutput.PlayerObject.Key        = _databaseObject.Key;
                loadMyPlayerObjectOutput.PlayerObject.Properties = _databaseObject.Properties;

                return(new ChannelResponse().Get(loadMyPlayerObjectOutput, this.Request.Headers["playertoken"].First()));
            };
        }
예제 #32
0
        public async Task ShouldUpdateChannel()
        {
            // Arrange
            var request = new UpdateChannelRequest("F9253C29-F09C-4B67-AF7F-E600BC153FD3", new Guid("A2BE089F-696C-4097-80EA-ABDAF31D098D"), "name")
            {
                Description    = "Description",
                WelcomeMessage = "Welcome Message",
                PhotoUrl       = "PhotoUrl"
            };

            var channelCreator = new Member {
                Id = new Guid("137FE248-7BE7-46A1-8D4D-258AD4A1418D")
            };

            var channel = new Channel {
                CreatorId = channelCreator.Id
            };

            _channelRepositoryMock.Setup(x => x.GetChannelAsync(It.Is <Guid>(id => id.Equals(request.ChannelId))))
            .ReturnsAsync(channel)
            .Verifiable();

            _memberRepositoryMock.Setup(x => x.GetMemberBySaasUserIdAsync(It.Is <string>(saasUserId => saasUserId.Equals(request.SaasUserId))))
            .ReturnsAsync(channelCreator)
            .Verifiable();

            const string cloudPhotoUrl = "cloudPhotoUrl";

            _cloudImageProviderMock.Setup(x => x.CopyImageToDestinationContainerAsync(It.Is <string>(photoUrl => photoUrl.Equals(request.PhotoUrl))))
            .ReturnsAsync(cloudPhotoUrl)
            .Verifiable();

            var utcNow = DateTimeOffset.UtcNow;

            _dateTimeProviderMock.Setup(x => x.GetUtcNow())
            .Returns(utcNow)
            .Verifiable();

            Channel channelToUpdate = null;

            _channelRepositoryMock.Setup(x => x.UpdateChannelAsync(It.Is <Channel>(c => c.Equals(channel))))
            .Callback <Channel>(x => channelToUpdate = x)
            .Returns(Task.CompletedTask)
            .Verifiable();

            var mappedChannel = new ChannelResponse();

            _domainModelsMapperMock.Setup(x => x.MapToChannelResponse(It.Is <Channel>(c => c.Equals(channel))))
            .Returns(mappedChannel)
            .Verifiable();

            // Act
            var result = await _channelService.UpdateChannelAsync(request);

            // Assert
            VerifyMocks();

            channelToUpdate.Description.Should().BeEquivalentTo(request.Description);
            channelToUpdate.WelcomeMessage.Should().BeEquivalentTo(request.WelcomeMessage);
            channelToUpdate.Name.Should().BeEquivalentTo(request.Name);
            channelToUpdate.PhotoUrl.Should().BeEquivalentTo(cloudPhotoUrl);
            channelToUpdate.Updated.Should().Be(utcNow);

            result.Should().BeEquivalentTo(mappedChannel);
        }
예제 #33
0
      public static ChannelResponse GetChannelResponseWithError()
      {
         ChannelResponse result = new ChannelResponse();
         result.Message = new ResponseMessage();

         ExceptionMessage message = new ExceptionMessage();
         message.ServiceKey = typeof (FakeProxy).Name;
         message.ExceptionType = "Stub";
         message.ExceptionMessages = new List<string>(new string[1] {"stub"});
         result.Message.ExceptionMessage = message;

         return result;
      }
예제 #34
0
      public static ChannelResponse GetChannelResponse()
      {
         ChannelResponse result = new ChannelResponse();
         result.Message = new ResponseMessage();
         result.Message.SessionTicket = Guid.NewGuid();
         result.Message.ResponseObject = "response";

         using (
            IBinaryMessageSerializer serializer =
               MessageSerializerFactory.CreateBinarySerializer(typeof (ResponseMessage)))
         {
            result.Content = serializer.Serialize(new ResponseMessage());
         }

         return result;
      }