示例#1
0
		public MetaDaemonApi(	RpcConfig bitsharesConfig, RpcConfig bitcoinConfig, 
								string bitsharesAccount,
								string databaseName, string databaseUser, string databasePassword,
								string listenAddress,
								string bitcoinFeeAddress,
								string bitsharesFeeAccount,
								string adminUsernames,
								string masterSiteUrl,
								string masterSiteIp,
								AsyncPump scheduler) : 
								base(bitsharesConfig, bitcoinConfig, bitsharesAccount, adminUsernames,
								databaseName, databaseUser, databasePassword)
		{
			m_bitshaaresFeeAccount = bitsharesFeeAccount;
			m_bitcoinFeeAddress = bitcoinFeeAddress;
			m_masterSiteUrl = masterSiteUrl.TrimEnd('/');

			m_scheduler = scheduler;

			ServicePointManager.ServerCertificateValidationCallback = Validator;

			Serialisation.Defaults();

			// don't ban on exception here because we'll only end up banning the webserver!
			m_server = new ApiServer<IDummyDaemon>(new string[] { listenAddress }, null, false, eDdosMaxRequests.Ignore, eDdosInSeconds.One);

			m_api = new SharedApi<IDummyDaemon>(m_dataAccess);
			m_server.ExceptionEvent += m_api.OnApiException;
			
			// only allow the main site to post to us
			m_server.SetIpLock(masterSiteIp);

			m_marketHandlers = new Dictionary<string,MarketBase>();

			// get all market pegged assets
			List<BitsharesAsset> allAssets = m_bitshares.BlockchainListAssets("", int.MaxValue);
			m_allBitsharesAssets = allAssets.ToDictionary(a => a.id);
			Dictionary<int, BitsharesAsset> peggedAssets = allAssets.Where(a => a.issuer_id <= 0).ToDictionary(a => a.id);
			

			// get all active markets containing those assets
			m_allDexMarkets = m_bitshares.BlockchainListMarkets().Where(m => m.last_error == null &&
																		peggedAssets.ContainsKey(m.base_id) &&
																		peggedAssets.ContainsKey(m.quote_id)).ToList();

			m_allCurrencies = m_dataAccess.GetAllCurrencies();

			List<MarketRow> markets = GetAllMarkets();
			foreach (MarketRow r in markets)
			{
				m_marketHandlers[r.symbol_pair] = CreateHandlerForMarket(r);
			}
			
			m_server.HandlePostRoute(Routes.kSubmitAddress,				OnSubmitAddress, eDdosMaxRequests.Ignore, eDdosInSeconds.Ignore, false);
			m_server.HandleGetRoute(Routes.kGetAllMarkets,				OnGetAllMarkets, eDdosMaxRequests.Ignore, eDdosInSeconds.Ignore, false);
		}
示例#2
0
        static void Main(string[] args)
        {
            if (args.Length == 17)
            {
                string bitsharesUrl = args[0];
                string bitsharesUser = args[1];
                string bitsharesPassword = args[2];
                string bitsharesAccount = args[3];

                string bitcoinUrl = args[4];
                string bitcoinUser = args[5];
                string bitcoinPassword = args[6];
                bool bitcoinUseTestNet = bool.Parse(args[7]);

                string database = args[8];
                string databaseUser = args[9];
                string databasePassword = args[10];

                string apiListen = args[11];

                string bitcoinFeeAddress = args[12];
                string bitsharesFeeAccount = args[13];
                string adminUsernames = args[14];

                string masterSiteUrl = args[15];
                string masterSiteIp = args[16];

                // create a scheduler so we can be sure of thread affinity
                AsyncPump scheduler = new AsyncPump(Thread.CurrentThread, OnException);

                using (MetaDaemonApi daemon = new MetaDaemonApi(new RpcConfig { m_url = bitsharesUrl, m_rpcUser = bitsharesUser, m_rpcPassword = bitsharesPassword },
                                                                new RpcConfig { m_url = bitcoinUrl, m_rpcUser = bitcoinUser, m_rpcPassword = bitcoinPassword, m_useTestnet = bitcoinUseTestNet },
                                                                bitsharesAccount,
                                                                database, databaseUser, databasePassword,
                                                                apiListen,
                                                                bitcoinFeeAddress, bitsharesFeeAccount, adminUsernames,
                                                                masterSiteUrl, masterSiteIp,
                                                                scheduler))
                {
                    scheduler.RunWithUpdate(daemon.Start, daemon.Update, 5);
                }

                Console.WriteLine("Exiting...");
            }
            else
            {
                Console.WriteLine("Error, usage.");
            }
        }
