Example #1
0
        public TcsRouting Quit(RoutingBuilder routingBuilder, ChannelCreator cc)
        {
            ICollection <PeerAddress> startPeers = _peerBean.PeerMap.ClosePeers(routingBuilder.LocationKey,
                                                                                routingBuilder.Parallel * 2);

            return(Routing(startPeers, routingBuilder, Message.Message.MessageType.Request4, cc));
        }
		public WcfChannelHolder(ChannelCreator channelCreator, IWcfBurden burden)
		{
			this.channelCreator = channelCreator;
			ChannelBurden = burden;
			ObtainChannelFactory();
			CreateChannel();
		}
Example #3
0
        /// <summary>
        /// Requests close neighbors from the remote peer. The remote peer may indicate if the
        /// data is present on that peer. This is an RPC.
        /// </summary>
        /// <param name="remotePeer">The remote peer to send this request to.</param>
        /// <param name="searchValues">The values to search for in the storage.</param>
        /// <param name="type">The type of the neighbor request:
        /// - Request1 for Neighbors means check for Put (no digest) for tracker and storage.
        /// - Request2 for Neighbors means check for Get (with digest) for storage.
        /// - Request3 for Neighbors means check for Get (with digest) for tracker.
        /// - Request4 for Neighbors means check for Put (with digest) for task.</param>
        /// <param name="channelCreator">The channel creator that creates connections.</param>
        /// <param name="configuration">The client-side connection configuration.</param>
        /// <returns>The future response message.</returns>
        public Task <Message.Message> CloseNeighborsAsync(PeerAddress remotePeer, SearchValues searchValues, Message.Message.MessageType type,
                                                          ChannelCreator channelCreator, IConnectionConfiguration configuration)
        {
            var tcsResponse = CloseNeighborsTcs(remotePeer, searchValues, type, channelCreator, configuration);

            return(tcsResponse.Task);
        }
Example #4
0
        /// <summary>
        /// Ping a TCP peer and find out how the other peer sees us.
        /// </summary>
        /// <param name="remotePeer">The destination peer.</param>
        /// <param name="channelCreator">The channel creator where we create a TCP channel.</param>
        /// <param name="configuration"></param>
        /// <param name="senderAddress"></param>
        /// <returns>The future response message.</returns>
        public Task <Message.Message> PingTcpDiscoverAsync(PeerAddress remotePeer, ChannelCreator channelCreator,
                                                           IConnectionConfiguration configuration, PeerAddress senderAddress)
        {
            var tcsResponse = CreateDiscoverHandler(remotePeer, senderAddress);

            return(new RequestHandler(tcsResponse, PeerBean, ConnectionBean, configuration).SendTcpAsync(channelCreator));
        }
Example #5
0
        public Task <Message> PutConfirmAsync(PeerAddress remotePeer, PutBuilder putBuilder,
                                              ChannelCreator channelCreator)
        {
            Utils.NullCheck(remotePeer);

            DataMap dataMap;

            if (putBuilder.DataMap != null)
            {
                dataMap = new DataMap(putBuilder.DataMap);
            }
            else
            {
                dataMap = new DataMap(putBuilder.LocationKey, putBuilder.DomainKey, putBuilder.VersionKey,
                                      putBuilder.DataMapConvert);
            }

            var message = CreateRequestMessage(remotePeer, Rpc.Commands.PutConfirm.GetNr(), Message.MessageType.Request1);

            if (putBuilder.IsSign)
            {
                message.SetPublicKeyAndSign(putBuilder.KeyPair);
            }

            message.SetDataMap(dataMap);

            var tcsResponse    = new TaskCompletionSource <Message>(message);
            var requestHandler = new RequestHandler(tcsResponse, PeerBean, ConnectionBean, putBuilder);

            if (!putBuilder.IsForceUdp)
            {
                return(requestHandler.SendTcpAsync(channelCreator));
            }
            return(requestHandler.SendUdpAsync(channelCreator));
        }
Example #6
0
 /// <summary>
 /// Ping a TCP peer, but don't expect an answer.
 /// </summary>
 /// <param name="remotePeer">The destination peer.</param>
 /// <param name="channelCreator">The channel creator where we create a TCP channel.</param>
 /// <param name="configuration"></param>
 /// <returns>The future response message.</returns>
 public Task <Message.Message> FireTcpAsync(PeerAddress remotePeer, ChannelCreator channelCreator,
                                            IConnectionConfiguration configuration)
 {
     return
         (CreateHandler(remotePeer, Message.Message.MessageType.RequestFf1, configuration)
          .SendTcpAsync(channelCreator));
 }
Example #7
0
 void IWcfEndpointVisitor.VisitBindingAddressEndpoint(BindingAddressEndpointModel model)
 {
     if (model.HasViaAddress)
     {
         var address     = model.EndpointAddress ?? new EndpointAddress(model.Address);
         var description = ContractDescription.GetContract(contract);
         var binding     = GetEffectiveBinding(model.Binding, address.Uri);
         var endpoint    = new ServiceEndpoint(description, binding, address);
         endpoint.Behaviors.Add(new ClientViaBehavior(model.ViaAddress));
         channelCreator = GetChannel(contract, endpoint);
     }
     else
     {
         if (model.EndpointAddress != null)
         {
             var binding = GetEffectiveBinding(model.Binding, model.EndpointAddress.Uri);
             channelCreator = GetChannel(contract, binding, model.EndpointAddress);
         }
         else
         {
             var binding = GetEffectiveBinding(model.Binding, new Uri(model.Address));
             channelCreator = GetChannel(contract, binding, model.Address);
         }
     }
 }
Example #8
0
 public WcfChannelHolder(ChannelCreator channelCreator, IWcfBurden burden, TimeSpan?closeTimeout)
 {
     this.channelCreator = channelCreator;
     ChannelBurden       = burden;
     CloseTimeout        = closeTimeout;
     ObtainChannelFactory();
     CreateChannel();
 }
