public static bool TryConnect(this TcpClient tcpClient, IPEndPoint ep, int retires, int timeout)
 {
     // TODO: exponential backoff.
     do
     {
         try
         {
             tcpClient.Connect(ep);
             LogMessage("Connected to {0}", ep);
             return true;
         }
         catch (SocketException e)
         {
             switch (e.SocketErrorCode)
             {
                 case SocketError.ConnectionRefused:
                 case SocketError.ConnectionReset:
                 case SocketError.HostDown:
                 case SocketError.Shutdown:
                 case SocketError.TimedOut:
                 case SocketError.TryAgain:
                     LogMessage("Connection to {0} failed with {1} wating {2} to retry",
                         ep, e.SocketErrorCode, timeout);
                     System.Threading.Thread.Sleep(timeout);
                     LogMessage("Retrying connection to {0}", ep);
                     retires--;
                     break;
                 default:
                     return false;
             }
         }
     }
     while (retires > 0);
     return false;
 }
 /// <summary>
 /// Connects to specified target host/port.
 /// </summary>
 /// <param name="route">The route.</param>
 /// <param name="targetHost">The target host.</param>
 /// <param name="targetPort">The target port.</param>
 /// <param name="nameResolver">The name resolver.</param>
 /// <returns></returns>
 public static Socket Connect(this Route route, string targetHost, int targetPort, INameResolver nameResolver)
 {
     var targetAddress = nameResolver.Resolve(targetHost, route);
     if (targetAddress == null)
         throw new ProxyRouteException(targetHost);
     return route.Connect(targetAddress, targetPort);
 }
Esempio n. 3
0
        public static IEnumerable<string> GetMessages(
            this NamedPipeClientStream pipeStream)
        {
            Decoder decoder = Encoding.UTF8.GetDecoder();
            Byte[] bytes = new Byte[10];
            Char[] chars = new Char[10];

            pipeStream.Connect();
            pipeStream.ReadMode = PipeTransmissionMode.Message;

            int numBytes;
            do
            {
                string message = "";
                do
                {
                    numBytes = pipeStream.Read(bytes, 0, bytes.Length);
                    int numChars = decoder.GetChars(bytes, 0, numBytes, chars, 0);
                    message += new String(chars, 0, numChars);
                } while (!pipeStream.IsMessageComplete);
                decoder.Reset();
                // *** producir el mensaje
                yield return message;
            } while (numBytes != 0);
        }
Esempio n. 4
0
 public static IObservable<Ohlcv> Connect(this TelnetrClient client, params object[] values)
 {
     foreach(var value in values) {
         client.Connect(value as dynamic);
     }
     return (IObservable<Ohlcv>)client;
 }
