Example #1
0
 public PCMUSession()
 {
     SSRC        = RngProvider.GetRandomNumber();
     Sequence    = 0;
     PayloadType = 0;
     ClockRate   = 8000;
 }
        public IEnumerable <int> GetRolls()
        {
            var rand        = new RngProvider();
            var rollManager = new RollManager(rand);

            return(rollManager.InitialRolls().ToList());
        }
Example #3
0
        internal static byte[] GenerateRandomBytes(int length)
        {
            var bytes = new byte[length];

            RngProvider.GetBytes(bytes);
            return(bytes);
        }
Example #4
0
        public H264Session()
        {
            SSRC         = RngProvider.GetRandomNumber();
            Sequence     = 0;
            PayloadType  = 96;
            lastSequence = 0;

            logger.Debug("H264Session() " + SSRC);
        }
        public void AngCharacter([FromBody] ICollection <int> rolls)
        {
            var character = Map(buffer);
            var rng       = new RngProvider();
            var manager   = new RollManager(rng);

            manager.SetRolls(rolls, character);
            Repo.CreateCharacter(character, buffer.MySkills);
        }
Example #6
0
        public void DeleteCharacterFromDbAlsoDeletesCharStats()
        {
            // arrange
            // In-memory database only exists while the connection is open
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var rand    = new RngProvider();
                var options = new DbContextOptionsBuilder <ANightsTaleContext>()
                              .UseSqlite(connection)
                              .Options;

                // Create the schema in the database
                using (var context = new ANightsTaleContext(options))
                {
                    context.Database.EnsureCreated();
                }

                // Act

                // Run the test against one instance of the context
                using (var context = new ANightsTaleContext(options))
                {
                    var         charRepo = new CharacterRepository(context);
                    DataSeeding seed     = new DataSeeding(context, charRepo);
                    seed.SeedCharacterSupportClasses();

                    var character = seed.SeedCharacter();

                    charRepo.AddCharacter(character);
                    charRepo.Save();

                    var stats = seed.SeedCharStats(character);
                    charRepo.AddCharStats(stats);
                    charRepo.Save();

                    charRepo.RemoveCharacter(1);
                    charRepo.Save();

                    // Assert
                    Assert.False(context.CharStats.Any());
                }
            }
            finally
            {
                connection.Close();
            }
        }
        public void SetAppropriateSavingThrows()
        {
            // arrange
            // In-memory database only exists while the connection is open
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var rand    = new RngProvider();
                var options = new DbContextOptionsBuilder <ANightsTaleContext>()
                              .UseSqlite(connection)
                              .Options;

                // Create the schema in the database
                using (var context = new ANightsTaleContext(options))
                {
                    context.Database.EnsureCreated();
                }

                // Act

                // Run the test against one instance of the context
                using (var context = new ANightsTaleContext(options))
                {
                    var         charRepo = new CharacterRepository(context);
                    DataSeeding seed     = new DataSeeding(context, charRepo);
                    seed.SeedCharacterSupportClasses();

                    var character = seed.SeedCharacter();
                    var stats     = seed.SeedCharStats(character);

                    charRepo.SetSavingThrows(character, stats);

                    // Assert
                    Assert.Equal(-3, stats.STR_Save);
                    Assert.Equal(-1, stats.DEX_Save);
                    Assert.Equal(3, stats.CON_Save);
                    Assert.Equal(2, stats.INT_Save);
                    Assert.Equal(0, stats.WIS_Save);
                    Assert.Equal(-3, stats.CHA_Save);
                }
            }
            finally
            {
                connection.Close();
            }
        }
        /// <summary>
        /// Creates a secret key with the specified number of bits of entropy and specified
        /// <see cref="CryptoSecureRequirement"/> to be shared with the user on wich the future valid TOTP codes will
        /// be based.
        /// </summary>
        /// <param name="bits">The number of bits of entropy to use.</param>
        /// <param name="cryptoSecureRequirement">The <see cref="CryptoSecureRequirement"/> to ensure cryptographically secure RNG's.</param>
        /// <returns>
        /// Returns a string of random values in 'Base32 alphabet' to be shared with the user / stored with the account.
        /// </returns>
        /// <exception cref="CryptographicException">
        /// Thrown when the <see cref="IRngProvider"/> of the instance is not cryptographically secure and the
        /// <see cref="CryptoSecureRequirement"/> requires a cryptographically secure RNG.
        /// </exception>
        public string CreateSecret(int bits, CryptoSecureRequirement cryptoSecureRequirement)
        {
            if (cryptoSecureRequirement == CryptoSecureRequirement.RequireSecure && !RngProvider.IsCryptographicallySecure)
            {
                throw new CryptographicException("RNG provider is not cryptographically secure");
            }

            int bytes = (int)Math.Ceiling((double)bits / 5);    // We use 5 bits of each byte (since we have a

            // 32-character 'alphabet' / base32)

            // Note that we DO NOT actually "base32 encode" the random bytes, we simply take 5 bits from each random
            // byte and map these directly to letters from the base32 alphabet (effectively 'base32 encoding on the fly').
            return(string.Concat(RngProvider.GetRandomBytes(bytes).Select(v => Base32.Base32Alphabet[v & 31])));
        }