Example #9
0
		public WcfChannelHolder(ChannelCreator channelCreator, IWcfBurden burden, TimeSpan? closeTimeout)
		{
			this.channelCreator = channelCreator;
			ChannelBurden = burden;
			CloseTimeout = closeTimeout;
			ObtainChannelFactory();
			CreateChannel();
		}
Example #10
0
        /// <summary>
        /// Creates the channel creator.
        /// </summary>
        /// <param name = "context"> The context for the creator. </param>
        /// <param name = "burden"> Receives the channel burden. </param>
        /// <returns> The channel creator. </returns>
        /// <remarks>
        /// Always Open the channel before being used to prevent serialization of requests.
        /// http://blogs.msdn.com/wenlong/archive/2007/10/26/best-practice-always-open-wcf-client-proxy-explicitly-when-it-is-shared.aspx
        /// </remarks>
        private ChannelCreator GetChannelCreator(CreationContext context, out IWcfBurden burden)
        {
            burden = channelBurden;
            var creator     = createChannel;
            var clientModel = ObtainClientModel(Model, context);

            if (clientModel != null)
            {
                var inner        = CreateChannelCreator(Kernel, Model, clientModel, out burden);
                var scopedBurden = burden;

                creator = () =>
                {
                    var client = (IChannel)inner();
                    if (client is IContextChannel)
                    {
                        ((IContextChannel)client).Extensions.Add(new WcfBurdenExtension <IContextChannel>(scopedBurden));
                    }
                    else
                    {
                        var parameters = client.GetProperty <ChannelParameterCollection>();
                        if (parameters != null)
                        {
                            parameters.Add(scopedBurden);
                        }
                    }
                    NotifyChannelCreatedOrAvailable(client, scopedBurden, true);

                    if (!clientModel.OpenChannelOnDemand)
                    {
                        client.Open();
                    }

                    return(client);
                };
            }
            else if (createChannel == null)
            {
                clientModel = ObtainClientModel(Model);
                var inner = CreateChannelCreator(Kernel, Model, clientModel, out channelBurden);
                creator = createChannel = () =>
                {
                    var client = (IChannel)inner();
                    NotifyChannelCreatedOrAvailable(client, channelBurden, true);

                    if (!clientModel.OpenChannelOnDemand)
                    {
                        client.Open();
                    }

                    return(client);
                };
                burden = channelBurden;
                clients.TrackBurden(burden);
            }

            return(creator);
        }
Example #11
0
        /// <summary>
        /// Ping a TCP peer and request the other peer to ping us on our public address with a
        /// fire-and-forget message.
        /// </summary>
        /// <param name="remotePeer">The destination peer.</param>
        /// <param name="channelCreator">The channel creator where we create a TCP channel.</param>
        /// <param name="configuration"></param>
        /// <returns>The future response message.</returns>
        public Task <Message.Message> PingTcpProbeAsync(PeerAddress remotePeer, ChannelCreator channelCreator,
                                                        IConnectionConfiguration configuration)
        {
            var message = CreateRequestMessage(remotePeer, Rpc.Commands.Ping.GetNr(),
                                               Message.Message.MessageType.Request3);
            var tcsResponse = new TaskCompletionSource <Message.Message>(message);

            return(new RequestHandler(tcsResponse, PeerBean, ConnectionBean, configuration).SendTcpAsync(channelCreator));
        }
Example #12
0
        private void DiscoverEndpoint(DiscoveryEndpoint discoveryEndpoint, DiscoveredEndpointModel model)
        {
            using (var discover = new DiscoveryClient(discoveryEndpoint))
            {
                var criteria = CreateSearchCriteria(model);

                var discovered = discover.Find(criteria);
                if (discovered.Endpoints.Count > 0)
                {
                    var binding          = model.Binding;
                    var endpointMetadata = discovered.Endpoints[0];
                    if (discovered.Endpoints.Count > 1 && model.EndpointPreference != null)
                    {
                        endpointMetadata = model.EndpointPreference(discovered.Endpoints);
                        if (endpointMetadata == null)
                        {
                            throw new EndpointNotFoundException(string.Format(
                                                                    "More than one endpoint was discovered for contract {0}.  " +
                                                                    "However, an endpoint could be selected.  This is most likely " +
                                                                    "a bug with the user-defined endpoint prefeence.",
                                                                    contract.FullName));
                        }
                    }

                    if (binding == null && model.DeriveBinding == false)
                    {
                        binding = GetBindingFromMetadata(endpointMetadata);
                    }

                    var address = endpointMetadata.Address;
                    if (model.Identity != null)
                    {
                        address = new EndpointAddress(address.Uri, model.Identity, address.Headers);
                    }

                    binding = GetEffectiveBinding(binding, address.Uri);
                    var innerCreator = GetChannel(contract, binding, address);
                    channelCreator = () =>
                    {
                        var channel = (IChannel)innerCreator();
                        if (channel is IContextChannel)
                        {
                            var metadata = new DiscoveredEndpointMetadata(endpointMetadata);
                            ((IContextChannel)channel).Extensions.Add(metadata);
                        }
                        return(channel);
                    };
                }
                else
                {
                    throw new EndpointNotFoundException(string.Format(
                                                            "Unable to discover the endpoint for contract {0}.  " +
                                                            "Either no service exists or it does not support discovery.",
                                                            contract.FullName));
                }
            }
        }