示例#3
0
        static void Main(string[] args)
        {
            if (!string.IsNullOrWhiteSpace(accessKey))
            {
                accessKeys = new WorkspaceCollectionKeys
                {
                    Key1 = accessKey
                };
            }

            AsyncPump.Run(async delegate
            {
                await Run();
            });

            Console.ReadKey(true);
        }
 public void StaticReactToChangesTest()
 {
     #region Static React to Changes
     AsyncPump.Run(
         async() =>
     {
         using (var client = await ConnectAsync("localhost", 9000))
             using (var consumer = await Consumer <SapphireRoot> .CreateAsync(client))
             {
                 var valueChanged                   = new TaskCompletionSource <string>();
                 var positionParameter              = consumer.Root.Sapphire.Sources.Fpgm1.Fader.Position;
                 positionParameter.PropertyChanged += (s, e) => valueChanged.SetResult(((IElement)s).GetPath());
                 Console.WriteLine("Waiting for the parameter to change...");
                 Console.WriteLine("A value of the element with the path {0} has been changed.", await valueChanged.Task);
             }
     });
     #endregion
 }
示例#5
0
        public static void Main(string[] args)
        {
            AsyncPump.Run(async() =>
            {
                var controller = new Controller();

                try
                {
                    await controller.Run();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }

                await Task.Delay(TimeSpan.FromMinutes(1));
            });
        }
示例#6
0
        public void WriteAsyncTest()
        {
            AsyncPump.Run(
                async() =>
            {
                var bytes = new byte[2];
                this.Random.NextBytes(bytes);

                // This covers the case where the written bytes are copied into the buffer in two chunks
                using (var stream = new MemoryStream())
                {
                    var writeBuffer = new WriteBuffer(stream.WriteAsync, 1);
                    await writeBuffer.WriteAsync(bytes, 0, bytes.Length, CancellationToken.None);
                    await writeBuffer.FlushAsync(CancellationToken.None);
                    CollectionAssert.AreEqual(bytes, stream.ToArray());
                }
            });
        }
        public void VersionTest()
        {
            AsyncPump.Run(() => TestWithRobot <S101Payloads>(
                              client =>
            {
                client.EmberDataReceived += (s, e) =>
                {
                    Console.WriteLine(e.Message.Command.ToString());
                };

                return(Task.FromResult(false));
            },
                              null,
                              null,
                              new EmberTypeBag(),
                              true,
                              "VersionLog.xml"));
        }
        public void ExceptionTest()
        {
            using (var dummy = new MemoryStream())
            {
                ReadAsyncCallback  fakeRead  = (b, o, c, t) => Task.FromResult(0);
                WriteAsyncCallback fakeWrite = (b, o, c, t) => Task.FromResult(false);
                AssertThrow <NotSupportedException>(() => new S101Client(dummy, fakeRead, fakeWrite).Dispose());

                AsyncPump.Run(
                    async() =>
                {
                    using (var connection = new CompleteOnDispose())
                        using (var client = new S101Client(connection, (b, o, c, t) => connection.Task, fakeWrite))
                        {
                            await AssertThrowAsync <InvalidOperationException>(
                                () => Task.Run(() => client.SendMessageAsync(new S101Message(0x00, new KeepAliveRequest()))));
                        }

                    AssertThrow <ArgumentNullException>(
                        () => new S101Client(null, fakeRead, fakeWrite).Dispose(),
                        () => new S101Client(dummy, null, fakeWrite).Dispose(),
                        () => new S101Client(dummy, fakeRead, null).Dispose());

                    AssertThrow <ArgumentOutOfRangeException>(
                        () => new S101Client(dummy, fakeRead, fakeWrite, null, 3000, 0).Dispose(),
                        () => new S101Client(dummy, fakeRead, fakeWrite, null, -2, 1).Dispose());

                    using (var connection = new CompleteOnDispose())
                        using (var client = new S101Client(
                                   connection, (b, o, c, t) => connection.Task, fakeWrite, null, 3000, 1))
                        {
                            await AssertThrowAsync <ArgumentNullException>(
                                () => client.SendMessageAsync(null));
                            await AssertThrowAsync <ArgumentException>(() => client.SendMessageAsync(EmberDataMessage));
                            await AssertThrowAsync <ArgumentException>(() => client.SendOutOfFrameByteAsync(0xFE));

                            client.Dispose();
                            await AssertThrowAsync <ObjectDisposedException>(
                                () => client.SendMessageAsync(new S101Message(0x00, new KeepAliveRequest())));
                        }
                });
            }
        }