Example #9
0
        public void RollsAreInTheRightRange()
        {
            var rand   = new RngProvider();
            var roller = new RollManager(rand);

            var newRolls = new List <int>();

            for (int i = 0; i < 100; i++)
            {
                newRolls = roller.DoRolls().ToList();
                Assert.Equal(3, newRolls.Count);
                for (int j = 0; j < 3; j++)
                {
                    Assert.True(newRolls[j] > 0 && newRolls[j] < 7);
                }
            }
        }
        public void BarbarianProficiencyCalculatedCorrectly()
        {
            // arrange
            // In-memory database only exists while the connection is open
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var rand    = new RngProvider();
                var options = new DbContextOptionsBuilder <ANightsTaleContext>()
                              .UseSqlite(connection)
                              .Options;

                // Create the schema in the database
                using (var context = new ANightsTaleContext(options))
                {
                    context.Database.EnsureCreated();
                }

                // Act

                // Run the test against one instance of the context
                using (var context = new ANightsTaleContext(options))
                {
                    var         charRepo = new CharacterRepository(context);
                    DataSeeding seed     = new DataSeeding(context, charRepo);
                    seed.SeedClass(1);

                    var val = charRepo.GetSavingThrowProficiency(1);

                    // Assert
                    Assert.Equal(new List <bool> {
                        true, false, true, false, false, false
                    }, val);
                }
            }
            finally
            {
                connection.Close();
            }
        }
Example #11
0
    unsafe private int NextImpl()
    {
        lock (Pool.SyncRoot)
        {
            if ((CurrentIndex + 4) > Pool.Length - 1)
            {
                RngProvider.GetBytes(Pool);
                CurrentIndex = 0;
            }
            else
            {
                CurrentIndex += 4;
            }

            fixed(byte *ptr = &Pool[CurrentIndex])
            {
                return(*((int *)ptr));
            }
        }
    }
Example #12
0
    unsafe private ulong SampleImpl()
    {
        lock (Pool.SyncRoot)
        {
            if ((CurrentIndex + 8) > Pool.Length - 1)
            {
                RngProvider.GetBytes(Pool);
                CurrentIndex = 0;
            }
            else
            {
                CurrentIndex += 8;
            }

            fixed(byte *ptr = &Pool[CurrentIndex])
            {
                return(*((UInt64 *)ptr));
            }
        }
    }
Example #13
0
        public void AddClassToDbIsSuccessful()
        {
            // arrange
            // In-memory database only exists while the connection is open
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var rand    = new RngProvider();
                var options = new DbContextOptionsBuilder <ANightsTaleContext>()
                              .UseSqlite(connection)
                              .Options;

                // Create the schema in the database
                using (var context = new ANightsTaleContext(options))
                {
                    context.Database.EnsureCreated();
                }

                // Act

                // Run the test against one instance of the context
                using (var context = new ANightsTaleContext(options))
                {
                    var         charRepo = new CharacterRepository(context);
                    DataSeeding seed     = new DataSeeding(context, charRepo);
                    seed.SeedClass(1);


                    // Assert
                    Assert.Equal(1, context.Class.First().ClassId);
                    Assert.Equal("TestClass", context.Class.First().Name);
                }
            }
            finally
            {
                connection.Close();
            }
        }
