Esempio n. 1
0
 static void Main(string[] args)
 {
     AsyncPump.Run(async delegate
     {
         await Run();
     });
 }
        public void S101ReadTest()
        {
            AsyncPump.Run(
                async() =>
            {
                byte[] input;

                using (var stream = new MemoryStream())
                {
                    var writer = new S101Writer(stream.WriteAsync, 1024);

                    using (var payloadStream = await writer.WriteMessageAsync(EmberDataMessage, CancellationToken.None))
                    {
                        var payload = new byte[BlockSize];
                        this.Random.NextBytes(payload);
                        await payloadStream.WriteAsync(payload, 0, payload.Length);
                        await payloadStream.DisposeAsync(CancellationToken.None);
                    }

                    await writer.DisposeAsync(CancellationToken.None);
                    input = stream.ToArray();
                }

                Console.WriteLine(
                    "S101Reader asynchronous: {0}ms",
                    await TimeMethod(count => TestS101ReaderAsync(input, count), LoopCount));
            });
        }
Esempio n. 3
0
        static void Main(string[] args)
        {
            Console.WriteLine("Application started. Creating modules.");

            var storage    = new Storage("downloads/");
            var database   = new DatabaseContext();
            var hashSolver = new HashSolver();

            var resourceManager  = new ResourceManager(database, storage, hashSolver);
            var pageManager      = new PageManager(database, resourceManager);
            var pageQueryManager = new PageQueryManager(database, pageManager);

            Console.WriteLine("Starting server.");

            // We are using asynchronout functions. The problem is that the database can be accessed only from a single
            // thread and therefore all functions must implicitly run in a single thread.
            // This is problem only for Console Application, Windows Forms and others have its own SynchronizationContext
            // https://devblogs.microsoft.com/pfxteam/await-synchronizationcontext-and-console-apps/

            AsyncPump.Run(async delegate
            {
                var s = new Server(8080, resourceManager, pageQueryManager);
                await s.Start();
            });
        }
        public void ConnectionLostTest()
        {
            AsyncPump.Run(
                async() =>
            {
                var readResult = new TaskCompletionSource <int>();
                using (var client = new S101Client(
                           new MemoryStream(),
                           (b, o, c, t) => readResult.Task,
                           (b, o, c, t) => Task.FromResult(false),
                           new S101Logger(GlowTypes.Instance, Console.Out)))
                {
                    var exception      = new IOException();
                    var connectionLost = new TaskCompletionSource <bool>();

                    client.ConnectionLost +=
                        (s, e) =>
                    {
                        Assert.AreEqual(exception, e.Exception);
                        connectionLost.SetResult(true);
                    };

                    readResult.SetException(exception);
                    await connectionLost.Task;
                    await AssertThrowAsync <ObjectDisposedException>(
                        () => client.SendMessageAsync(new S101Message(0x00, new KeepAliveRequest())));
                }
            });
        }
        public void MainTest()
        {
            AsyncPump.Run(
                async() =>
            {
                var writtenBytes = new byte[this.Random.Next(3072, 10241)];
                this.Random.NextBytes(writtenBytes);

                using (var output = new MemoryStream())
                {
                    using (var framer = new GlowOutput(1024, 0, (s, e) => output.Write(e.FramedPackage, 0, e.FramedPackageLength)))
                    {
                        framer.WriteBytes(writtenBytes);
                        framer.Finish();
                    }

                    output.Position = 0;
                    var reader      = new S101Reader(output.ReadAsync, 1024);
                    Assert.IsTrue(await reader.ReadAsync(CancellationToken.None));
                    Assert.IsInstanceOfType(reader.Message.Command, typeof(EmberData));

                    using (var input = new MemoryStream())
                    {
                        await reader.Payload.CopyToAsync(input);
                        CollectionAssert.AreEqual(writtenBytes, input.ToArray());
                    }

                    await reader.DisposeAsync(CancellationToken.None);
                }
            });
        }