Example #13
0
        public async void TestGracefulHalt()
        {
            Peer           sender = null;
            Peer           recv1  = null;
            ChannelCreator cc     = null;

            try
            {
                sender = new PeerBuilder(new Number160("0x9876"))
                         .SetChannelServerConfiguration(Utils2.CreateInfiniteTimeoutChannelServerConfiguration(2424, 2424))
                         .SetMaintenanceTask(Utils2.CreateInfiniteIntervalMaintenanceTask())
                         .SetP2PId(55)
                         .SetPorts(2424)
                         .Start();
                recv1 = new PeerBuilder(new Number160("0x1234"))
                        .SetChannelServerConfiguration(Utils2.CreateInfiniteTimeoutChannelServerConfiguration(7777, 7777))
                        .SetMaintenanceTask(Utils2.CreateInfiniteIntervalMaintenanceTask())
                        .SetP2PId(55)
                        .SetPorts(7777)
                        .Start();

                // bootstrap first
                await sender.Bootstrap().SetPeerAddress(recv1.PeerAddress).StartAsync();

                Assert.IsTrue(sender.PeerBean.PeerMap.All.Count == 1);
                Assert.IsTrue(recv1.PeerBean.PeerMap.AllOverflow.Count == 1);

                // graceful shutdown
                cc = await recv1.ConnectionBean.Reservation.CreateAsync(1, 0);

                var shutdownBuilder = new ShutdownBuilder(sender);

                await sender.QuitRpc.QuitAsync(recv1.PeerAddress, shutdownBuilder, cc);

                await sender.ShutdownAsync();

                sender = null; // ignore finally-block shutdown

                Assert.IsTrue(recv1.PeerBean.PeerMap.All.Count == 0);
            }
            finally
            {
                if (cc != null)
                {
                    cc.ShutdownAsync().Wait();
                }
                if (sender != null)
                {
                    sender.ShutdownAsync().Wait();
                }
                if (recv1 != null)
                {
                    recv1.ShutdownAsync().Wait();
                }
            }
        }
Example #14
0
        public async void TestOrder()
        {
            Peer           sender = null;
            Peer           recv1  = null;
            ChannelCreator cc     = null;

            try
            {
                sender = new PeerBuilder(new Number160("0x50"))
                         .SetMaintenanceTask(Utils2.CreateInfiniteIntervalMaintenanceTask())
                         .SetChannelServerConfiguration(Utils2.CreateInfiniteTimeoutChannelServerConfiguration(2525, 2525))
                         .SetP2PId(55)
                         .SetPorts(2525)
                         .Start();
                recv1 = new PeerBuilder(new Number160("0x20"))
                        .SetMaintenanceTask(Utils2.CreateInfiniteIntervalMaintenanceTask())
                        .SetChannelServerConfiguration(Utils2.CreateInfiniteTimeoutChannelServerConfiguration(9099, 9099))
                        .SetP2PId(55)
                        .SetPorts(8088)
                        .Start();
                recv1.RawDataReply(new TestOrderRawDataReply());

                for (int i = 0; i < 500; i++)
                {
                    cc = await sender.ConnectionBean.Reservation.CreateAsync(0, 1);

                    var sendDirectBuilder = new SendDirectBuilder(sender, (PeerAddress)null);
                    var buffer            = AlternativeCompositeByteBuf.CompBuffer().WriteInt(i);
                    sendDirectBuilder.SetBuffer(new Buffer(buffer));
                    sendDirectBuilder.SetIsStreaming();

                    var tr = sender.DirectDataRpc.SendAsync(recv1.PeerAddress, sendDirectBuilder, cc);
                    Core.Utils.Utils.AddReleaseListener(cc, tr);
                    tr.ContinueWith(t =>
                    {
                        int j = t.Result.Buffer(0).BackingBuffer.ReadInt();
                        Console.WriteLine("Received {0}.", j);
                    });
                }
            }
            finally
            {
                if (sender != null)
                {
                    sender.ShutdownAsync().Wait();
                }
                if (recv1 != null)
                {
                    recv1.ShutdownAsync().Wait();
                }
                if (cc != null)
                {
                    cc.ShutdownAsync().Wait();
                }
            }
        }
Example #15
0
 public void AddTcsDhtReleaseListener(ChannelCreator channelCreator)
 {
     Task.ContinueWith(tDht =>
     {
         FutureRequests.Task.ContinueWith(tcsForkJoin =>
         {
             channelCreator.ShutdownAsync();
         });
     });
 }
Example #16
0
        public Task <Message.Message> SendAsync(PeerAddress remotePeer, ISendDirectBuilder sendDirectBuilder,
                                                ChannelCreator channelCreator)
        {
            var requestHandler = SendInternal(remotePeer, sendDirectBuilder);

            if (!sendDirectBuilder.IsForceUdp)
            {
                return(requestHandler.SendTcpAsync(channelCreator));
            }
            return(requestHandler.SendUdpAsync(channelCreator));
        }
Example #17
0
        public async void TestDirect1()
        {
            Peer           sender = null;
            Peer           recv1  = null;
            ChannelCreator cc     = null;

            try
            {
                sender = new PeerBuilder(new Number160("0x50"))
                         .SetMaintenanceTask(Utils2.CreateInfiniteIntervalMaintenanceTask())
                         .SetChannelServerConfiguration(Utils2.CreateInfiniteTimeoutChannelServerConfiguration(2525, 2525))
                         .SetP2PId(55)
                         .SetPorts(2525)
                         .Start();
                recv1 = new PeerBuilder(new Number160("0x20"))
                        .SetMaintenanceTask(Utils2.CreateInfiniteIntervalMaintenanceTask())
                        .SetChannelServerConfiguration(Utils2.CreateInfiniteTimeoutChannelServerConfiguration(9099, 9099))
                        .SetP2PId(55)
                        .SetPorts(8088)
                        .Start();
                recv1.RawDataReply(new TestRawDataReply());

                cc = await sender.ConnectionBean.Reservation.CreateAsync(0, 1);

                var sendDirectBuilder = new SendDirectBuilder(sender, (PeerAddress)null);
                sendDirectBuilder.SetIsStreaming();
                sendDirectBuilder.SetIdleTcpSeconds(Int32.MaxValue);
                var buffer = CreateTestBuffer();
                sendDirectBuilder.SetBuffer(buffer);

                var   tr1 = sender.DirectDataRpc.SendAsync(recv1.PeerAddress, sendDirectBuilder, cc);
                await tr1;
                Assert.IsTrue(!tr1.IsFaulted);

                var ret = tr1.Result.Buffer(0);
                Assert.AreEqual(buffer, ret);
            }
            finally
            {
                if (sender != null)
                {
                    sender.ShutdownAsync().Wait();
                }
                if (recv1 != null)
                {
                    recv1.ShutdownAsync().Wait();
                }
                if (cc != null)
                {
                    cc.ShutdownAsync().Wait();
                }
            }
        }
