public Task <Entry <K, V> > ReadAsync(K key)
        {
            var box = new AsyncBox <Entry <K, V> >();

            jobQueue.Enqueue(Tuple.Create(key, box));
            jobSignal.Release();
            return(box.GetResultAsync());
        }
Example #2
0
 public SendEvent(DateTime time, TimeSpan interval, DeviceAgent initiator, AsyncBox <bool> completionBox, byte[] payload, int bytesSent) : base(time)
 {
     Interval      = interval;
     Initiator     = initiator;
     CompletionBox = completionBox;
     Payload       = payload;
     BytesSent     = bytesSent;
 }
        //public TableSegment GetQueryFromTableInSegments(string tableName, string continueToken)
        //{
        //    // Create the table client.
        //    CloudTableClient tableClient = new CloudTableClient(tableURI, tableCreds);

        //    // Create the CloudTable object that represents the "people" table.
        //    CloudTable table = tableClient.GetTableReference(tableName);

        //    // Initialize a default TableQuery to retrieve all the entities in the table.
        //    TableQuery<DynamicTableEntity> tableQuery = new TableQuery<DynamicTableEntity>();

        //    // Initialize the continuation token to null to start from the beginning of the table.
        //    TableContinuationToken continuationToken = null;
        //    if (!string.IsNullOrEmpty(continueToken))
        //    {
        //        continuationToken = new TableContinuationToken();
        //        XmlReader reader = XmlReader.Create(new StringReader(continueToken));
        //        continuationToken.ReadXml(reader);
        //    }


        //    // Retrieve a segment (up to 1,000 entities).
        //    AsyncBox holder = new AsyncBox();
        //    holder = QueryAsync(tableQuery, table, continuationToken).Result;
        //    TableSegment seg = new TableSegment();
        //    foreach (DynamicTableEntity entity in holder.tableQuerySegment.Results)
        //    {
        //        seg.AddRowToSegement(entity);
        //    }
        //    StringWriter sw = new StringWriter();
        //    XmlWriter writer = XmlWriter.Create(sw);
        //    continuationToken.WriteXml(writer);
        //    seg.SetContinuationToken(sw.ToString());

        //    return seg;
        //}
        private async System.Threading.Tasks.Task <AsyncBox> QueryAsync(TableQuery <DynamicTableEntity> tableQuery, CloudTable table, TableContinuationToken token)
        {
            AsyncBox temp = new AsyncBox();
            TableQuerySegment <DynamicTableEntity> tableQuerySegment = await table.ExecuteQuerySegmentedAsync(tableQuery, token);

            temp.token             = token;
            temp.tableQuerySegment = tableQuerySegment;
            return(temp);
        }
Example #4
0
            public async Task SendAsync(DeviceAgent sender, byte[] contents)
            {
                var interval      = TimeSpan.FromMilliseconds(SimulationBluetoothConstants.SEND_TICK_INTERVAL);
                var completionBox = new AsyncBox <bool>();
                var sendEvent     = new SendEvent(DateTime.Now + interval, interval, sender, completionBox, contents, 0);
                await ChannelsExtensions.WriteAsync(adapterEventQueueChannel, sendEvent).ConfigureAwait(false);

                await completionBox.GetResultAsync().ConfigureAwait(false);
            }