示例#9
0
        static void Main(string[] args)
        {
            if (args.Length == 14)
            {
                string bitsharesUrl = args[0];
                string bitsharesUser = args[1];
                string bitsharesPassword = args[2];
                string bitsharesAccount = args[3];
                string bitsharesAssetName = args[4];

                string bitcoinUrl = args[5];
                string bitcoinUser = args[6];
                string bitcoinPassword = args[7];
                bool bitcoinUseTestNet = bool.Parse(args[8]);
                string bitcoinDepositAddress = args[9];

                string database = args[10];
                string databaseUser = args[11];
                string databasePassword = args[12];

                string apiListen = args[13];

                // create a scheduler so we can be sure of thread affinity
                AsyncPump scheduler = new AsyncPump(Thread.CurrentThread, OnException);

                DaemonApi daemon = new DaemonApi(		new RpcConfig { m_url = bitsharesUrl, m_rpcUser = bitsharesUser, m_rpcPassword = bitsharesPassword },
                                                        new RpcConfig { m_url = bitcoinUrl, m_rpcUser = bitcoinUser, m_rpcPassword = bitcoinPassword, m_useTestnet = bitcoinUseTestNet },
                                                        bitsharesAccount, bitsharesAssetName, bitcoinDepositAddress,
                                                        database, databaseUser, databasePassword,
                                                        apiListen);

                scheduler.RunWithUpdate(daemon.Start, daemon.Update, 1 );

                Console.WriteLine("Exiting...");
            }
            else
            {
                Console.WriteLine("Error, usage: BtsOnRampDamon.exe <bitshares rpc url> <bitshares rpc user> <bitshares rpc password> " +
                                    "<bitshares asset name> <bitcoin rpc url> <bitcoin rpc user> <bitcoin rpc password> <use bitcoin testnet> <bitcoin deposit address> " +
                                    "<myql database name> <mysql database user> <mysql database password> <api listen address>");
            }
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        #region Main Method
        private static void Main()
        {
            // This is necessary so that we can execute async code in a console application.
            AsyncPump.Run(
                async() =>
            {
                // Establish S101 protocol
                using (S101Client client = await ConnectAsync("localhost", 9000))

                    // Retrieve *all* elements in the provider database and store them in a local copy
                    using (Consumer <MyRoot> consumer = await Consumer <MyRoot> .CreateAsync(client))
                    {
                        // Get the root of the local database.
                        INode root = consumer.Root;

                        // For now just output the number of direct children under the root node.
                        Console.WriteLine(root.Children.Count);
                    }
            });
        }
示例#11
0
 public void WriteTest()
 {
     AsyncPump.Run(
         async() =>
     {
         CollectionAssert.AreEqual(
             new byte[] { 0xFE, 0x00, 0x0E, 0x01, 0x01, 0x94, 0xE4, 0xFF },
             await Encode(new S101Message(0x00, new KeepAliveRequest())));
         CollectionAssert.AreEqual(
             new byte[] { 0xFE, 0x00, 0x0E, 0x02, 0x01, 0xFD, 0xDC, 0xCE, 0xFF },
             await Encode(new S101Message(0x00, new KeepAliveResponse())));
         CollectionAssert.AreEqual(
             new byte[]
         {
             0xFE, 0x00, 0x0E, 0x00, 0x01, 0x80, 0x01, 0x02, 0x0a, 0x02, 0xF5, 0x78, 0xFF,
             0xFE, 0x00, 0x0E, 0x00, 0x01, 0x60, 0x01, 0x02, 0x0a, 0x02, 0x13, 0x53, 0xFF
         },
             await Encode(EmberDataMessage, new byte[] { }));
     });
 }
        async Task HandleTransportAsync(IAsyncTransport transport)
        {
            if (this.saslMechanisms != null)
            {
                ListenerSasProfile profile = new ListenerSasProfile(this);
                transport = await profile.OpenAsync(null, transport);
            }

            Connection connection = new ListenerConnection(this, this.address, transport);

            connection.Closed += this.OnConnectionClosed;
            lock (this.connections)
            {
                this.connections.Add(connection);
            }

            AsyncPump pump = new AsyncPump(transport);

            pump.Start(connection);
        }
        public void ConnectionLostTest()
        {
            #region Connection Lost
            AsyncPump.Run(
                async() =>
            {
                using (var client = await ConnectAsync("localhost", 9000))
                    using (var consumer = await Consumer <MyRoot> .CreateAsync(client))
                    {
                        var connectionLost       = new TaskCompletionSource <Exception>();
                        consumer.ConnectionLost += (s, e) => connectionLost.SetResult(e.Exception);

                        Console.WriteLine("Waiting for the provider to disconnect...");
                        var exception = await connectionLost.Task;
                        Console.WriteLine("Connection Lost!");
                        Console.WriteLine("Exception:{0}{1}", exception, Environment.NewLine);
                    }
            });
            #endregion
        }
        public void IncomingTest()
        {
            AsyncPump.Run(() => AssertThrowAsync <S101Exception>(() => TestWithRobot <S101Payloads>(
                                                                     async client =>
            {
                using (var stream = new MemoryStream())
                {
                    using (var writer = new EmberWriter(stream))
                    {
                        writer.WriteValue(EmberId.CreateApplication(0), false);
                    }

                    await client.SendMessageAsync(EmberDataMessage, stream.ToArray());
                }
            },
                                                                     null,
                                                                     null,
                                                                     Types,
                                                                     false,
                                                                     "IncomingLog.xml")));
        }
        public void EmberDataTest()
        {
            AsyncPump.Run(() => TestNoExceptionsAsync(
                              async(consumer, provider) =>
            {
                var slot = (byte)this.Random.Next(byte.MaxValue + 1);
                var data = new byte[this.Random.Next(512, 16384)];
                this.Random.NextBytes(data);

                var emberDataReceived = new TaskCompletionSource <bool>();
                EventHandler <MessageReceivedEventArgs> emberDataHandler =
                    (s, e) =>
                {
                    Assert.AreEqual(slot, e.Message.Slot);
                    Assert.IsInstanceOfType(e.Message.Command, typeof(EmberData));
                    CollectionAssert.AreEqual(data, e.GetPayload());
                    emberDataReceived.SetResult(true);
                };

                var outOfFrameByte         = this.GetRandomByteExcept(0xFE);
                var outOfFrameByteReceived = new TaskCompletionSource <bool>();
                EventHandler <OutOfFrameByteReceivedEventArgs> outOfFrameByteHandler =
                    (s, e) =>
                {
                    Assert.AreEqual(outOfFrameByte, e.Value);
                    outOfFrameByteReceived.SetResult(true);
                };

                provider.EmberDataReceived      += emberDataHandler;
                provider.OutOfFrameByteReceived += outOfFrameByteHandler;
                await consumer.SendMessageAsync(new S101Message(slot, EmberDataCommand), data);
                await emberDataReceived.Task;
                await consumer.SendOutOfFrameByteAsync(outOfFrameByte);
                await outOfFrameByteReceived.Task;
                provider.OutOfFrameByteReceived -= outOfFrameByteHandler;
                provider.EmberDataReceived      -= emberDataHandler;
            },
                              () => ConnectAsync(-1, null),
                              () => WaitForConnectionAsync(null)));
        }
示例#16
0
        /// <summary>
        /// Compares two files using binary or text comparison methods.
        /// </summary>
        /// <param name="fileA"></param>
        /// <param name="fileB"></param>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <param name="args"></param>
        /// <param name="progress"></param>
        private DiffBinaryTextResults GetFileLines(IFileInfo fileA
                                                   , IFileInfo fileB
                                                   , TextBinaryDiffArgs args
                                                   , IDiffProgress progress)
        {
            // Nothing to compare if both files do not exist
            if (fileA.FileExists == false && fileB.FileExists == false)
            {
                return(new DiffBinaryTextResults(CompareType.Text, new FileContentInfo(), new FileContentInfo()));
            }

            if (args.CompareType == CompareType.Binary ||
                (args.IsAuto && fileA.Is == FileType.Binary || fileB.Is == FileType.Binary))
            {
                return(GetBinaryFileLines(fileA, fileB, args, progress));
            }

            FileContentInfo af = null, bf = null;

            if (fileA.FileExists)
            {
                af = AsyncPump.Run(() => FileEx.GetFileTextAsync(fileA.FullName));
            }
            else
            {
                af = new FileContentInfo();
            }

            if (fileB.FileExists)
            {
                bf = AsyncPump.Run(() => FileEx.GetFileTextAsync(fileB.FullName));
            }
            else
            {
                bf = new FileContentInfo();
            }

            return(new DiffBinaryTextResults(CompareType.Text, af, bf));
        }
        public void Async_transaction_should_flow()
        {
            // Given
            Transaction transactionBeforeDbCall = null;
            Transaction transactionAfterDbCall  = null;

            using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                transactionBeforeDbCall = Transaction.Current;
                AsyncPump.Run(async() =>
                {
                    // When
                    await MakeDatabaseCall().ConfigureAwait(false);
                    transactionAfterDbCall = Transaction.Current;
                });
                tran.Complete();
            }

            // Then
            Assert.That(transactionBeforeDbCall, Is.Not.Null);
            Assert.That(transactionAfterDbCall, Is.Not.Null);
        }
        public void MixedModifyTest()
        {
            #region Mixed Modify
            AsyncPump.Run(
                async() =>
            {
                using (var client = await ConnectAsync("localhost", 9000))
                    using (var consumer = await Consumer <MixedSapphireRoot> .CreateAsync(client))
                    {
                        foreach (var source in consumer.Root.Sapphire.Sources.Children)
                        {
                            source.Fader.DBValue.Value    = -67.0;
                            source.Fader.Position.Value   = 128;
                            source.Dsp.Input.LRMode.Value = LRMode.Mono;
                            source.Dsp.Input.Phase.Value  = false;
                        }

                        await consumer.SendAsync();
                    }
            });
            #endregion
        }