Esempio n. 5
0
        public static void Deserialize(this Template template)
        {
            template.Clear();

            var tplJs = new JSONObject(template.JSON);

            // Discard templates without the Operators and Connections fields
            if (tplJs.HasField("Operators") && tplJs.HasField("Connections")) {
                var opsJs = tplJs.GetField("Operators");
                var connsJs = tplJs.GetField("Connections");
                foreach (var opJs in opsJs.list) {
                    var type = System.Type.GetType(opJs["Type"].str);
                    var op = (Operator) System.Activator.CreateInstance(type);
                    op.Deserialize(opJs);
                    template.AddOperator(op, false);
                }
                foreach (var connJs in connsJs.list) {

                    // Discard connections with invalid Operator GUIDs
                    if (!template.Operators.ContainsKey(connJs["From"].str) || !template.Operators.ContainsKey(connJs["To"].str)) {
                        Debug.LogWarning("Discarding connection in template due to an invalid Operator GUID");
                        continue;
                    }

                    Operator fromOp = template.Operators[connJs["From"].str];
                    IOOutlet output = fromOp.GetOutput(connJs["Output"].str);

                    Operator toOp = template.Operators[connJs["To"].str];
                    IOOutlet input = toOp.GetInput(connJs["Input"].str);

                    template.Connect(fromOp, output, toOp, input, false);
                }
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Connect to a device via TCP/IP.
        /// </summary>
        /// <param name="client">
        /// An instance of a class that implements the <see cref="IAdbClient"/> interface.
        /// </param>
        /// <param name="address">
        /// The IP address of the remote device.
        /// </param>
        public static void Connect(this IAdbClient client, IPAddress address)
        {
            if (address == null)
            {
                throw new ArgumentNullException(nameof(address));
            }

            client.Connect(new IPEndPoint(address, AdbClient.DefaultPort));
        }
Esempio n. 7
0
        /// <summary>
        /// Connect to a device via TCP/IP.
        /// </summary>
        /// <param name="client">
        /// An instance of a class that implements the <see cref="IAdbClient"/> interface.
        /// </param>
        /// <param name="host">
        /// The host address of the remote device.
        /// </param>
        public static void Connect(this IAdbClient client, string host)
        {
            if (string.IsNullOrEmpty(host))
            {
                throw new ArgumentNullException(nameof(host));
            }

            client.Connect(new DnsEndPoint(host, AdbClient.DefaultPort));
        }
Esempio n. 8
0
        /// <summary>
        /// Connect to a device via TCP/IP.
        /// </summary>
        /// <param name="client">
        /// An instance of a class that implements the <see cref="IAdbClient"/> interface.
        /// </param>
        /// <param name="endpoint">
        /// The IP endpoint at which the <c>adb</c> server on the device is running.
        /// </param>
        public static void Connect(this IAdbClient client, IPEndPoint endpoint)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException(nameof(endpoint));
            }

            client.Connect(new DnsEndPoint(endpoint.Address.ToString(), endpoint.Port));
        }
        public static void ConnectTest(this Rfc977NntpClientWithExtensions obj)
        {
            var Server = ConfigurationManager.AppSettings["NntpHostname"];
            var UserId = ConfigurationManager.AppSettings["NntpUserIdX"];
            var Password = ConfigurationManager.AppSettings["NntpPassword"];

            obj.Connect(Server);
            // client.AuthenticateUser(UserId, Password);
        }
Esempio n. 10
0
 public static void SetOption(this MIGInterface iface, string option, string value)
 {
     var opt = iface.GetOption(option);
     if (opt != null)
     {
         iface.Disconnect();
         opt.Value = value;
         iface.Connect();
     }
 }
Esempio n. 11
0
 /// <summary>
 /// Connects to target host/address and port.
 /// </summary>
 /// <param name="route">The route.</param>
 /// <param name="hostOrAddress">The host or address.</param>
 /// <param name="port">The port.</param>
 /// <returns></returns>
 /// <exception cref="System.IO.IOException"></exception>
 public static Socket Connect(this Route route, string hostOrAddress, int port)
 {
     IPAddress ipAddress;
     if (!IPAddress.TryParse(hostOrAddress, out ipAddress))
     {
         var entry = Dns.GetHostEntry(hostOrAddress);
         ipAddress = entry.AddressList.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork)
                     ?? entry.AddressList.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetworkV6);
     }
     if (ipAddress == null)
         throw new IOException(string.Format("Impossible to resolve '{0}'", hostOrAddress));
     return route.Connect(ipAddress, port);
 }
Esempio n. 12
0
        /// <summary>
        /// </summary>
        /// <param name="pGraph"></param>
        /// <param name="pSrc"></param>
        /// <param name="pDest"></param>
        /// <returns></returns>
        public static bool ConnectFilters(this IGraphBuilder pGraph, IBaseFilter pSrc, IBaseFilter pDest)
        {
            // Find an output pin on the first filter.
            IPin pIn = pDest.FindUnconnectedPin(PinDirection.Input);
            IPin pOut = pSrc.FindUnconnectedPin(PinDirection.Output);

            if (pIn == null || pOut == null) return false;

            int hresult = pGraph.Connect(pOut, pIn);
            Marshal.ThrowExceptionForHR(hresult);

            pIn.Dispose();
            pOut.Dispose();
            return true;
        }