Example #5
0
        public async Task <RmiResponseDto> Invoke(RemoveServiceInfo serviceInfo, MethodInfo methodInfo, object[] methodArguments)
        {
            var invocationId = Guid.NewGuid();
            var request      = new RmiRequestDto {
                InvocationId           = invocationId,
                MethodArguments        = methodArguments,
                MethodGenericArguments = methodInfo.GetGenericArguments(),
                MethodName             = methodInfo.Name,
                ServiceId = serviceInfo.ServiceId
            };

            if (logger.IsDebugEnabled)
            {
                logger.Debug($"Sending RMI {invocationId.ToString("n").Substring(0, 6)} Request on method {methodInfo.Name} for service {serviceInfo.ServiceType.Name}. Local: {localIdentity.Id.ToString("n").Substring(0, 6)}, Remote: {serviceInfo.Peer.Identity.Id.ToString("n").Substring(0, 6)}");
            }

            if (localIdentity.Id == serviceInfo.Peer.Identity.Id)
            {
                if (logger.IsErrorEnabled)
                {
                    logger.Error($"Swallowing as routed to self - RMI {invocationId.ToString("n").Substring(0, 6)} Request on method {methodInfo.Name} for service {serviceInfo.ServiceType.Name}. Local: {localIdentity.Id.ToString("n").Substring(0, 6)}, Remote: {serviceInfo.Peer.Identity.Id.ToString("n").Substring(0, 6)}");
                }
                throw new ArgumentException("Attempted to perform remote service invocation on self.");
            }

            var responseBox = new AsyncBox <RmiResponseDto>();

            responseBoxes.AddOrThrow(invocationId, responseBox);

            await messenger.SendReliableAsync(request, serviceInfo.Peer.Identity.Id).ConfigureAwait(false);

            if (logger.IsDebugEnabled)
            {
                logger.Debug($"Sent RMI {invocationId.ToString("n").Substring(0, 6)} Request on method {methodInfo.Name} for service {serviceInfo.ServiceType.Name}");
            }

            // response box removed by HandleInvocationResponse - don't cleanup
            var result = await responseBox.GetResultAsync().ConfigureAwait(false);

            if (logger.IsDebugEnabled)
            {
                logger.Debug($"Received RMI {invocationId.ToString("n").Substring(0, 6)} Response on method {methodInfo.Name} for service {serviceInfo.ServiceType.Name}");
            }
            return(result);
        }
      public async Task<RmiResponseDto> Invoke(RemoveServiceInfo serviceInfo, MethodInfo methodInfo, object[] methodArguments) {
         var invocationId = Guid.NewGuid();
         var request = new RmiRequestDto {
            InvocationId = invocationId,
            MethodArguments = methodArguments,
            MethodGenericArguments = methodInfo.GetGenericArguments(),
            MethodName = methodInfo.Name,
            ServiceId = serviceInfo.ServiceId
         };

         if (logger.IsDebugEnabled) {
            logger.Debug($"Sending RMI {invocationId.ToString("n").Substring(0, 6)} Request on method {methodInfo.Name} for service {serviceInfo.ServiceType.Name}. Local: {localIdentity.Id.ToString("n").Substring(0, 6)}, Remote: {serviceInfo.Peer.Identity.Id.ToString("n").Substring(0, 6)}");
         }

         if (localIdentity.Id == serviceInfo.Peer.Identity.Id) {
            if (logger.IsErrorEnabled) {
               logger.Error($"Swallowing as routed to self - RMI {invocationId.ToString("n").Substring(0, 6)} Request on method {methodInfo.Name} for service {serviceInfo.ServiceType.Name}. Local: {localIdentity.Id.ToString("n").Substring(0, 6)}, Remote: {serviceInfo.Peer.Identity.Id.ToString("n").Substring(0, 6)}");
            }
            throw new ArgumentException("Attempted to perform remote service invocation on self.");
         }

         var responseBox = new AsyncBox<RmiResponseDto>();
         responseBoxes.AddOrThrow(invocationId, responseBox);

         await messenger.SendReliableAsync(request, serviceInfo.Peer.Identity.Id).ConfigureAwait(false);

         if (logger.IsDebugEnabled) {
            logger.Debug($"Sent RMI {invocationId.ToString("n").Substring(0, 6)} Request on method {methodInfo.Name} for service {serviceInfo.ServiceType.Name}");
         }

         // response box removed by HandleInvocationResponse - don't cleanup
         var result = await responseBox.GetResultAsync().ConfigureAwait(false);

         if (logger.IsDebugEnabled) {
            logger.Debug($"Received RMI {invocationId.ToString("n").Substring(0, 6)} Response on method {methodInfo.Name} for service {serviceInfo.ServiceType.Name}");
         }
         return result;
      }
Example #7
0
            private async Task HandshakeAsync(double minTimeoutSeconds)
            {
                using (await synchronization.LockAsync().ConfigureAwait(false)) {
                    var isServer = androidBluetoothAdapter.AdapterId.CompareTo(AdapterId) > 0;

                    // Michael's laptop is always the client as windows client doesn't understand being a server.
                    if (Name?.Contains("DESKTOP") ?? false)
                    {
                        isServer = true;
                    }

                    if (isServer)
                    {
                        socket = await inboundBluetoothSocketTable.TakeAsyncOrTimeout(device).ConfigureAwait(false);
                    }
                    else
                    {
                        var socketBox = new AsyncBox <BluetoothSocket>();
                        new Thread(() => {
                            try {
                                socketBox.SetResult(device.CreateInsecureRfcommSocketToServiceRecord(CampfireNetBluetoothConstants.APP_UUID));
                            } catch (Exception e) {
                                socketBox.SetException(e);
                            }
                        }).Start();

                        socket = await socketBox.GetResultAsync().ConfigureAwait(false);

                        var connectedChannel = ChannelFactory.Nonblocking <bool>();

                        Go(async() => {
                            await socket.ConnectAsync().ConfigureAwait(false);
                            await ChannelsExtensions.WriteAsync(connectedChannel, true);
                        }).Forget();

                        bool isTimeout = false;
                        await new Select {
                            Case(ChannelFactory.Timer(TimeSpan.FromSeconds(minTimeoutSeconds)), () => {
                                socket.Dispose();
                                isTimeout = true;
                            }),
                            Case(connectedChannel, () => {
                                // whee!
                            })
                        }.ConfigureAwait(false);
                        if (isTimeout)
                        {
                            throw new TimeoutException();
                        }
                    }
                    disconnectedChannel.SetIsClosed(false);

                    ChannelsExtensions.Go(async() => {
                        Console.WriteLine("Entered BT Reader Task");
                        var networkStream = socket.InputStream;
                        try {
                            while (!disconnectedChannel.IsClosed)
                            {
                                Console.WriteLine("Reading BT Frame");
                                var dataLengthBuffer = await ReadBytesAsync(networkStream, 4).ConfigureAwait(false);
                                var dataLength       = BitConverter.ToInt32(dataLengthBuffer, 0);
                                var data             = await ReadBytesAsync(networkStream, dataLength).ConfigureAwait(false);
                                await ChannelsExtensions.WriteAsync(inboundChannel, data).ConfigureAwait(false);
                            }
                        } catch (Exception e) {
                            Console.WriteLine(e);
                            Teardown();
                        }
                    }).Forget();
                }
            }
Example #8
0
 public appender(ContextualStream <T> stream)
 {
     this.stream        = stream;
     lastKnownNode      = AsyncBox.Create <node>(null);
     lastKnownNodeIndex = AsyncBox.Create(0);
 }