示例#19
0
        static void Main(string[] args)
        {
            if (args.Length >= 5 && args.Length <= 6)
            {
                string httpUrl = args[0];

                string database = args[1];
                string databaseUser = args[2];
                string databasePassword = args[3];

                bool maintenance = bool.Parse(args[4]);
                string ipLock = null;
                if (args.Length == 6)
                {
                    ipLock = args[5];
                }

                using (m_gServer = new MetaServer(httpUrl, Constants.kWebRoot, database, databaseUser, databasePassword, maintenance))
                {
                    AsyncPump scheduler = new AsyncPump(Thread.CurrentThread, OnException);

                    m_gServer.ExceptionEvent += OnServerException;

                    if (ipLock != null)
                    {
                        m_gServer.SetIpLock(ipLock);
                    }

                    scheduler.RunWithUpdate(m_gServer.Start, m_gServer.Update, Constants.kUpdateTimeoutSeconds);

                    Console.WriteLine("Exiting...");
                }
            }
            else
            {
                Console.WriteLine("Error, usage.");
            }
        }
示例#20
0
        static void Main(string[] args)
        {
            if (args.Length >= 5 && args.Length <= 6)
            {
                string httpUrl = args[0];

                string database         = args[1];
                string databaseUser     = args[2];
                string databasePassword = args[3];

                bool   maintenance = bool.Parse(args[4]);
                string ipLock      = null;
                if (args.Length == 6)
                {
                    ipLock = args[5];
                }

                using (m_gServer = new MetaServer(httpUrl, Constants.kWebRoot, database, databaseUser, databasePassword, maintenance))
                {
                    AsyncPump scheduler = new AsyncPump(Thread.CurrentThread, OnException);

                    m_gServer.ExceptionEvent += OnServerException;

                    if (ipLock != null)
                    {
                        m_gServer.SetIpLock(ipLock);
                    }

                    scheduler.RunWithUpdate(m_gServer.Start, m_gServer.Update, Constants.kUpdateTimeoutSeconds);

                    Console.WriteLine("Exiting...");
                }
            }
            else
            {
                Console.WriteLine("Error, usage.");
            }
        }