Esempio n. 13
0
 public static Task ConnectAsync(this Tcp tcp, string ipAddress, int port)
 {
     var tcs = new TaskCompletionSource<object>();
     try {
         tcp.Connect(ipAddress, port, (e) => {
             if (e == null) {
                 tcs.SetResult(null);
             } else {
                 tcs.SetException(e);
             }
         });
     } catch (Exception e) {
         tcs.SetException(e);
     }
     return tcs.Task;
 }
Esempio n. 14
0
 public static Task ConnectAsync(this Pipe pipe, string name)
 {
     var tcs = new TaskCompletionSource<object>();
     try {
         pipe.Connect(name, (e) => {
             if (e == null) {
                 tcs.SetResult(null);
             } else {
                 tcs.SetException(e);
             }
         });
     } catch (Exception e) {
         tcs.SetException(e);
     }
     return tcs.Task;
 }
Esempio n. 15
0
 public static Task ConnectAsync(this Tcp tcp, IPEndPoint ep)
 {
     var tcs = new TaskCompletionSource<object>();
     try {
         tcp.Connect(ep, (e) => {
             if (e == null) {
                 tcs.SetResult(null);
             } else {
                 tcs.SetException(e);
             }
         });
     } catch (Exception e) {
         tcs.SetException(e);
     }
     return tcs.Task;
 }
Esempio n. 16
0
        public static void Connect(this TcpClient connection, string ip, int port, out SocketException ex)
        {
            ex = null;

            for (int i = 0; i < 10 && !connection.Connected; i++)
            {
                try
                {
                    connection.Connect(IPAddress.Parse(ip), port);
                    break;
                }
                catch (SocketException se)
                {
                    ex = se;
                    continue;
                }
            }
        }
        public static bool TryConnect(this Socket s, EndPoint ep, int timeout)
        {
            bool connected = false;
            new Thread(delegate {
                    try {
                        // s.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.Linger, new byte[] { 0, 0, 0, 0 });
                        s.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
                        s.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, false);
                        s.SendTimeout = timeout;
                        s.ReceiveTimeout = timeout;
                        s.Connect(ep);

                        connected = true;
                    } catch { }
                }).Start();
            int checks = 10;
            while (checks-- > 0 && connected == false) Thread.Sleep(100);
            // if (connected == false) throw new Exception("Failed to connect");
            return connected;
        }
Esempio n. 18
0
        /// <summary>
        /// Connect to the first ip address of the host the match the address family
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="host">Host name to resolve</param>
        /// <param name="port">Port to connect</param>
        public static void Connect(this AsyncSocket socket, string host, int port)
        {
            if (host == null)
                throw new ArgumentNullException("host");

            if (port < 0 || port > 65535)
            {
                throw new ArgumentOutOfRangeException("port");
            }

            var ipAddress = Dns.GetHostAddresses(host).FirstOrDefault(ip=>                 
                ip.AddressFamily == socket.AddressFamily || 
                (socket.AddressFamily == AddressFamily.InterNetworkV6 && socket.DualMode && ip.AddressFamily == AddressFamily.InterNetwork));

            if (ipAddress != null)
            {
                socket.Connect(ipAddress, port);
            }
            else
            {
                throw new ArgumentException("invalid host", "host");
            }            
        }
Esempio n. 19
0
 public static BufferingConsumer Consume(this IDataProducer producer)
 {
     var c = new BufferingConsumer();
     producer.Connect(c);
     return c;
 }
 /// <summary>
 /// Gets an <seealso cref="Channel"/> abstraction wrapper using the <seealso cref="OutboundSocket"/> instance.
 /// </summary>
 /// <param name="eventSocket">The <seealso cref="OutboundSocket"/> instance to use.</param>
 /// <returns>A Task of <seealso cref="Channel"/>.</returns>
 public static async Task<Channel> GetChannel(this OutboundSocket eventSocket)
 {
     await eventSocket.Connect().ConfigureAwait(false);
     return new Channel(eventSocket);
 }