Example #14
0
        public void RollsSetProperly()
        {
            var rand   = new RngProvider();
            var roller = new RollManager(rand);

            var        character = new Library.Character();
            List <int> rolls     = new List <int>()
            {
                5, 18, 10, 11, 12, 14
            };

            roller.SetRolls(rolls, character);

            // Assert

            Assert.Equal(5, character.Str);
            Assert.Equal(18, character.Dex);
            Assert.Equal(10, character.Con);
            Assert.Equal(11, character.Int);
            Assert.Equal(12, character.Wis);
            Assert.Equal(14, character.Cha);
        }
        public void InvalidClassIdThrowsException(int id)
        {
            // arrange
            // In-memory database only exists while the connection is open
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var rand    = new RngProvider();
                var options = new DbContextOptionsBuilder <ANightsTaleContext>()
                              .UseSqlite(connection)
                              .Options;

                // Create the schema in the database
                using (var context = new ANightsTaleContext(options))
                {
                    context.Database.EnsureCreated();
                }

                // Act

                // Run the test against one instance of the context
                using (var context = new ANightsTaleContext(options))
                {
                    var         charRepo = new CharacterRepository(context);
                    DataSeeding seed     = new DataSeeding(context, charRepo);
                    seed.SeedClass(3);

                    // Assert
                    Assert.ThrowsAny <ArgumentException>(() => charRepo.GetSavingThrowProficiency(id));
                }
            }
            finally
            {
                connection.Close();
            }
        }
Example #16
0
        public void AddNullCharacterThrowsNullException()
        {
            // arrange
            // In-memory database only exists while the connection is open
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var rand    = new RngProvider();
                var options = new DbContextOptionsBuilder <ANightsTaleContext>()
                              .UseSqlite(connection)
                              .Options;

                // Create the schema in the database
                using (var context = new ANightsTaleContext(options))
                {
                    context.Database.EnsureCreated();
                }

                // Act

                // Run the test against one instance of the context
                using (var context = new ANightsTaleContext(options))
                {
                    var charRepo = new CharacterRepository(context);

                    // Assert
                    Assert.ThrowsAny <ArgumentNullException>(() => charRepo.AddCharacter(null));
                }
            }
            finally
            {
                connection.Close();
            }
        }