示例#21
0
        static void InitializeContainer()
        {
            DirectoryCatalog moduleCatalog = new DirectoryCatalog(ConfigurationManager.AppSettings["moduleFolder"], "*.dll");

            /// monitor the Modules folder for dlls
            _watcher                     = new FileSystemWatcher(ConfigurationManager.AppSettings["moduleFolder"], "*.dll");
            _watcher.Created            += (sender, e) => { moduleCatalog.Refresh(); };
            _watcher.Changed            += (sender, e) => { moduleCatalog.Refresh(); };
            _watcher.EnableRaisingEvents = true;

            // load Mef container
            ObjectBase.Container = MEFLoader.Init(new List <ComposablePartCatalog>()
            {
                moduleCatalog
                , new AssemblyCatalog(Assembly.GetExecutingAssembly())
                , new AssemblyCatalog(typeof(AlgorithmBase).Assembly)
                //, new DirectoryCatalog(Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath))
            });

            // start the strategy algorithm if one was added
            ObjectBase.Container.ExportsChanged += (sender, e) =>
            {
                foreach (var item in e.AddedExports)
                {
                    if (item.ContractName == "MarketMiner.Algorithm.Common.Contracts.IAlgorithm")
                    {
                        Console.WriteLine(string.Format("\nNew {0} snap-in detected.", item.ContractName));

                        //ObjectBase.Container.ComposeExportedValue(item);
                        IAlgorithm algorithm = item as IAlgorithm;
                        _algorithms.Add(algorithm);

                        AsyncPump.Run(() => Task.Factory.StartNew(() => StartAlgorithm(algorithm)));
                        //Task.Factory.StartNew(() => StartAlgorithm(algorithm));
                    }
                }
            };
        }
        static void Main(string[] args)
        {
            if (!string.IsNullOrWhiteSpace(accessKey))
            {
                accessKeys = new WorkspaceCollectionKeys
                {
                    Key1 = accessKey
                };
            }

            SetupCommands();
            userInput = new UserInput();
            AsyncPump.Run(async delegate
            {
                bool execute = true;
                while (execute)
                {
                    execute = await Run();
                }
            });
            Console.WriteLine("Enter any key to terminate: ");
            Console.ReadKey(true);
        }
示例#23
0
        public void MainTest()
        {
            AsyncPump.Run(
                async() =>
            {
                var proTask = WaitForConnectionAsync(9000);

                using (var conTcp = new TcpClient())
                {
                    await conTcp.ConnectAsync("localhost", 8999);

                    using (var proTcp = await proTask)
                    {
                        var proStream = proTcp.GetStream();

                        using (var proS101 = new S101Client(proTcp, proStream.ReadAsync, proStream.WriteAsync))
                        {
                            var conStream = conTcp.GetStream();

                            using (var conS101 = new S101Client(conTcp, conStream.ReadAsync, conStream.WriteAsync))
                                using (var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(
                                           typeof(ModelPayloads), "SapphireLog.xml"))
                                    using (var reader = XmlReader.Create(resourceStream))
                                    {
                                        var robotTask = S101Robot.RunAsync(proS101, GlowTypes.Instance, reader, true);

                                        using (await Consumer <EmptyDynamicRoot> .CreateAsync(conS101))
                                        {
                                            await conS101.SendOutOfFrameByteAsync(0x00);
                                            await robotTask;
                                        }
                                    }
                        }
                    }
                }
            });
        }
        public void KeepAliveExceptionTest()
        {
            AsyncPump.Run(
                async() =>
            {
                var providerTask = WaitForConnectionAsync();
                int timeout      = this.Random.Next(4000, 8000);
                Console.WriteLine("Timeout: {0}", timeout);

                using (var consumer = new TcpClient("localhost", 8099))
                    using (var stream = consumer.GetStream())
                        using (var logger = new S101Logger(GlowTypes.Instance, Console.Out))
                            using (var consumerClient =
                                       new S101Client(consumer, stream.ReadAsync, stream.WriteAsync, logger, timeout, 8192))
                            {
                                (await providerTask).Ignore();
                                consumerClient.KeepAliveRequestSlot = (byte)this.Random.Next(byte.MaxValue + 1);
                                var source = new TaskCompletionSource <bool>();
                                consumerClient.ConnectionLost += (s, e) => OnConnectionLost(source, e);
                                var task = await Task.WhenAny(source.Task, Task.Delay(timeout + (timeout / 4)));
                                await AssertThrowAsync <S101Exception>(() => task);
                            }
            });
        }