Esempio n. 6
0
        public async Task Run()
        {
            var task = new Task(() => AsyncPump.Run(ProcessPackets), TaskCreationOptions.LongRunning);

            task.Start();
            await task;
        }
Esempio n. 7
0

        
 /// <summary>
 /// Uses AsyncPump from:
 /// https://devblogs.microsoft.com/pfxteam/await-synchronizationcontext-and-console-apps/
 /// </summary>
 public static void Main(string[] args)
 {
     AsyncPump.Run(async() => {
         await RunTests();
     });
     Console.ReadKey();
 }
        public void KeepAliveMainTest()
        {
            AsyncPump.Run(
                async() =>
            {
                var providerClientTask = WaitForConnectionAsync();
                int timeout            = this.Random.Next(1000, 2000);
                Console.WriteLine("Timeout: {0}", timeout);

                using (var consumer = await ConnectAsync(timeout, null))
                {
                    var slot = (byte)this.Random.Next(byte.MaxValue + 1);
                    consumer.KeepAliveRequestSlot = slot;
                    Assert.AreEqual(slot, consumer.KeepAliveRequestSlot);

                    var connectionLost       = new TaskCompletionSource <bool>();
                    consumer.ConnectionLost += (s, e) => OnConnectionLost(connectionLost, e);
                    var providerClient       = await providerClientTask;
                    var stream = providerClient.GetStream();

                    using (new S101Client(
                               providerClient,
                               stream.ReadAsync,
                               stream.WriteAsync,
                               new S101Logger(GlowTypes.Instance, Console.Out),
                               Timeout.Infinite,
                               8192))
                    {
                        await Task.Delay(timeout + (timeout / 4));
                    }

                    await connectionLost.Task;
                }
            });
        }
        public void DynamicReactToChangesTest()
        {
            #region Dynamic React to Changes
            AsyncPump.Run(
                async() =>
            {
                using (var client = await ConnectAsync("localhost", 9000))
                    using (var consumer = await Consumer <MyRoot> .CreateAsync(client))
                    {
                        INode root = consumer.Root;

                        // Navigate to the parameter we're interested in.
                        var sapphire          = (INode)root.Children.First(c => c.Identifier == "Sapphire");
                        var sources           = (INode)sapphire.Children.First(c => c.Identifier == "Sources");
                        var fpgm1             = (INode)sources.Children.First(c => c.Identifier == "FPGM 1");
                        var fader             = (INode)fpgm1.Children.First(c => c.Identifier == "Fader");
                        var positionParameter = fader.Children.First(c => c.Identifier == "Position");

                        var valueChanged = new TaskCompletionSource <string>();
                        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
        }
Esempio n. 11
0
        //Sync VS

        static void Main(string[] args)
        {
            Customers   = new string[customersNumber];
            workspaceID = new string[customersNumber];

            for (int i = 0; i < customersNumber; i++)
            {
                Customers[i] = $"Customer{i}";
            }


            if (!string.IsNullOrWhiteSpace(accessKey))
            {
                accessKeys = new WorkspaceCollectionKeys
                {
                    Key1 = accessKey
                };
            }

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

            Console.ReadKey(true);
        }
        public void DynamicModifyTest()
        {
            #region Dynamic Modify
            AsyncPump.Run(
                async() =>
            {
                using (var client = await ConnectAsync("localhost", 9000))
                    using (var consumer = await Consumer <MyRoot> .CreateAsync(client))
                    {
                        INode root = consumer.Root;

                        // Navigate to the parameters we're interested in.
                        var sapphire = (INode)root.Children.First(c => c.Identifier == "Sapphire");
                        var sources  = (INode)sapphire.Children.First(c => c.Identifier == "Sources");
                        var fpgm1    = (INode)sources.Children.First(c => c.Identifier == "FPGM 1");
                        var fader    = (INode)fpgm1.Children.First(c => c.Identifier == "Fader");
                        var level    = (IParameter)fader.Children.First(c => c.Identifier == "dB Value");
                        var position = (IParameter)fader.Children.First(c => c.Identifier == "Position");

                        // Set parameters to the desired values.
                        level.Value    = -67.0;
                        position.Value = 128L;

                        // We send the changes back to the provider with the call below. Here, this is necessary so that
                        // the changes are sent before Dispose is called on the consumer. In a real-world application
                        // however, SendAsync often does not need to be called explicitly because it is automatically
                        // called every 100ms as long as there are pending changes. See AutoSendInterval for more
                        // information.
                        await consumer.SendAsync();
                    }
            });
            #endregion
        }
Esempio n. 13
0
 public static void Create(this IFile file, string content)
 {
     using (var stream = file.CreateWriteSync())
     {
         AsyncPump.Run(() => stream.WriteStringAsync(content, Encoding.UTF8));
     }
 }
Esempio n. 14
0
        protected override void ProcessRecord()
        {
            using (var eventStream = new Subject <BuildEvent>())
            {
                var credential = Credential != null?
                                 Credential.GetNetworkCredential() :
                                     CredentialCache.DefaultNetworkCredentials;

                var crmDb = SqlUsername != null && SqlPassword != null ?
                            new CrmDatabase(SqlServerName, SqlUsername, SqlPassword) :
                            new CrmDatabase(SqlServerName);

                eventStream.Where(e => e.Type == BuildEventType.Information)
                .Subscribe(e => WriteVerbose($"[{DateTime.Now:HH:mm:ss.FFFF}] {e.Message}"));

                eventStream.Where(e => e.Type == BuildEventType.Warning)
                .Subscribe(e => WriteWarning($"[{DateTime.Now:HH:mm:ss.FFFF}] {e.Message}"));

                eventStream.Where(e => e.Type == BuildEventType.Error)
                .Subscribe(e => WriteError(new ErrorRecord(new Exception(e.Message), e.Message, ErrorCategory.InvalidOperation, this)));

                try
                {
                    AsyncPump.Run(async delegate { await Reprovision(eventStream, crmDb, credential); });
                }
                finally
                {
                    crmDb.Dispose();
                }
            }

            base.ProcessRecord();
        }
Esempio n. 15
0
 protected sealed override void ProcessRecord()
 {
     AsyncPump.Run(async delegate
     {
         await ProcessRecordAsync();
     });
 }
Esempio n. 16
0
        public void ReadAsyncTest()
        {
            AsyncPump.Run(
                async() =>
            {
                var originalBytes = new byte[3];
                this.Random.NextBytes(originalBytes);

                // This covers the case where the read bytes are copied into the buffer in two chunks
                using (var originalStream = new MemoryStream(originalBytes))
                {
                    var readBuffer = new ReadBuffer((ReadAsyncCallback)originalStream.ReadAsync, 2);
                    var buffer     = new byte[1];
                    int read;

                    using (var readStream = new MemoryStream())
                    {
                        while ((read = await readBuffer.ReadAsync(
                                    buffer, 0, buffer.Length, CancellationToken.None)) > 0)
                        {
                            readStream.Write(buffer, 0, read);
                        }

                        var largeBuffer = new byte[readBuffer.Capacity + 1];
                        Assert.AreEqual(
                            0,
                            await readBuffer.ReadAsync(largeBuffer, 0, largeBuffer.Length, CancellationToken.None));
                        CollectionAssert.AreEqual(originalBytes, readStream.ToArray());
                    }
                }
            });
        }
Esempio n. 17
0
        public void ValidateHandshakeAsync()
        {
            AsyncPump.Run(() => _target.ConnectAsync("ws://echo.websocket.org"));
            var response = AsyncPump.Run(() => _target.SendHandshakeAsync());

            Assert.IsNotNull(response);
            Assert.AreEqual(HttpStatusCode.SwitchingProtocols, response.StatusCode, "Unexpected status code");
        }
Esempio n. 18
0
 //这里演示使用自定义的SingleThreadSynchronizationContext让Main的Await使用同一个线程
 static void Main2()
 {
     Console.WriteLine("Main2 @" + Thread.CurrentThread.ManagedThreadId);
     AsyncPump.Run(async delegate
     {
         await DemoAsync();
     });
 }
Esempio n. 19
0
 public static string Content(this IFile file)
 {
     using (var s = file.OpenReadSync())
         using (var r = new StreamReader(s))
         {
             return(AsyncPump.Run(() => r.ReadToEndAsync()));
         }
 }
Esempio n. 20
0
        public void PayloadTest()
        {
            AsyncPump.Run(
                async() =>
            {
#pragma warning disable SA1123 // Do not place regions within elements. Necessary so that tested code snippets can be included in the documentation.
                #region Payload Test
                var writtenMessage = new S101Message(0x00, new EmberData(0x01, 0x0A, 0x02));
                var writtenPayload = new byte[8192];
                this.Random.NextBytes(writtenPayload);

                using (var encodedStream = new MemoryStream())
                {
                    // First we create a writer, which can be used to write multiple messages.
                    // We specify which methods are used to write encoded output and flush it plus the size the internal
                    // buffer should have.
                    var writer = new S101Writer(encodedStream.WriteAsync);

                    // Next we write the message. In return we get a Stream object for the payload.
                    using (var payloadStream =
                               await writer.WriteMessageAsync(writtenMessage, CancellationToken.None))
                    {
                        // Now we write the payload.
                        await payloadStream.WriteAsync(writtenPayload, 0, writtenPayload.Length);
                        await payloadStream.DisposeAsync(CancellationToken.None);
                    }

                    await writer.DisposeAsync(CancellationToken.None);

                    // Reset the encoded stream to the beginning, so that we can read from it.
                    encodedStream.Position = 0;

                    // First we create a reader, which can be used to read multiple messages.
                    // We specify which methods are used to read encoded input.
                    var reader = new S101Reader(encodedStream.ReadAsync);
                    Assert.IsTrue(await reader.ReadAsync(CancellationToken.None));     // Read the first message
                    var readMessage = reader.Message;

                    // Assert the written and read messages are equal
                    Assert.AreEqual(writtenMessage.Slot, readMessage.Slot);
                    Assert.AreEqual(writtenMessage.Command, readMessage.Command);

                    using (var readPayload = new MemoryStream())
                    {
                        await reader.Payload.CopyToAsync(readPayload);     // Copy the payload.
                        // Assert that there is only one message
                        Assert.IsFalse(await reader.ReadAsync(CancellationToken.None));
                        CollectionAssert.AreEqual(writtenPayload, readPayload.ToArray());
                    }

                    await reader.DisposeAsync(CancellationToken.None);
                }
                #endregion
#pragma warning restore SA1123 // Do not place regions within elements
            });
        }
 public void ExceptionTest()
 {
     AsyncPump.Run(
         async() =>
     {
         AssertThrow <ArgumentNullException>(() => StreamHelper.Fill(null, new byte[1], 0, 1));
         await AssertThrowAsync <ArgumentNullException>(
             () => StreamHelper.FillAsync(null, new byte[1], 0, 1, CancellationToken.None));
     });
 }
Esempio n. 22
0
        public void ExceptionTest()
        {
            AsyncPump.Run(
                async() =>
            {
                AssertThrow <ArgumentNullException>(
                    () => new ReadBuffer((ReadCallback)null, 1).Ignore(),
                    () => new ReadBuffer((ReadAsyncCallback)null, 1).Ignore(),
                    () => new WriteBuffer((WriteCallback)null, 1).Ignore(),
                    () => new WriteBuffer((WriteAsyncCallback)null, 1).Ignore(),
                    () => new WriteBuffer((b, o, c) => { }, 1).WriteAsUtf8(null, 0));
                AssertThrow <ArgumentOutOfRangeException>(() => new ReadBuffer((b, o, c) => 0, 0).Ignore());

                using (var stream = new MemoryStream())
                {
                    var readBuffer = new ReadBuffer(stream.Read, 1);
                    AssertThrow <EndOfStreamException>(
                        () => readBuffer.Fill(new byte[1], 0, 1),
                        () => readBuffer.Fill(new byte[2], 0, 2));
                    await AssertThrowAsync <InvalidOperationException>(
                        () => readBuffer.ReadAsync(CancellationToken.None),
                        () => readBuffer.ReadAsync(new byte[1], 0, 1, CancellationToken.None),
                        () => readBuffer.FillAsync(1, CancellationToken.None),
                        () => readBuffer.FillAsync(new byte[1], 0, 1, CancellationToken.None));

                    var asyncReadBuffer = new ReadBuffer((ReadAsyncCallback)stream.ReadAsync, 1);
                    await AssertThrowAsync <EndOfStreamException>(
                        () => asyncReadBuffer.FillAsync(new byte[1], 0, 1, CancellationToken.None),
                        () => asyncReadBuffer.FillAsync(new byte[2], 0, 2, CancellationToken.None));
                    AssertThrow <InvalidOperationException>(
                        () => asyncReadBuffer.Read(),
                        () => asyncReadBuffer.Read(new byte[1], 0, 1),
                        () => asyncReadBuffer.Fill(1),
                        () => asyncReadBuffer.Fill(new byte[1], 0, 1),
                        () => asyncReadBuffer.ReadUtf8(1));

                    var writeBuffer = new WriteBuffer(stream.Write, 1);
                    await AssertThrowAsync <InvalidOperationException>(
                        () => writeBuffer.FlushAsync(CancellationToken.None),
                        () => writeBuffer.ReserveAsync(2, CancellationToken.None),
                        () => writeBuffer.WriteAsync(new byte[3], 0, 3, CancellationToken.None));

                    var asyncWriteBuffer = new WriteBuffer(stream.WriteAsync, 1);
                    asyncWriteBuffer[asyncWriteBuffer.Count++] = 42;
                    AssertThrow <InvalidOperationException>(() => asyncWriteBuffer.Flush());
                    asyncWriteBuffer[asyncWriteBuffer.Count++] = 42;
                    AssertThrow <InvalidOperationException>(
                        () => asyncWriteBuffer.Reserve(2), () => asyncWriteBuffer.Write(new byte[3], 0, 3));
                    asyncWriteBuffer[asyncWriteBuffer.Count++] = 42;
                    var str = "Hello";
                    AssertThrow <InvalidOperationException>(
                        () => asyncWriteBuffer.WriteAsUtf8(str, Encoding.UTF8.GetByteCount(str)));
                }
            });
        }
Esempio n. 23
0
        public static void AssertContent(this Stream s, string content)
        {
            var s2 = new MemoryStream((int)s.Length);

            AsyncPump.Run(() => s.CopyToAsync(s2));
            s2.Seek(0, SeekOrigin.Begin);
            using (var reader = new StreamReader(s2))
            {
                Assert.Equal(content, reader.ReadToEnd());
            }
        }
Esempio n. 24
0
 private void PatchEditor_VisibleChanged(object sender, EventArgs e)
 {
     if (!extensionsLoaded)
     {
         extensionsLoaded = true;
         using (var sf = new SplashForm())
         {
             AsyncPump.Run(() => Session.LoadExtensionDocuments(sf));
         }
     }
 }
        static void Main(string[] args)
        {
            if (CommandLine.Parser.Default.ParseArgumentsStrict(args, _options))
            {
                if (_options.Verbose)
                {
                    Console.WriteLine("ConnectionString: {0}", _options.ConnectionString);
                }

                AsyncPump.Run(() => MainAsync(args));
            }
        }
Esempio n. 26
0
        public void ExceptionTest()
        {
            AsyncPump.Run(
                async() =>
            {
                new S101Writer((b, o, c, t) => Task.FromResult(false)).Ignore();

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

                var writer = new S101Writer((b, o, c, t) => Task.FromResult(false), 1);
                await AssertThrowAsync <ArgumentNullException>(
                    () => writer.WriteMessageAsync(null, CancellationToken.None));

                using (var stream = await writer.WriteMessageAsync(EmberDataMessage, CancellationToken.None))
                {
                    await AssertThrowAsync <ArgumentNullException>(
                        () => stream.WriteAsync(null, 0, 0, CancellationToken.None));

                    await AssertThrowAsync <ArgumentOutOfRangeException>(
                        () => stream.WriteAsync(new byte[1], -1, 1, CancellationToken.None),
                        () => stream.WriteAsync(new byte[1], 0, -1, CancellationToken.None));

                    await AssertThrowAsync <ArgumentException>(
                        () => stream.WriteAsync(new byte[1], 0, 2, CancellationToken.None),
                        () => stream.WriteAsync(new byte[1], 2, 0, CancellationToken.None),
                        () => stream.WriteAsync(new byte[1], 1, 1, CancellationToken.None));

                    await AssertThrowAsync <NotSupportedException>(
                        () => stream.ReadAsync(null, 0, 0, CancellationToken.None));

                    Assert.IsFalse(stream.CanSeek);
                    AssertThrow <NotSupportedException>(
                        () => stream.Length.Ignore(),
                        () => stream.SetLength(0),
                        () => stream.Position.Ignore(),
                        () => stream.Position = 0,
                        () => stream.Seek(0, SeekOrigin.Begin));

                    await AssertThrowAsync <InvalidOperationException>(() => writer.WriteMessageAsync(
                                                                           new S101Message(0x00, new KeepAliveRequest()), CancellationToken.None));
                    await stream.DisposeAsync(CancellationToken.None);
                    await AssertThrowAsync <ObjectDisposedException>(
                        () => stream.WriteAsync(new byte[] { 2 }, 0, 1, CancellationToken.None));
                }

                await writer.DisposeAsync(CancellationToken.None);
                await AssertThrowAsync <ObjectDisposedException>(() => writer.WriteMessageAsync(
                                                                     new S101Message(0x00, new KeepAliveRequest()), CancellationToken.None));
            });
        }
Esempio n. 27
0
        Node GetNodeDefinition(INodeInfo nodeInfo)
        {
            var document = AsyncPump.Run(() => LoadDocumentAsync(nodeInfo.Filename));

            foreach (var n in GetNodeDefinitions(document))
            {
                if (Matches(n, nodeInfo))
                {
                    return(n);
                }
            }
            return(null);
        }
Esempio n. 28
0
        public static void AssertContentMatches(this Stream s, string content)
        {
            var s2 = new MemoryStream((int)s.Length);

            AsyncPump.Run(() => s.CopyToAsync(s2));
            s2.Seek(0, SeekOrigin.Begin);
            using (var reader = new StreamReader(s2))
            {
                var actualContent = reader.ReadToEnd();
                Assert.True(MockDirectory.MatchGlob(content).IsMatch(actualContent),
                            string.Format("\r\n{0} and \r\n{1} do not match.", actualContent, content));
            }
        }
 public void ConnectionLostTest()
 {
     AsyncPump.Run(() => AssertThrowAsync <S101Exception>(() => TestWithRobot <S101Payloads>(
                                                              client =>
     {
         client.Dispose();
         return(Task.FromResult(false));
     },
                                                              null,
                                                              null,
                                                              Types,
                                                              false,
                                                              "IncomingLog.xml")));
 }
 public void DynamicIterateTest()
 {
     #region Dynamic Iterate
     AsyncPump.Run(
         async() =>
     {
         using (var client = await ConnectAsync("localhost", 9000))
             using (var consumer = await Consumer <MyRoot> .CreateAsync(client))
             {
                 WriteChildren(consumer.Root, 0);
             }
     });
     #endregion
 }