Example #17
0
        private void ClientProc()
        {
            var address = "net.tcp://" + ServerAddr + "/ScreenCaster";

            if (this.ServerPort > 0)
            {
                address = "net.tcp://" + ServerAddr + ":" + ServerPort + "/ScreenCaster";
            }
            
            try
            {

                var uri = new Uri(address);
                this.ClientId = RngProvider.GetRandomNumber().ToString();

                //NetTcpSecurity security = new NetTcpSecurity
                //{
                //    Mode = SecurityMode.Transport,
                //    Transport = new TcpTransportSecurity
                //    {
                //        ClientCredentialType = TcpClientCredentialType.Windows,
                //        ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign,
                //    },
                //};

                NetTcpSecurity security = new NetTcpSecurity
                {
                    Mode = SecurityMode.None,
                };

                var binding = new NetTcpBinding
                {
                    ReceiveTimeout = TimeSpan.MaxValue,//TimeSpan.FromSeconds(10),
                    SendTimeout = TimeSpan.FromSeconds(10),
                    Security = security,
                };

                factory = new ChannelFactory<IScreenCastService>(binding, new EndpointAddress(uri));
                var channel = factory.CreateChannel();

                try
                {
                    //channel.PostMessage(new ServerRequest { Command = "Ping" });

                    var channelInfos = channel.GetChannelInfos();

                    if (channelInfos == null)
                    {
                        logger.Error("channelInfos == null");
                        return;
                    }


                    TransportMode transportMode = TransportMode.Udp;
                    var videoChannelInfo = channelInfos.FirstOrDefault(c => c.MediaInfo is VideoChannelInfo);

                    if (videoChannelInfo != null)
                    {
                        transportMode = videoChannelInfo.Transport;

                        if(transportMode == TransportMode.Tcp)
                        {
                            if (videoChannelInfo.ClientsCount > 0)
                            {
                                throw new Exception("Server is busy");
                            }
                        }

                        var videoAddr = videoChannelInfo.Address;

                        if(transportMode == TransportMode.Tcp)
                        {
                            videoAddr = ServerAddr;
                        }

                        var videoPort = videoChannelInfo.Port;

                        //if (string.IsNullOrEmpty(videoAddr))
                        //{
                        //    //channel.Play()
                        //}

                        //if (transportMode == TransportMode.Tcp)
                        //{
                        //   var res = channel.Play(channelInfos);
                        //}

                        var videoInfo = videoChannelInfo.MediaInfo as VideoChannelInfo;
                        if (videoInfo != null)
                        {
                            var inputPars = new VideoEncoderSettings
                            {
                                Resolution = videoInfo.Resolution,
                                //Width = videoInfo.Resolution.Width,
                                //Height = videoInfo.Resolution.Height,
                                FrameRate = new MediaRatio(videoInfo.Fps,
                            };

                            var outputPars = new VideoEncoderSettings
                            {
                                //Width = 640,//2560,
                                //Height = 480,//1440,
                                //Width = 1920,
                                //Height = 1080,

                                //FrameRate = 30,

                                //Width = videoInfo.Resolution.Width,
                                //Height = videoInfo.Resolution.Height,
                                Resolution = videoInfo.Resolution,
                                FrameRate = videoInfo.Fps,

                            };

                            //bool keepRatio = true;
                            //if (keepRatio)
                            //{
                            //    var srcSize = new Size(inputPars.Width, inputPars.Height);
                            //    var destSize = new Size(outputPars.Width, outputPars.Height);


                            //    var ratio = srcSize.Width / (double)srcSize.Height;
                            //    int destWidth = destSize.Width;
                            //    int destHeight = (int)(destWidth / ratio);
                            //    if (ratio < 1)
                            //    {
                            //        destHeight = destSize.Height;
                            //        destWidth = (int)(destHeight * ratio);
                            //    }
                            //    outputPars.Width = destWidth;
                            //    outputPars.Height = destHeight;
                            //}



                            var networkPars = new NetworkSettings
                            {
                                LocalAddr = videoAddr,
                                LocalPort = videoPort,
                                TransportMode = transportMode,

                                SSRC = videoChannelInfo.SSRC,
                            };

                            VideoReceiver = new VideoReceiver();


                            VideoReceiver.Setup(inputPars, outputPars, networkPars);
                            VideoReceiver.UpdateBuffer += VideoReceiver_UpdateBuffer;
                        }

                    }


                    var audioChannelInfo =channelInfos.FirstOrDefault(c => c.MediaInfo is AudioChannelInfo);
                    if (audioChannelInfo != null)
                    {
                        var audioInfo = audioChannelInfo.MediaInfo as AudioChannelInfo;
                        if (audioInfo != null)
                        {

                            var audioAddr = audioChannelInfo.Address;
                            transportMode = audioChannelInfo.Transport;

                            if (transportMode == TransportMode.Tcp)
                            {
                                audioAddr = ServerAddr;
                            }

                            if (transportMode == TransportMode.Tcp)
                            {
                                if (audioChannelInfo.ClientsCount > 0)
                                {
                                    throw new Exception("Server is busy");
                                }
                            }

                            var audioPort = audioChannelInfo.Port;

                            AudioReceiver = new AudioReceiver();

                            var networkPars = new NetworkSettings
                            {
                                LocalAddr = audioAddr,
                                LocalPort = audioPort,
                                TransportMode = transportMode,

                                SSRC = audioChannelInfo.SSRC,

                            };

                            var audioDeviceId = "";
                            try
                            {
                                var devices = DirectSoundOut.Devices;
                                var device = devices.FirstOrDefault();
                                audioDeviceId = device?.Guid.ToString() ?? "";
                            }
                            catch(Exception ex)
                            {
                                logger.Error(ex);
                            }


                            var audioPars = new AudioEncoderSettings
                            {
                                SampleRate = audioInfo.SampleRate,
                                Channels = audioInfo.Channels,
                                Encoding = "ulaw",
                                DeviceId = audioDeviceId,//currentDirectSoundDeviceInfo?.Guid.ToString() ?? "",
                            };

                            AudioReceiver.Setup(audioPars, networkPars);
                        }

                    }


                    if (VideoReceiver != null)
                    {
                        VideoReceiver.Play();
                    }

                    if (AudioReceiver != null)
                    {
                        AudioReceiver.Play();
                    }


                    running = true;

                    State = ClientState.Connected;

                    OnStateChanged(State);

                    while (running)
                    {

                        channel.PostMessage(new ServerRequest { Command = "Ping" });


                        syncEvent.WaitOne(1000);

                        //InternalCommand command = null;
                        //do
                        //{
                        //    command = DequeueCommand();
                        //    if (command != null)
                        //    {
                        //        ProcessCommand(command);
                        //    }

                        //} while (command != null);
                    }


                }
                finally
                {
                    running = false;

                    State = ClientState.Disconnected;
                    OnStateChanged(State);

                    try
                    {
                        var c = (IClientChannel)channel;
                        if (c.State != CommunicationState.Faulted)
                        {
                            c.Close();
                        }
                        else
                        {
                            c.Abort();
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);


                State = ClientState.Faulted;
                OnStateChanged(State);

                //Close();
            }
            finally
            {
                Close();
            }
        }
Example #18
0
        private void ClientProc()
        {
            var address = "net.tcp://" + ServerAddr + "/RemoteDesktop";

            try
            {
                var uri = new Uri(address);
                //NetTcpSecurity security = new NetTcpSecurity
                //{
                //    Mode = SecurityMode.Transport,
                //    Transport = new TcpTransportSecurity
                //    {
                //        ClientCredentialType = TcpClientCredentialType.Windows,
                //        ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign,
                //    },
                //};

                NetTcpSecurity security = new NetTcpSecurity
                {
                    Mode = SecurityMode.None,
                };

                var binding = new NetTcpBinding
                {
                    ReceiveTimeout = TimeSpan.MaxValue,//TimeSpan.FromSeconds(10),
                    SendTimeout    = TimeSpan.FromSeconds(10),
                    Security       = security,
                };


                factory = new ChannelFactory <IRemoteDesktopService>(binding, new EndpointAddress(uri));
                var channel = factory.CreateChannel();

                try
                {
                    this.ClientId = RngProvider.GetRandomNumber().ToString();

                    var connectReq = new RemoteDesktopRequest
                    {
                        SenderId = ClientId,
                    };

                    var connectionResponse = channel.Connect(connectReq);
                    if (!connectionResponse.IsSuccess)
                    {
                        logger.Error("connectionResponse " + connectionResponse.FaultCode);
                        return;
                    }

                    this.ServerId   = connectionResponse.ServerId;
                    this.ServerName = connectionResponse.HostName;

                    var screens       = connectionResponse.Screens;
                    var primaryScreen = screens.FirstOrDefault(s => s.IsPrimary);

                    var startRequest = new StartSessionRequest
                    {
                        SenderId = this.ClientId,

                        SrcRect              = primaryScreen.Bounds,
                        DestAddr             = "", //"192.168.1.135",//localAddr.Address.ToString(), //localAddr.ToString(),
                        DestPort             = 1234,
                        DstSize              = new Size(1920, 1080),
                        EnableInputSimulator = true,
                    };


                    var startResponse = channel.Start(startRequest);
                    if (!startResponse.IsSuccess)
                    {
                        logger.Error("startResponse " + startResponse.FaultCode);
                        return;
                    }

                    var inputPars = new VideoEncoderSettings
                    {
                        Resolution = startRequest.DstSize,
                        //Width = startRequest.DstSize.Width,
                        //Height = startRequest.DstSize.Height,

                        //Width = 640,//2560,
                        //Height = 480,//1440,
                        FrameRate = 30,
                    };

                    var outputPars = new VideoEncoderSettings
                    {
                        //Width = 640,//2560,
                        //Height = 480,//1440,
                        //Width = startRequest.DstSize.Width,
                        //Height = startRequest.DstSize.Height,

                        Resolution = startRequest.DstSize,
                        FrameRate  = 30,
                    };
                    var transport = TransportMode.Udp;

                    var networkPars = new NetworkSettings
                    {
                        LocalAddr     = ServerAddr,
                        LocalPort     = 1234,
                        TransportMode = transport,
                    };

                    this.Play(inputPars, outputPars, networkPars);

                    InputManager = new InputManager();

                    InputManager.Start(ServerAddr, 8888);
                    running = true;

                    State = ClientState.Connected;

                    OnStateChanged(State);

                    while (running)
                    {
                        channel.PostMessage("Ping", null);


                        syncEvent.WaitOne(1000);

                        //InternalCommand command = null;
                        //do
                        //{
                        //    command = DequeueCommand();
                        //    if (command != null)
                        //    {
                        //        ProcessCommand(command);
                        //    }

                        //} while (command != null);
                    }
                }
                finally
                {
                    running = false;

                    State = ClientState.Disconnected;
                    OnStateChanged(State);

                    try
                    {
                        var c = (IClientChannel)channel;
                        if (c.State != CommunicationState.Faulted)
                        {
                            c.Close();
                        }
                        else
                        {
                            c.Abort();
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);


                State = ClientState.Faulted;
                OnStateChanged(State);

                Close();
            }
        }
        public void Connect(string addr, int port)
        {
            tracer.Verb("ScreenCastControl::Connecting(...) " + addr + " " + port);
            hWnd = this.Handle;//this.Parent.Parent.Handle;
            //logger.Debug("RemoteDesktopClient::Connecting(...) " + addr + " " + port);

            state = ClientState.Connecting;

            cancelled = false;
            errorCode = ErrorCode.Ok;

            this.ServerAddr = addr;
            this.ServerPort = port;

            this.ClientId = RngProvider.GetRandomNumber().ToString();

            var address = "net.tcp://" + ServerAddr + "/ScreenCaster";

            if (this.ServerPort > 0)
            {
                address = "net.tcp://" + ServerAddr + ":" + ServerPort + "/ScreenCaster";
            }

            //Console.WriteLine(address);

            UpdateControls();

            mainTask = Task.Run(() =>
            {
                //int maxTryCount = 10;
                uint tryCount = 0;

                bool forceReconnect = (MaxTryConnectCount == uint.MaxValue);

                while ((forceReconnect || tryCount <= MaxTryConnectCount) && !cancelled)
                {
                    tracer.Verb("ScreenCastControl::Connecting count: " + tryCount);

                    //logger.Debug("Connecting count: " + tryCount);
                    //errorMessage = "";
                    errorCode = ErrorCode.Ok;

                    try
                    {
                        var uri = new Uri(address);

                        NetTcpSecurity security = new NetTcpSecurity
                        {
                            Mode = SecurityMode.None,
                        };

                        var binding = new NetTcpBinding
                        {
                            ReceiveTimeout = TimeSpan.MaxValue,//TimeSpan.FromSeconds(10),
                            SendTimeout    = TimeSpan.FromSeconds(5),
                            OpenTimeout    = TimeSpan.FromSeconds(5),

                            Security = security,
                        };

                        //var _uri = new Uri("net.tcp://" + ServerAddr + ":" + 0 + "/ScreenCaster");
                        //factory = new ChannelFactory<IScreenCastService>(binding, new EndpointAddress(_uri));

                        //var viaUri = new Uri("net.tcp://" + ServerAddr + ":" + ServerPort + "/ScreenCaster");
                        //factory.Endpoint.EndpointBehaviors.Add(new System.ServiceModel.Description.ClientViaBehavior(viaUri));

                        factory         = new ChannelFactory <IScreenCastService>(binding, new EndpointAddress(uri));
                        factory.Closed += Factory_Closed;

                        var channel = factory.CreateChannel();

                        try
                        {
                            var channelInfos = channel.GetChannelInfos();

                            state = ClientState.Connected;
                            UpdateControls();
                            Connected?.Invoke();

                            if (channelInfos == null)
                            {
                                errorCode = ErrorCode.NotReady;
                                throw new Exception("Server not configured");
                            }

                            var videoChannelInfo = channelInfos.FirstOrDefault(c => c.MediaInfo is VideoChannelInfo);
                            if (videoChannelInfo != null)
                            {
                                if (videoChannelInfo.Transport == TransportMode.Tcp && videoChannelInfo.ClientsCount > 0)
                                {
                                    errorCode = ErrorCode.IsBusy;
                                    throw new Exception("Server is busy");
                                }
                                SetupVideo(videoChannelInfo);
                            }

                            var audioChannelInfo = channelInfos.FirstOrDefault(c => c.MediaInfo is AudioChannelInfo);
                            if (audioChannelInfo != null)
                            {
                                if (audioChannelInfo.Transport == TransportMode.Tcp && videoChannelInfo.ClientsCount > 0)
                                {
                                    errorCode = ErrorCode.IsBusy;
                                    throw new Exception("Server is busy");
                                }

                                SetupAudio(audioChannelInfo);
                            }

                            if (VideoReceiver != null)
                            {
                                VideoReceiver.Play();
                                // d3dRenderer.Start();
                            }

                            if (AudioReceiver != null)
                            {
                                AudioReceiver.Play();
                            }

                            channel.PostMessage(new ServerRequest {
                                Command = "Ping"
                            });
                            tryCount = 0;

                            state = ClientState.Running;
                            UpdateControls();

                            while (state == ClientState.Running)
                            {
                                try
                                {
                                    channel.PostMessage(new ServerRequest {
                                        Command = "Ping"
                                    });
                                    if (d3dRenderer.ErrorCode != 0)
                                    {
                                        tracer.Warn("ScreenCastControl::imageProvider.ErrorCode: " + d3dRenderer.ErrorCode);

                                        // logger.Debug("imageProvider.ErrorCode: " + videoRenderer.ErrorCode);
                                        //Process render error...
                                    }

                                    //TODO::
                                    // Receivers errors...

                                    syncEvent.WaitOne(1000);
                                }
                                catch (Exception ex)
                                {
                                    state     = ClientState.Interrupted;
                                    errorCode = ErrorCode.Interrupted;
                                }
                            }
                        }
                        finally
                        {
                            CloseChannel(channel);
                        }
                    }
                    catch (EndpointNotFoundException ex)
                    {
                        errorCode = ErrorCode.NotFound;

                        tracer.Error(ex.Message);

                        //logger.Error(ex.Message);

                        //Console.WriteLine(ex.Message);
                    }
                    catch (Exception ex)
                    {
                        tracer.Error(ex);
                        //logger.Error(ex);

                        if (errorCode == ErrorCode.Ok)
                        {
                            errorCode = ErrorCode.Fail;
                        }

                        //Console.WriteLine(ex);
                    }
                    finally
                    {
                        Close();
                    }

                    if (!cancelled)
                    {
                        if (errorCode != ErrorCode.Ok)
                        {
                            UpdateControls();

                            tryCount++;

                            var statusStr = "Attempting to connect..."; // + tryCount; // + " of " + maxTryCount;

                            SetStatus(statusStr);
                        }

                        Thread.Sleep(1000);
                        continue;
                    }
                    else
                    {
                        errorCode = ErrorCode.Cancelled;
                        break;
                    }
                }//while end

                cancelled = false;

                state = ClientState.Disconnected;
                UpdateControls();

                Disconnected?.Invoke(null);
            });
        }
Example #20
0
 public RollManager(RngProvider rand)
 {
     _rand = rand;
 }