示例#25
0
        public void LogEventTest()
        {
            AsyncPump.Run(
                async() =>
            {
                TestLogListener listener = new TestLogListener(EventLevel.Verbose);

                string logMessage = "Test the debug log";
                string moduleName = "LawoTest";

                Log.Debug(logMessage, moduleName);

                var logEvent = await WaitForLogEventAsync(listener.LogEvents, logMessage);

                Assert.AreEqual(EventLevel.Verbose, logEvent.EventLevel);
                Assert.AreEqual(1, logEvent.EventId);

                Assert.AreEqual(logMessage, logEvent.LogMessage);
                Assert.AreEqual(NativeMethods.GetCurrentThreadId(), logEvent.ThreadId);
                Assert.IsTrue(logEvent.FilePath.Contains("LogTest.cs"));
                Assert.AreEqual(37, logEvent.LineNumber);
                Assert.AreEqual(moduleName, logEvent.ModluleName);
            });
        }
        public void SkipTest()
        {
            AsyncPump.Run(() => TestWithRobot <S101Payloads>(
                              async client =>
            {
                var done  = new TaskCompletionSource <bool>();
                var count = 0;

                client.EmberDataReceived += (s, e) =>
                {
                    if (++count == 3)
                    {
                        done.SetResult(true);
                    }
                };

                await done.Task;
            },
                              null,
                              null,
                              Types,
                              true,
                              "SkipLog.xml"));
        }
 public void SendHandshakeAsync()
 {
     AsyncPump.Run(() => _target.ConnectAsync("ws://echo.websocket.org"));
     AsyncPump.Run(() => _target.SendHandshakeAsync());
 }
 public void ConnectAsync()
 {
     AsyncPump.Run(() => _target.ConnectAsync("ws://echo.websocket.org"));
 }
示例#29
0
        static void Main(string[] args)
        {
            InitializeContainer();

            try
            {
                bool runTests    = false;
                bool okToStart   = true;
                bool ignoreTests = true;

                Console.WriteLine("\nStarting MarketMiner.Algorithms ...");

                #region tests .. move to unit tests?
                if (runTests)
                {
                    Console.WriteLine("\nTests running. Please wait ...");

                    var tests = new CustomOANDARestTest();

                    // hook up the prop change handler
                    tests.Results.PropertyChanged += ((s, e) =>
                    {
                        //Console.WriteLine(((RestTestResults)s).LastMessage);
                    });

                    // run
                    var task = tests.RunTest(EEnvironment.Practice, Security.Token.PracticeToken, Security.Account.PracticeAccount);
                    task.Wait();

                    Console.WriteLine(string.Format("\nTests complete. There were {0} failures.", tests.Failures));

                    // run starts?
                    okToStart = tests.Failures.Equals(0);
                    if (!okToStart)
                    {
                        short tickErrors = 0;
                        foreach (var message in tests.Results.Messages.Values)
                        {
                            if (message.IndexOf("False").Equals(0) && message.ToLower().Contains("streaming tick"))
                            {
                                tickErrors++;
                            }
                        }

                        okToStart = tickErrors == 0;
                    }
                }
                #endregion

                if (okToStart || ignoreTests)
                {
                    AsyncPump.Run(() => StartAlgorithms());
                }

                Console.WriteLine("\nMarketMiner.Algorithms is started. Please press enter to Exit");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("\nMarketMiner.Algorithms has faulted. Please press enter to Exit");
                Console.WriteLine("\nERROR: " + ex.Message);
                Console.WriteLine("\nPlease press enter to Exit.");

                Console.ReadLine();
            }
        }
示例#30
0
 public static Stream CreateWriteSync(this IFile file)
 {
     return(AsyncPump.Run <Stream>(() => file.CreateWrite()));
 }