Example #18
0
        public async void TestPingTcpDeadlock()
        {
            Peer           sender1 = null;
            Peer           recv1   = null;
            ChannelCreator cc      = null;

            try
            {
                sender1 = new PeerBuilder(new Number160("0x9876")).
                          SetP2PId(55).
                          SetPorts(2424).
                          Start();
                recv1 = new PeerBuilder(new Number160("0x1234")).
                        SetP2PId(55).
                        SetPorts(8088).
                        Start();

                cc = await recv1.ConnectionBean.Reservation.CreateAsync(0, 1);

                var   tr = sender1.PingRpc.PingTcpAsync(recv1.PeerAddress, cc, new DefaultConnectionConfiguration());
                await tr;
                await tr.ContinueWith(async t =>
                {
                    var tr2 = sender1.PingRpc.PingTcpAsync(recv1.PeerAddress, cc, new DefaultConnectionConfiguration());
                    try
                    {
                        await tr2;
                    }
                    catch (Exception ex)
                    {
                        Assert.Fail(ex.ToString());
                    }
                });

                Assert.IsTrue(!tr.IsFaulted);
            }
            finally
            {
                if (cc != null)
                {
                    cc.ShutdownAsync().Wait();
                }
                if (sender1 != null)
                {
                    sender1.ShutdownAsync().Wait();
                }
                if (recv1 != null)
                {
                    recv1.ShutdownAsync().Wait();
                }
            }
        }
        public async Task StopProposalsAsync()
        {
            var photoBot = Service.PhotoBot;

            var winnerProposal = photoBot.Config.Proposals
                                 .OrderBy(element => Guid.NewGuid())
                                 .ThenByDescending(element => element.Score)
                                 .First();

            var proposalsChannel = photoBot.SocketGuild.GetTextChannel(photoBot.Config.CurrentProposalsChannelId);
            var winnersChannel   = photoBot.SocketGuild.GetTextChannel(photoBot.Config.WinnerChannelId);

            using var client = new WebClient();
            await client.DownloadFileTaskAsync(new Uri(winnerProposal.ImageUrl), "winner_proposal.png");

            try
            {
                await winnersChannel.SendFileAsync("winner_proposal.png", $"Thema: {winnerProposal.Topic}");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            var users = photoBot.Config.PhotoUserIds;

            photoBot.Config.UserIdToPhotoChannelId = new Dictionary <ulong, ulong>();

            foreach (var userId in users)
            {
                var user         = photoBot.SocketGuild.GetUser(userId);
                var photoChannel = await ChannelCreator.CreateChannelAsync($"photo-{user.Username}", photoBot.Config.PhotoCategoryId);

                var denyAllPermissions = new Overwrite(photoBot.Config.EveryoneRoleId, PermissionTarget.Role,
                                                       OverwritePermissions.DenyAll(photoChannel));

                var allowUserPermissions = new Overwrite(userId, PermissionTarget.User,
                                                         OverwritePermissions.AllowAll(photoChannel));

                var permissions = new List <Overwrite> {
                    denyAllPermissions, allowUserPermissions
                };

                await photoChannel.ModifyAsync(prop => prop.PermissionOverwrites = permissions);

                photoBot.Config.UserIdToPhotoChannelId.Add(userId, photoChannel.Id);
            }

            await Archiver.ArchiveChannelAsync(proposalsChannel);

            await PhotoConfig.SaveAsync();
        }
Example #20
0
        public async void TestReservationUdp()
        {
            Peer           sender = null;
            Peer           recv1  = null;
            ChannelCreator cc     = null;

            try
            {
                sender = new PeerBuilder(new Number160("0x9876"))
                         .SetP2PId(55)
                         .SetPorts(2424)
                         .Start();
                recv1 = new PeerBuilder(new Number160("0x1234"))
                        .SetP2PId(55)
                        .SetPorts(8088)
                        .Start();
                cc = await recv1.ConnectionBean.Reservation.CreateAsync(3, 0);

                for (int i = 0; i < 100; i++)
                {
                    var   tr1 = sender.PingRpc.PingUdpAsync(recv1.PeerAddress, cc, new DefaultConnectionConfiguration());
                    var   tr2 = sender.PingRpc.PingUdpAsync(recv1.PeerAddress, cc, new DefaultConnectionConfiguration());
                    var   tr3 = sender.PingRpc.PingUdpAsync(recv1.PeerAddress, cc, new DefaultConnectionConfiguration());
                    await tr1;
                    await tr2;
                    await tr3;
                    Assert.IsTrue(!tr1.IsFaulted);
                    Assert.IsTrue(!tr2.IsFaulted);
                    Assert.IsTrue(!tr3.IsFaulted);
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                throw;
            }
            finally
            {
                if (sender != null)
                {
                    sender.ShutdownAsync().Wait();
                }
                if (recv1 != null)
                {
                    recv1.ShutdownAsync().Wait();
                }
                if (cc != null)
                {
                    cc.ShutdownAsync().Wait();
                }
            }
        }
Example #21
0
        public async void TestPingTimeoutUdp()
        {
            Peer           sender = null;
            Peer           recv1  = null;
            ChannelCreator cc     = null;

            try
            {
                sender = new PeerBuilder(new Number160("0x9876"))
                         .SetMaintenanceTask(Utils2.CreateInfiniteIntervalMaintenanceTask())
                         .SetP2PId(55)
                         .SetPorts(2424)
                         .Start();
                recv1 = new PeerBuilder(new Number160("0x1234"))
                        .SetMaintenanceTask(Utils2.CreateInfiniteIntervalMaintenanceTask())
                        .SetP2PId(55)
                        .SetPorts(8088)
                        .Start();
                var handshake1 = new PingRpc(sender.PeerBean, sender.ConnectionBean, false, true, true);
                var handshake2 = new PingRpc(recv1.PeerBean, recv1.ConnectionBean, false, true, true);

                cc = await recv1.ConnectionBean.Reservation.CreateAsync(1, 0);

                var tr = handshake1.PingUdpAsync(recv1.PeerAddress, cc, new DefaultConnectionConfiguration());

                try
                {
                    await tr;
                    Assert.Fail("Timeout should have let task fail.");
                }
                catch (Exception)
                {
                    Assert.IsTrue(tr.IsFaulted);
                }
            }
            finally
            {
                if (cc != null)
                {
                    cc.ShutdownAsync().Wait();
                }
                if (sender != null)
                {
                    sender.ShutdownAsync().Wait();
                }
                if (recv1 != null)
                {
                    recv1.ShutdownAsync().Wait();
                }
            }
        }
Example #22
0
        public async void TestPingUdpPool()
        {
            Peer           sender = null;
            Peer           recv1  = null;
            ChannelCreator cc     = null;

            try
            {
                sender = new PeerBuilder(new Number160("0x9876"))
                         .SetMaintenanceTask(Utils2.CreateInfiniteIntervalMaintenanceTask())
                         .SetP2PId(55)
                         .SetPorts(2424)
                         .Start();
                recv1 = new PeerBuilder(new Number160("0x1234"))
                        .SetMaintenanceTask(Utils2.CreateInfiniteIntervalMaintenanceTask())
                        .SetP2PId(55)
                        .SetPorts(8088)
                        .Start();

                var tasks = new List <Task <Message> >(50);
                cc = await recv1.ConnectionBean.Reservation.CreateAsync(tasks.Capacity, 0);

                for (int i = 0; i < tasks.Capacity; i++)
                {
                    var taskResponse = sender.PingRpc.PingUdpAsync(recv1.PeerAddress, cc,
                                                                   new DefaultConnectionConfiguration());
                    tasks.Add(taskResponse);
                }
                foreach (var task in tasks)
                {
                    await task;
                    Assert.IsTrue(!task.IsFaulted);
                }
            }
            finally
            {
                if (cc != null)
                {
                    cc.ShutdownAsync().Wait();
                }
                if (sender != null)
                {
                    sender.ShutdownAsync().Wait();
                }

                if (recv1 != null)
                {
                    recv1.ShutdownAsync().Wait();
                }
            }
        }
      public void DummyService_WithProxyChannel_ReturnNull()
      {
         Binding binding = new BasicHttpBinding();
         EndpointAddress address = new EndpointAddress("http://localhost:8733/DummyService/");

         var channelFactory = new ChannelFactory<IDummyService>(binding, address);
         ICanCreateChannels<IDummyService> channelCreator = new ChannelCreator<IDummyService>(channelFactory);
         IChannelManager<IDummyService> channelManager = new SingleActionChannelManager<IDummyService>(channelCreator);

         var proxy = new DummyProxyChannel(channelManager);

         proxy.Execute("ReturnNull", null, Type.EmptyTypes);

      }
Example #24
0
        public async void TestPingTcp2()
        {
            Peer           sender = null;
            Peer           recv1  = null;
            ChannelCreator cc     = null;

            try
            {
                sender = new PeerBuilder(new Number160("0x9876"))
                         .SetMaintenanceTask(Utils2.CreateInfiniteIntervalMaintenanceTask())
                         .SetChannelServerConfiguration(Utils2.CreateInfiniteTimeoutChannelServerConfiguration(2424, 2424))
                         .SetP2PId(55)
                         .SetPorts(2424)
                         .Start();
                recv1 = new PeerBuilder(new Number160("0x1234"))
                        .SetMaintenanceTask(Utils2.CreateInfiniteIntervalMaintenanceTask())
                        .SetChannelServerConfiguration(Utils2.CreateInfiniteTimeoutChannelServerConfiguration(8088, 8088))
                        .SetP2PId(55)
                        .SetPorts(8088)
                        .Start();

                // TODO check release in cc for first ping
                cc = await recv1.ConnectionBean.Reservation.CreateAsync(0, 1);

                var   tr = sender.PingRpc.PingTcpAsync(recv1.PeerAddress, cc, new DefaultConnectionConfiguration());
                await tr;
                var   tr2 = recv1.PingRpc.PingTcpAsync(sender.PeerAddress, cc, new DefaultConnectionConfiguration());
                await tr2;

                Assert.IsTrue(!tr.IsFaulted);
                Assert.IsTrue(!tr2.IsFaulted);
            }
            finally
            {
                if (cc != null)
                {
                    cc.ShutdownAsync().Wait();
                }
                if (sender != null)
                {
                    sender.ShutdownAsync().Wait();
                }
                if (recv1 != null)
                {
                    recv1.ShutdownAsync().Wait();
                }
            }
        }
Example #25
0
        /// <summary>
        /// Removes data from a peer.
        /// </summary>
        /// <param name="remotePeer">The remote peer on which to store the data.</param>
        /// <param name="removeBuilder">The builder to use for this operation.</param>
        /// <param name="channelCreator">The channel creator that will be used.</param>
        /// <returns>The future response message.</returns>
        public Task <Message> RemoveAsync(PeerAddress remotePeer, RemoveBuilder removeBuilder,
                                          ChannelCreator channelCreator)
        {
            var message = CreateRequestMessage(remotePeer, Rpc.Commands.Remove.GetNr(),
                                               removeBuilder.IsReturnResults ? Message.MessageType.Request2 : Message.MessageType.Request1);

            if (removeBuilder.IsSign)
            {
                message.SetPublicKeyAndSign(removeBuilder.KeyPair);
            }
            if (removeBuilder.IsRange)
            {
                var keys = new List <Number640>(2);
                keys.Add(removeBuilder.From);
                keys.Add(removeBuilder.To);
                message.SetIntValue(0); // marker
                message.SetKeyCollection(new KeyCollection(keys));
            }
            else if (removeBuilder.Keys == null)
            {
                if (removeBuilder.LocationKey == null || removeBuilder.DomainKey == null)
                {
                    throw new ArgumentException("Null not allowed in location or domain.");
                }
                message.SetKey(removeBuilder.LocationKey);
                message.SetKey(removeBuilder.DomainKey);

                if (removeBuilder.ContentKeys != null)
                {
                    message.SetKeyCollection(new KeyCollection(removeBuilder.LocationKey, removeBuilder.DomainKey,
                                                               removeBuilder.VersionKey, removeBuilder.ContentKeys));
                }
            }
            else
            {
                message.SetKeyCollection(new KeyCollection(removeBuilder.Keys));
            }

            var tcsResponse    = new TaskCompletionSource <Message>(message);
            var requestHandler = new RequestHandler(tcsResponse, PeerBean, ConnectionBean, removeBuilder);

            if (!removeBuilder.IsForceUdp)
            {
                return(requestHandler.SendTcpAsync(channelCreator));
            }
            return(requestHandler.SendUdpAsync(channelCreator));
        }
        public async Task StartBattleAsync()
        {
            var photoBot = Service.PhotoBot;

            await ReplyAsync("Starting new photoshop battle.");

            var proposalsChannel = await ChannelCreator.CreateChannelAsync("proposals", photoBot.Config.PhotoCategoryId);

            if (photoBot.Config.CurrentProposalsChannelId != 0)
            {
                var oldProposalsChannel = photoBot.SocketGuild.GetTextChannel(photoBot.Config.CurrentProposalsChannelId);
                await Archiver.ArchiveChannelAsync(oldProposalsChannel);
            }

            if (photoBot.Config.CurrentVotingChannelId != 0)
            {
                var oldVotingChannel = photoBot.SocketGuild.GetTextChannel(photoBot.Config.CurrentVotingChannelId);
                await Archiver.ArchiveChannelAsync(oldVotingChannel);
            }

            if (photoBot.Config.UserIdToPhotoChannelId != null)
            {
                foreach (var(_, value) in photoBot.Config.UserIdToPhotoChannelId)
                {
                    if (value == 0)
                    {
                        continue;
                    }
                    var channel = photoBot.SocketGuild.GetTextChannel(value);
                    if (channel != null)
                    {
                        await channel.DeleteAsync();
                    }
                }
            }

            photoBot.Config.CurrentProposalsChannelId = proposalsChannel.Id;

            await photoBot.GetPhotoUsersAsync();

            photoBot.Config.Proposals = new List <PhotoMessage>();
            photoBot.Config.Photos    = new List <PhotoMessage>();
            photoBot.Config.UserIdToPhotoChannelId = new Dictionary <ulong, ulong>();

            await PhotoConfig.SaveAsync();
        }
Example #27
0
        public async void TestPingBroadcastUdpToJava()
        {
            // setup Java server and get it's PeerAddress
            _tcs = new TaskCompletionSource <PeerAddress>();
            ThreadPool.QueueUserWorkItem(delegate
            {
                JarRunner.Run("JavaPingReceiver-start", DataReceived);
            });
            PeerAddress server = await _tcs.Task;

            // ping & test
            Peer           sender = null;
            ChannelCreator cc     = null;

            try
            {
                // setup .NET sender
                sender = new PeerBuilder(new Number160("0x9876")).
                         SetP2PId(55).
                         SetPorts(2424).
                         Start();

                cc = await sender.ConnectionBean.Reservation.CreateAsync(1, 0);

                var handshake       = new PingRpc(sender.PeerBean, sender.ConnectionBean);
                var task            = handshake.PingBroadcastUdpAsync(server, cc, new DefaultConnectionConfiguration());
                var responseMessage = await task;

                Assert.IsTrue(task.IsCompleted && !task.IsFaulted);
                Assert.AreEqual(responseMessage.Sender, server);
                Assert.IsTrue(responseMessage.Type == Message.MessageType.Ok);
                Assert.IsTrue(responseMessage.Command == Core.Rpc.Rpc.Commands.Ping.GetNr());
            }
            finally
            {
                if (cc != null)
                {
                    cc.ShutdownAsync().Wait();
                }
                if (sender != null)
                {
                    sender.ShutdownAsync().Wait();
                }
                JarRunner.WriteToProcess("JavaPingReceiver-stop");
            }
        }
Example #28
0
        public async void TestFireUdpFromJava()
        {
            // TODO find a way to check whether Java side received the ff ping
            // setup Java server and get it's PeerAddress
            _tcs = new TaskCompletionSource <PeerAddress>();
            ThreadPool.QueueUserWorkItem(delegate
            {
                JarRunner.Run("JavaPingReceiver-start", DataReceived);
            });
            PeerAddress server = await _tcs.Task;

            // ping & test
            Peer           sender = null;
            ChannelCreator cc     = null;

            try
            {
                // setup .NET sender
                sender = new PeerBuilder(new Number160("0x9876")).
                         SetP2PId(55).
                         SetPorts(2424).
                         Start();

                cc = await sender.ConnectionBean.Reservation.CreateAsync(1, 0);

                var handshake       = new PingRpc(sender.PeerBean, sender.ConnectionBean);
                var task            = handshake.FireUdpAsync(server, cc, new DefaultConnectionConfiguration());
                var responseMessage = await task;

                Assert.IsTrue(task.IsCompleted && !task.IsFaulted);
                Assert.IsTrue(responseMessage == null);
            }
            finally
            {
                if (cc != null)
                {
                    cc.ShutdownAsync().Wait();
                }
                if (sender != null)
                {
                    sender.ShutdownAsync().Wait();
                }
                JarRunner.WriteToProcess("JavaPingReceiver-stop");
            }
        }
Example #29
0
        private TaskCompletionSource <Message.Message> Send(Message.Message message, IConnectionConfiguration configuration,
                                                            ChannelCreator channelCreator)
        {
            var tcsResponse = new TaskCompletionSource <Message.Message>(message);

            tcsResponse.Task.ContinueWith(taskResponse =>
            {
                if (!taskResponse.IsFaulted)
                {
                    var response = taskResponse.Result;
                    if (response != null)
                    {
                        var neighborSet = response.NeighborsSet(0);
                        if (neighborSet != null)
                        {
                            foreach (var neighbor in neighborSet.Neighbors)
                            {
                                lock (PeerBean.PeerStatusListeners)
                                {
                                    foreach (var listener in PeerBean.PeerStatusListeners)
                                    {
                                        listener.PeerFound(neighbor, response.Sender, null);
                                    }
                                }
                            }
                        }
                    }
                }
            });

            var requestHandler = new RequestHandler(tcsResponse, PeerBean, ConnectionBean, configuration);

            if (!configuration.IsForceTcp)
            {
                requestHandler.SendUdpAsync(channelCreator);
            }
            else
            {
                requestHandler.SendTcpAsync(channelCreator);
            }
            // .NET-specific: Return TCS instead of Task. It's actually the same TCS that is provided with
            // the RequestHandler c'tor
            return(tcsResponse);
        }
Example #30
0
        public async void TestPingUdp()
        {
            Peer           sender = null;
            Peer           recv1  = null;
            ChannelCreator cc     = null;

            try
            {
                sender = new PeerBuilder(new Number160("0x9876")).
                         SetP2PId(55).
                         SetPorts(2424).
                         Start();
                recv1 = new PeerBuilder(new Number160("0x1234")).
                        SetP2PId(55).
                        SetPorts(8088).
                        Start();
                var handshake = new PingRpc(sender.PeerBean, sender.ConnectionBean);

                cc = await recv1.ConnectionBean.Reservation.CreateAsync(1, 0);

                var   t = handshake.PingUdpAsync(recv1.PeerAddress, cc, new DefaultConnectionConfiguration());
                await t;
                Assert.IsTrue(t.IsCompleted && !t.IsFaulted);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (cc != null)
                {
                    cc.ShutdownAsync().Wait();
                }
                if (sender != null)
                {
                    sender.ShutdownAsync().Wait();
                }
                if (recv1 != null)
                {
                    recv1.ShutdownAsync().Wait();
                }
            }
        }
Example #31
0
        public async void TestPingHandlerError()
        {
            Peer           sender = null;
            Peer           recv1  = null;
            ChannelCreator cc     = null;

            try
            {
                sender = new PeerBuilder(new Number160("0x9876"))
                         .SetP2PId(55)
                         .SetPorts(2424)
                         .Start();
                recv1 = new PeerBuilder(new Number160("0x1234"))
                        .SetP2PId(55)
                        .SetPorts(8088)
                        .Start();
                var handshake1 = new PingRpc(sender.PeerBean, sender.ConnectionBean, false, true, false);
                var handshake2 = new PingRpc(recv1.PeerBean, recv1.ConnectionBean, false, true, false);

                cc = await recv1.ConnectionBean.Reservation.CreateAsync(0, 1);

                var   tr = handshake1.PingTcpAsync(recv1.PeerAddress, cc, new DefaultConnectionConfiguration());
                await tr;

                Assert.IsTrue(tr.IsFaulted);
            }
            finally
            {
                if (cc != null)
                {
                    cc.ShutdownAsync().Wait();
                }
                if (sender != null)
                {
                    sender.ShutdownAsync().Wait();
                }
                if (recv1 != null)
                {
                    recv1.ShutdownAsync().Wait();
                }
            }
        }
Example #32
0
        /// <summary>
        /// Sends a message that indicates this peer is about to quit. This is an RPC.
        /// </summary>
        /// <param name="remotePeer">The remote peer to send this request.</param>
        /// <param name="shutdownBuilder">Used for the sign and force TCP flag. Set if the message should be signed.</param>
        /// <param name="channelCreator">The channel creator that creates connections.</param>
        /// <returns>The future response message.</returns>
        public Task <Message.Message> QuitAsync(PeerAddress remotePeer, ShutdownBuilder shutdownBuilder,
                                                ChannelCreator channelCreator)
        {
            var message = CreateRequestMessage(remotePeer, Rpc.Commands.Quit.GetNr(),
                                               Message.Message.MessageType.RequestFf1);

            if (shutdownBuilder.IsSign)
            {
                message.SetPublicKeyAndSign(shutdownBuilder.KeyPair);
            }

            var tcsResponse    = new TaskCompletionSource <Message.Message>(message);
            var requestHandler = new RequestHandler(tcsResponse, PeerBean, ConnectionBean, shutdownBuilder);

            Logger.Debug("Send QUIT message {0}.", message);
            if (!shutdownBuilder.IsForceTcp)
            {
                return(requestHandler.FireAndForgetUdpAsync(channelCreator));
            }
            return(requestHandler.SendTcpAsync(channelCreator));
        }
Example #33
0
        /// <summary>
        /// Adds a listener to the response tasks and releases all acquired channels in the channel creator.
        /// </summary>
        /// <param name="channelCreator">The channel creator that will be shutdown and all connections will be closed.</param>
        /// <param name="tasks">The tasks to listen to. If all the tasks finished, then the channel creator is shut down.
        /// If null is provided, then the channel crator is shut down immediately.</param>
        /// <returns>The task that completes when all listeners have completed.</returns>
        public static Task AddReleaseListener(ChannelCreator channelCreator, params Task[] tasks)
        {
            if (tasks == null)
            {
                return(channelCreator.ShutdownAsync());
            }
            var continuationTasks = new List <Task>(tasks.Length);
            int count             = tasks.Count();
            var finished          = new VolatileInteger(0);

            foreach (var task in tasks)
            {
                var contTask = task.ContinueWith(delegate
                {
                    if (finished.IncrementAndGet() == count)
                    {
                        channelCreator.ShutdownAsync();
                    }
                });
                continuationTasks.Add(contTask);
            }
            return(Task.WhenAll(continuationTasks));
        }
		void IWcfEndpointVisitor.VisitBindingAddressEndpoint(BindingAddressEndpointModel model)
		{
			if (model.HasViaAddress)
			{
				var address = model.EndpointAddress ?? new EndpointAddress(model.Address);
				var description = ContractDescription.GetContract(contract);
				var binding = GetEffectiveBinding(model.Binding, address.Uri);
				var endpoint = new ServiceEndpoint(description, binding, address);
				endpoint.Behaviors.Add(new ClientViaBehavior(model.ViaAddress));
				channelCreator = GetChannel(contract, endpoint);
			}
			else
			{
				if (model.EndpointAddress != null)
				{
					var binding = GetEffectiveBinding(model.Binding, model.EndpointAddress.Uri);
					channelCreator = GetChannel(contract, binding, model.EndpointAddress);
				}
				else
				{
					var binding = GetEffectiveBinding(model.Binding, new Uri(model.Address));
					channelCreator = GetChannel(contract, binding, model.Address);
				}
			}
		}
		void IWcfEndpointVisitor.VisitBindingEndpoint(BindingEndpointModel model)
		{
			channelCreator = GetChannel(contract, GetEffectiveBinding(model.Binding, null), string.Empty);
		}
		void IWcfEndpointVisitor.VisitConfigurationEndpoint(ConfigurationEndpointModel model)
		{
			channelCreator = GetChannel(contract, model.EndpointName);
		}
		void IWcfEndpointVisitor.VisitServiceEndpoint(ServiceEndpointModel model)
		{
			channelCreator = GetChannel(contract, model.ServiceEndpoint);
		}
		void IWcfEndpointVisitor.VisitContractEndpoint(ContractEndpointModel model)
		{
			channelCreator = GetChannel(contract);
		}
		private void DiscoverEndpoint(DiscoveryEndpoint discoveryEndpoint, DiscoveredEndpointModel model)
		{
			using (var discover = new DiscoveryClient(discoveryEndpoint))
			{
				var criteria = CreateSearchCriteria(model);

				var discovered = discover.Find(criteria);
				if (discovered.Endpoints.Count > 0)
				{
					var binding = model.Binding;
					var endpointMetadata = discovered.Endpoints[0];
					if (discovered.Endpoints.Count > 1 && model.EndpointPreference != null)
					{
						endpointMetadata = model.EndpointPreference(discovered.Endpoints);
						if (endpointMetadata == null)
						{
							throw new EndpointNotFoundException(string.Format(
								"More than one endpoint was discovered for contract {0}.  " +
								"However, an endpoint could be selected.  This is most likely " +
								"a bug with the user-defined endpoint prefeence.",
								contract.FullName));
						}
					}

					if (binding == null && model.DeriveBinding == false)
					{
						binding = GetBindingFromMetadata(endpointMetadata);
					}
					
					var address = endpointMetadata.Address;
					if (model.Identity != null)
					{
						address = new EndpointAddress(address.Uri, model.Identity, address.Headers);
					}

					binding = GetEffectiveBinding(binding, address.Uri);
					var innerCreator = GetChannel(contract, binding, address);
					channelCreator = () =>
					{
						var channel = (IChannel)innerCreator();
						if (channel is IContextChannel)
						{
							var metadata = new DiscoveredEndpointMetadata(endpointMetadata);
							((IContextChannel)channel).Extensions.Add(metadata);
						}
						return channel;
					};
				}
				else
				{
					throw new EndpointNotFoundException(string.Format(
						"Unable to discover the endpoint for contract {0}.  " + 
						"Either no service exists or it does not support discovery.",
						contract.FullName));
				}
			}
		}
		private void DiscoverEndpoint(DiscoveryEndpoint discoveryEndpoint, DiscoveredEndpointModel model)
		{
			using (var discover = new DiscoveryClient(discoveryEndpoint))
			{
				var criteria = CreateSearchCriteria(model);

				var discovered = discover.Find(criteria);
				if (discovered.Endpoints.Count > 0)
				{
					var binding = model.Binding;
					var endpointMetadata = discovered.Endpoints[0];

					if (binding == null && model.DeriveBinding == false)
					{
						binding = GetBindingFromMetadata(endpointMetadata);					
					}
					
					var address = endpointMetadata.Address;
					binding = GetEffectiveBinding(binding, address.Uri);
					channelCreator = GetChannel(contract, binding, address);
				}
				else
				{
					throw new EndpointNotFoundException(string.Format(
						"Unable to discover the endpoint address for contract {0}.  " + 
						"Either no service exists or it does not support discovery.",
						contract.FullName));
				}
			}
		}