Esempio n. 21
0
 public static void SetOption(this MIGInterface iface, string option, string value)
 {
     var opt = iface.GetOption(option);
     if (opt == null)
     {
         opt = new MIGServiceConfiguration.Interface.Option() { Name =  option };
         iface.Options.Add(opt);
     }
     iface.Disconnect();
     opt.Value = value;
     iface.Connect();
 }
Esempio n. 22
0
        /// <summary>
        /// Connects the given <paramref name="pipeClientStream"/> object and write the given <paramref name="message"/> into it.
        /// </summary>
        /// <param name="pipeClientStream">The <see cref="NamedPipeClientStream"/> to connect and write to.</param>
        /// <param name="message">The message to write into the <see cref="NamedPipeClientStream"/> object.</param>
        /// <param name="timeout">The timeout in milliseconds for the client connection.</param>
        public static bool ConnectAndWrite(this NamedPipeClientStream pipeClientStream, byte[] message, int timeout = 1000)
        {
            if (message != null && message.Length > 0)
              {
            try
            {
              pipeClientStream.Connect(timeout);

              pipeClientStream.Write(
              message
            , 0
            , message.Length);

              return true;
            }
            catch (Exception ex)
            {
              Logger.Error(ex.Message);
            }
              }

              return false;
        }
        internal static void UploadFile(this SftpClient sftp, FileInfo file, bool overwrite = false, string remoteDirectoryPath = null)
        {
            if (file == null) throw new ArgumentNullException("file");

            // auto-connect
            if (sftp.IsConnected == false)
                sftp.Connect();

            // create remote directory and return the new path
            var dest = CreateRemoteDirectory(sftp, file.Name, remoteDirectoryPath);

            // stream file to ftp directory
            using (var stream = file.OpenRead())
                sftp.UploadFile(stream, dest, overwrite);
        }
Esempio n. 24
0
 public static void TcpConnect(this ISocket socket, string host, int port)
 {
     socket.Connect("tcp://{0}:{1}", host, port);
 }
Esempio n. 25
0
 public static void Connect(this ISocket socket, string address, params object[] args)
 {
     socket.Connect(string.Format(address, args));
 }
Esempio n. 26
0
 public static void Connect(this AsyncSocket socket, IPAddress ipAddress, int port)
 {
     socket.Connect(new IPEndPoint(ipAddress, port));
 }
Esempio n. 27
0
 public static List<RadDiagramShape> CreateDivisionBranch(this RadDiagram diagram, string name)
 {
     var shapes = new List<RadDiagramShape>();
     var director = diagram.CreateShape(name + " director");
     shapes.Add(director);
     var manCount = Rand.Next(2, 4);
     for (var j = 0; j < manCount; j++)
     {
         var man = diagram.CreateShape(name + " manager");
         shapes.Add(man);
         man.Geometry = ShapeFactory.GetShapeGeometry(CommonShapeType.EllipseShape);
         man.Background = new SolidColorBrush(Colors.Brown);
         var devCount = Rand.Next(3, 6);
         diagram.AddConnection(director, man, ConnectorPosition.Bottom,ConnectorPosition.Top);
         for (var k = 0; k < devCount; k++)
         {
             var dev = diagram.CreateShape("Dev " + k);
             shapes.Add(dev);
             dev.Background = new SolidColorBrush(Colors.LightGray);
             diagram.Connect(man, dev);
         }
     }
     return shapes;
 }
Esempio n. 28
0
 public static Task<Tuple<ReactiveRTM.RTC.ReturnCode_t, ReactiveRTM.RTC.ConnectorProfile>> ConnectAsync(this PortService target,ReactiveRTM.RTC.ConnectorProfile connectorProfile)
 {
     return Task.Factory.StartNew(()=>{
         var ret = target.Connect(ref connectorProfile);
         return Tuple.Create(ret,connectorProfile);
     });
 }