示例#31
0
 public static void SingleThreadedContext()
 {
     Console.WriteLine("SingleThreadedContext");
     AsyncPump.Run(async() => await DoWorkAsync());
 }
        public void ExceptionTest()
        {
            TestStandardExceptionConstructors <S101Exception>();

            AsyncPump.Run(
                async() =>
            {
                new S101Reader((b, o, c, t) => Task.FromResult(0)).Ignore();

                AssertThrow <ArgumentNullException>(() => new S101Reader(null, 1).Ignore());
                AssertThrow <ArgumentOutOfRangeException>(() => new S101Reader((b, o, c, t) => Task.FromResult(0), 0).Ignore());

                using (var input = new MemoryStream(
                           new byte[] { 0xFE, 0x00, 0x0E, 0x01, 0x01, 0x94, 0xE4, 0xFF, 0xFE, 0x00, 0x0E, 0x02, 0x01, 0xFD, 0xDC, 0xCE, 0xFF }))
                {
                    var reader = new S101Reader(input.ReadAsync, 1);
                    AssertThrow <InvalidOperationException>(() => reader.Message.Ignore());
                    AssertThrow <InvalidOperationException>(() => reader.Payload.Ignore());
                    Assert.IsTrue(await reader.ReadAsync(CancellationToken.None));
                    Assert.IsInstanceOfType(reader.Message.Command, typeof(KeepAliveRequest));
                    Assert.AreEqual(0, await reader.Payload.ReadAsync(new byte[1], 0, 1, CancellationToken.None));
                    AssertThrow <NotSupportedException>(
                        () => reader.Payload.Read(new byte[1], 0, 1),
                        () => reader.Payload.Write(new byte[1], 0, 1));
                    Assert.IsTrue(await reader.ReadAsync(CancellationToken.None));
                    Assert.IsInstanceOfType(reader.Message.Command, typeof(KeepAliveResponse));
                    Assert.AreEqual(0, await reader.Payload.ReadAsync(new byte[1], 0, 1, CancellationToken.None));
                    Assert.IsFalse(await reader.ReadAsync(CancellationToken.None));
                    AssertThrow <InvalidOperationException>(() => reader.Message.Ignore());
                    AssertThrow <InvalidOperationException>(() => reader.Payload.Ignore());
                    await reader.DisposeAsync(CancellationToken.None);
                    await AssertThrowAsync <ObjectDisposedException>(() => reader.ReadAsync(CancellationToken.None));
                    AssertThrow <ObjectDisposedException>(
                        () => reader.Message.Ignore(), () => reader.Payload.Ignore());
                }

                await AssertEmpty(0xFE, 0xFF);
                await AssertEmpty(0xFE, 0xFE);

                for (byte invalid = 0xF8; invalid < 0xFD; ++invalid)
                {
                    await AssertEmpty(0xFE, invalid);
                }

                for (ushort invalid = 0xF8; invalid < 0x100; ++invalid)
                {
                    await AssertEmpty(0xFE, 0xFD, (byte)invalid);
                }

                await AssertS101Exception("Unexpected end of stream.", 0xFE, 0x00, 0x00, 0x00);

                await AssertS101Exception("Unexpected end of stream.", 0xFE, 0x00, 0x0E, 0x00, 0x00, 0x00);

                await AssertS101Exception(
                    "Unexpected end of stream.",
                    0xFE, 0x00, 0x0E, 0x00, 0x01, 0x80, 0x01, 0x02, 0x0A, 0x02, 0xF5, 0x78, 0xFF);

                await AssertS101Exception(
                    "Inconsistent Slot in multi-packet message.",
                    0xFE, 0x00, 0x0E, 0x00, 0x01, 0x80, 0x01, 0x02, 0x0A, 0x02, 0xF5, 0x78, 0xFF,
                    0xFE, 0x01, 0x0E, 0x00, 0x01, 0x60, 0x01, 0x02, 0x0A, 0x02, 0x00, 0x00, 0x00);

                await AssertS101Exception(
                    "Unexpected Message Type.",
                    0xFE, 0x00, 0x0F, 0x00, 0x01, 0x80, 0x01, 0x02, 0x0A, 0x02, 0x00, 0x00, 0x00);

                await AssertS101Exception(
                    "Unexpected Command.", 0xFE, 0x00, 0x0E, 0x04, 0x01, 0x80, 0x01, 0x02, 0x0A, 0x02, 0x00, 0x00, 0x00);

                await AssertS101Exception(
                    "Inconsistent Command in multi-packet message.",
                    0xFE, 0x00, 0x0E, 0x00, 0x01, 0x80, 0x01, 0x02, 0x0A, 0x02, 0xF5, 0x78, 0xFF,
                    0xFE, 0x00, 0x0E, 0x01, 0x01, 0x60, 0x01, 0x02, 0x0A, 0x02, 0x00, 0x00, 0x00);

                await AssertS101Exception(
                    "Unexpected Version.", 0xFE, 0x00, 0x0E, 0x00, 0x00, 0x80, 0x01, 0x02, 0x0A, 0x02, 0x00, 0x00, 0x00);

                await AssertS101Exception(
                    "Missing FirstPacket flag in first packet.",
                    0xFE, 0x00, 0x0E, 0x00, 0x01, 0x20, 0x01, 0x02, 0x0A, 0x02, 0x00, 0x00, 0x00);

                await AssertS101Exception(
                    "FirstPacket flag in subsequent packet.",
                    0xFE, 0x00, 0x0E, 0x00, 0x01, 0x80, 0x01, 0x02, 0x0A, 0x02, 0xF5, 0x78, 0xFF,
                    0xFE, 0x00, 0x0E, 0x00, 0x01, 0xE0, 0x01, 0x02, 0x0A, 0x02, 0x00, 0x00, 0x00);
            });
        }
        async Task HandleTransportAsync(IAsyncTransport transport)
        {
            if (this.saslSettings != null)
            {
                ListenerSaslProfile profile = new ListenerSaslProfile(this);
                transport = await profile.OpenAsync(null, transport);
            }

            Connection connection = new ListenerConnection(this, this.address, transport);
            bool shouldClose = false;
            lock (this.connections)
            {
                if (!this.closed)
                {
                    connection.Closed += this.OnConnectionClosed;
                    this.connections.Add(connection);
                }
                else
                {
                    shouldClose = true;
                }
            }

            if (shouldClose)
            {
                await connection.CloseAsync();
            }
            else
            {
                AsyncPump pump = new AsyncPump(transport);
                pump.Start(connection);
            }
        }
示例#34
0
        async Task HandleTransportAsync(IAsyncTransport transport)
        {
            IPrincipal principal = null;
            if (this.saslSettings != null)
            {
                ListenerSaslProfile profile = new ListenerSaslProfile(this);
                transport = await profile.OpenAsync(null, this.BufferManager, transport);
                principal = profile.GetPrincipal();
            }

            var connection = new ListenerConnection(this, this.address, transport);
            if (principal == null)
            {
                // SASL principal preferred. If not present, check transport.
                IAuthenticated authenticated = transport as IAuthenticated;
                if (authenticated != null)
                {
                    principal = authenticated.Principal;
                }
            }

            connection.Principal = principal;

            bool shouldClose = false;
            lock (this.connections)
            {
                if (!this.closed)
                {
                    connection.Closed += this.OnConnectionClosed;
                    this.connections.Add(connection);
                }
                else
                {
                    shouldClose = true;
                }
            }

            if (shouldClose)
            {
                await connection.CloseAsync();
            }
            else
            {
                AsyncPump pump = new AsyncPump(this.BufferManager, transport);
                pump.Start(connection);
            }
        }
        async Task HandleTransportAsync(IAsyncTransport transport)
        {
            if (this.saslSettings != null)
            {
                ListenerSaslProfile profile = new ListenerSaslProfile(this);
                transport = await profile.OpenAsync(null, transport);
            }

            Connection connection = new ListenerConnection(this, this.address, transport);
            connection.Closed += this.OnConnectionClosed;
            lock (this.connections)
            {
                this.connections.Add(connection);
            }

            AsyncPump pump = new AsyncPump(transport);
            pump.Start(connection);
        }
示例#36
0
        public void OutOfFrameByteTest()
        {
            AsyncPump.Run(
                async() =>
            {
                var first  = this.GetRandomByteExcept(0xFE);
                var second = this.GetRandomByteExcept(0xFE);

                var prefix  = new[] { this.GetRandomByteExcept() };
                var third   = this.GetRandomByteExcept(0xFE);
                var postfix = new[] { this.GetRandomByteExcept() };

                using (var asyncStream = new MemoryStream())
                {
                    var writer = new S101Writer(asyncStream.WriteAsync);

                    try
                    {
                        await writer.WriteOutOfFrameByteAsync(first, CancellationToken.None);
                        await writer.WriteMessageAsync(KeepAliveRequestMessage, CancellationToken.None);
                        await writer.WriteOutOfFrameByteAsync(second, CancellationToken.None);

                        using (var encodingStream = await writer.WriteMessageAsync(EmberDataMessage, CancellationToken.None))
                        {
                            await encodingStream.WriteAsync(prefix, 0, prefix.Length, CancellationToken.None);
                            await writer.WriteOutOfFrameByteAsync(third, CancellationToken.None);
                            await encodingStream.WriteAsync(postfix, 0, postfix.Length, CancellationToken.None);
                            await encodingStream.DisposeAsync(CancellationToken.None);
                        }
                    }
                    finally
                    {
                        await writer.DisposeAsync(CancellationToken.None);
                    }

                    asyncStream.Position = 0;
                    var reader           = new S101Reader(asyncStream.ReadAsync);
                    var firstTask        = WaitForOutOfFrameByte(reader);
                    Assert.IsTrue(await reader.ReadAsync(CancellationToken.None));
                    Assert.AreEqual(0x00, reader.Message.Slot);
                    Assert.IsInstanceOfType(reader.Message.Command, typeof(KeepAliveRequest));
                    Assert.AreEqual(first, await firstTask);
                    var secondTask = WaitForOutOfFrameByte(reader);
                    Assert.IsTrue(await reader.ReadAsync(CancellationToken.None));
                    Assert.AreEqual(0x00, reader.Message.Slot);
                    Assert.IsInstanceOfType(reader.Message.Command, typeof(EmberData));
                    Assert.AreEqual(second, await secondTask);
                    var thirdTask = WaitForOutOfFrameByte(reader);

                    using (var payloadStream = new MemoryStream())
                    {
                        await reader.Payload.CopyToAsync(payloadStream);
                        var payload = payloadStream.ToArray();
                        Assert.AreEqual(2, payload.Length);
                        Assert.AreEqual(prefix.Single(), payload[0]);
                        Assert.AreEqual(postfix.Single(), payload[1]);
                    }

                    Assert.AreEqual(third, await thirdTask);
                }
            });
        }
示例#37
0
 public static Stream OpenReadSync(this IFile file)
 {
     return(AsyncPump.Run <Stream>(() => file.OpenRead()));
 }