コード例 #1
0
        public static uint[] Convert(string dotted)
        {
            if (dotted == null)
            {
                throw new ArgumentNullException("dotted");
            }

            var parts  = dotted.Split(new[] { '.' });
            var result = new List <uint> ();

            foreach (var s in parts.Where(s => !string.IsNullOrEmpty(s)))
            {
#if CF
                result.Add(uint.Parse(s));
#else
                uint temp;
#if NETCF
                if (TryParsers.UInt32TryParse(s, out temp))
#else
                if (uint.TryParse(s, out temp))
#endif
                { result.Add(temp); }
                else
                {
                    throw new ArgumentException(string.Format("Parameter {0} is out of 32 bit unsigned integer range", s), "dotted");
                }
#endif
            }

            return(result.ToArray());
        }
コード例 #2
0
        /// <summary>
        /// Converts decimal string to bytes.
        /// </summary>
        /// <param name="description">The decimal string.</param>
        /// <returns>The converted bytes.</returns>
        /// <remarks><c>" 16 18 "</c> is converted to <c>new byte[] { 0x10, 0x12 }</c>.</remarks>
        public static byte[] ConvertDecimal(string description)
        {
            if (description == null)
            {
                throw new ArgumentNullException("description");
            }

            var result  = new List <byte> ();
            var content = description.Trim().Split(new[] { ' ' });

            foreach (var part in content)
            {
#if CF
                result.Add(byte.Parse(part, NumberStyles.Integer, CultureInfo.InvariantCulture));
#else
                byte temp;
#if NETCF
                if (TryParsers.ByteTryParse(part, out temp))
#else
                if (byte.TryParse(part, out temp))
#endif
                { result.Add(temp); }
#endif
            }

            return(result.ToArray());
        }
コード例 #3
0
        private static bool tryCreatePorts(string value, out int[] result, out string parseError)
        {
            var ports = value.Trim('"').Split(',');
            var len   = ports.Length;
            var res   = new int[len];

            for (var i = 0; i < len; i++)
            {
                res[i] = Int32.MinValue;

                var port = ports[i].Trim();
                if (port.Length == 0)
                {
                    continue;
                }

#if SSHARP
                if (!TryParsers.Int32TryParse(port, out res[i]))
#else
                if (!Int32.TryParse(port, out res[i]))
#endif
                {
                    result     = new int[0];
                    parseError = port;

                    return(false);
                }
            }

            result     = res;
            parseError = String.Empty;

            return(true);
        }
コード例 #4
0
        internal FtpStatus GetResponseStatus()
        {
            while (true)
            {
                string response = null;

                try
                {
                    response = controlReader.ReadLine();
                }
                catch (IOException)
                {
                }

                if (response == null || response.Length < 3)
                {
                    return(ServiceNotAvailable());
                }

                int code;
#if SSHARP
                if (!TryParsers.Int32TryParse(response.Substring(0, 3), out code))
#else
                if (!Int32.TryParse(response.Substring(0, 3), out code))
#endif
                { return(ServiceNotAvailable()); }

                if (response.Length > 3 && response[3] == '-')
                {
                    string line = null;
                    string find = code.ToString() + ' ';
                    while (true)
                    {
                        line = null;
                        try
                        {
                            line = controlReader.ReadLine();
                        }
                        catch (IOException)
                        {
                        }
                        if (line == null)
                        {
                            return(ServiceNotAvailable());
                        }

                        response += Environment.NewLine + line;

                        if (line.StartsWith(find, StringComparison.Ordinal))
                        {
                            break;
                        }
                    }
                }
                return(new FtpStatus((FtpStatusCode)code, response));
            }
        }
コード例 #5
0
        public WebConnectionStream(WebConnection cnc, WebConnectionData data)
        {
            if (data == null)
            {
                throw new InvalidOperationException("data was not initialized");
            }
            if (data.Headers == null)
            {
                throw new InvalidOperationException("data.Headers was not initialized");
            }
            if (data.request == null)
            {
                throw new InvalidOperationException("data.request was not initialized");
            }
            isRead        = true;
            cb_wrapper    = new AsyncCallback(ReadCallbackWrapper);
            pending       = new ManualResetEvent(true);
            this.request  = data.request;
            read_timeout  = request.ReadWriteTimeout;
            write_timeout = read_timeout;
            this.cnc      = cnc;
            string contentType = data.Headers["Transfer-Encoding"];
            bool   chunkedRead = (contentType != null && contentType.IndexOf("chunked", StringComparison.OrdinalIgnoreCase) != -1);
            string clength     = data.Headers["Content-Length"];

            if (!chunkedRead && clength != null && clength != "")
            {
                try
                {
                    contentLength = Int32.Parse(clength);
                    if (contentLength == 0 && !IsNtlmAuth())
                    {
                        ReadAll();
                    }
                }
                catch
                {
                    contentLength = Int32.MaxValue;
                }
            }
            else
            {
                contentLength = Int32.MaxValue;
            }

            // Negative numbers?
#if SSHARP
            if (!TryParsers.Int32TryParse(clength, out stream_length))
#else
            if (!Int32.TryParse(clength, out stream_length))
#endif
            { stream_length = -1; }
        }
コード例 #6
0
        protected override void OnValueChanged()
        {
            int i;

#if NETCF
            if (TryParsers.Int32TryParse(Value, out i))
#else
            if (int.TryParse(Value, out i))
#endif
            { Enabled = i != 0; }
            else
            {
                Enabled = Convert.ToBoolean(Value);
            }
        }
コード例 #7
0
        /// <summary>
        /// Converts the byte string to bytes.
        /// </summary>
        /// <param name="description">The HEX string.</param>
        /// <returns>The converted bytes.</returns>
        /// <remarks><c>"80 00"</c> is converted to <c>new byte[] { 0x80, 0x00 }</c>.</remarks>
        public static byte[] Convert(IEnumerable <char> description)
        {
            if (description == null)
            {
                throw new ArgumentNullException("description");
            }

            var result = new List <byte> ();
            var buffer = new StringBuilder(2);

            foreach (var c in description.Where(c => !char.IsWhiteSpace(c)))
            {
                if (!char.IsLetterOrDigit(c))
                {
                    throw new ArgumentException("illegal character found", "description");
                }

                buffer.Append(c);
                if (buffer.Length != 2)
                {
                    continue;
                }
#if CF
                result.Add(byte.Parse(buffer.ToString(), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture));
                #else
                byte temp;
#if NETCF
                if (TryParsers.ByteTryParse(buffer.ToString(), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out temp))
#else
                if (byte.TryParse(buffer.ToString(), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out temp))
#endif
                { result.Add(temp); }
#endif
                buffer.Length = 0;
            }

            if (buffer.Length != 0)
            {
                throw new ArgumentException("not a complete byte string", "description");
            }

            return(result.ToArray());
        }
コード例 #8
0
        // Constructors

        internal HttpWebResponse(Uri uri, string method, WebConnectionData data, CookieContainer container)
        {
            this.uri          = uri;
            this.method       = method;
            webHeaders        = data.Headers;
            version           = data.Version;
            statusCode        = (HttpStatusCode)data.StatusCode;
            statusDescription = data.StatusDescription;
            stream            = data.stream;
            contentLength     = -1;

            try
            {
                string cl = webHeaders["Content-Length"];
#if SSHARP
                if (String.IsNullOrEmpty(cl) || !TryParsers.Int64TryParse(cl, out contentLength))
#else
                if (String.IsNullOrEmpty(cl) || !Int64.TryParse(cl, out contentLength))
#endif
                { contentLength = -1; }
            }
            catch (Exception)
            {
                contentLength = -1;
            }

            if (container != null)
            {
                this.cookie_container = container;
                FillCookies();
            }

            string content_encoding = webHeaders["Content-Encoding"];
            if (content_encoding == "gzip" && (data.request.AutomaticDecompression & DecompressionMethods.GZip) != 0)
            {
                stream = new GZipStream(stream, CompressionMode.Decompress);
            }
            else if (content_encoding == "deflate" && (data.request.AutomaticDecompression & DecompressionMethods.Deflate) != 0)
            {
                stream = new DeflateStream(stream, CompressionMode.Decompress);
            }
        }
コード例 #9
0
        public CrestronLoggerTraceListener(string initializeData)
        {
            string[] info = initializeData.Split(new char[] { ' ', ',', ';' });
            uint     lev;
            bool     logonly;

            if (info.Length == 0)
            {
                return;
            }
            if (info.Length > 0)
            {
                if (TryParsers.UInt32TryParse(info[0], out lev) && lev <= 10)
                {
                    _debugLevel = lev;
                }

                if (info.Length > 1)
                {
                    if (TryParsers.BooleanTryParse(info[1], out logonly))
                    {
                        _logOnlyThisLevel = logonly;
                    }

                    if (info.Length > 2)
                    {
                        LoggerModeEnum le;
                        try
                        {
                            le          = (LoggerModeEnum)Enum.Parse(typeof(LoggerModeEnum), info[2], true);
                            _loggerMode = le;
                        }
                        catch (ArgumentException)
                        {
                        }
                    }
                }
            }
        }
コード例 #10
0
		/// <summary>
		/// Creates a new instance of the <see cref="IP"/> class from a specific <see cref="String"/>.
		/// </summary>
		/// <param name="ip">IP string</param>
		public IP (string ip)
			{
			// IMPORTANT: copied from Mono's IPAddress.cs
			int pos = ip.IndexOf (' ');
			if (pos != -1)
				{
				string[] nets = ip.Substring (pos + 1).Split (new char[] {'.'});
				if (nets.Length > 0)
					{
					string lastNet = nets[nets.Length - 1];
					if (lastNet.Length == 0)
						throw new FormatException ("An invalid IP address was specified.");
#if NET_2_1 //workaround for smcs, as it generate code that can't access string.GetEnumerator ()
					foreach (char c in lastNet.ToCharArray ())
#else
					foreach (char c in lastNet)
						{
#endif
						if (!IsHexDigit (c))
							throw new FormatException ("An invalid IP address was specified.");
						}
					}
				ip = ip.Substring (0, pos);
				}

			if (ip.Length == 0 || ip[ip.Length - 1] == '.')
				throw new FormatException ("An invalid IP address was specified.");

			string[] ips = ip.Split (new char[] {'.'});
			if (ips.Length > IPv4Length)
				throw new FormatException ("An invalid IP address was specified.");

			// Make the number in network order
			try
				{
				_ip = new byte[IPv4Length];
				long val = 0;
				for (int i = 0; i < ips.Length; i++)
					{
					string subnet = ips[i];
					if ((3 <= subnet.Length && subnet.Length <= 4) && (subnet[0] == '0') && (subnet[1] == 'x' || subnet[1] == 'X'))
						{
						if (subnet.Length == 3)
							val = (byte)FromHex (subnet[2]);
						else
							val = (byte)((FromHex (subnet[2]) << 4) | FromHex (subnet[3]));
						}
					else if (subnet.Length == 0)
						throw new FormatException ("An invalid IP address was specified.");
					else if (subnet[0] == '0')
						{
						// octal
						val = 0;
						for (int j = 1; j < subnet.Length; j++)
							{
							if ('0' <= subnet[j] && subnet[j] <= '7')
								val = (val << 3) + subnet[j] - '0';
							else
								throw new FormatException ("An invalid IP address was specified.");
							}
						}
					else
						{
#if NETCF
						if (!TryParsers.Int64TryParse (subnet, NumberStyles.None, null, out val))
#else
						if (!long.TryParse (subnet, NumberStyles.None, null, out val))
#endif
							throw new FormatException ("An invalid IP address was specified.");
						}

					if (i == (ips.Length - 1))
						{
						if (i != 0 && val >= (256 << ((3 - i) * 8)))
							throw new FormatException ("An invalid IP address was specified.");
						else if (val > 0x3fffffffe) // this is the last number that parses correctly with MS
							throw new FormatException ("An invalid IP address was specified.");
						i = 3;
						}
					else if (val >= 0x100)
						throw new FormatException ("An invalid IP address was specified.");
					_ip[i] = (byte)val;
					}
				}
			catch (Exception)
				{
				throw new FormatException ("An invalid IP address was specified.");
				}
			}
コード例 #11
0
        private void ProcessSimpleMethod()
        {
            State = RequestState.TransferInProgress;

            FtpStatus status;

            if (method == WebRequestMethods.Ftp.PrintWorkingDirectory)
            {
                method = "PWD";
            }

            if (method == WebRequestMethods.Ftp.Rename)
            {
                method = RenameFromCommand;
            }

            status = SendCommand(method, file_name);

            ftpResponse.Stream = Stream.Null;

            string desc = status.StatusDescription;

            switch (method)
            {
            case WebRequestMethods.Ftp.GetFileSize:
            {
                if (status.StatusCode != FtpStatusCode.FileStatus)
                {
                    throw CreateExceptionFromResponse(status);
                }

                int  i, len;
                long size;
                for (i = 4, len = 0; i < desc.Length && Char.IsDigit(desc[i]); i++, len++)
                {
                    ;
                }

                if (len == 0)
                {
                    throw new WebException("Bad format for server response in " + method);
                }

#if SSHARP
                if (!TryParsers.Int64TryParse(desc.Substring(4, len), out size))
#else
                if (!Int64.TryParse(desc.Substring(4, len), out size))
#endif
                { throw new WebException("Bad format for server response in " + method); }

                ftpResponse.contentLength = size;
            }
            break;

            case WebRequestMethods.Ftp.GetDateTimestamp:
                if (status.StatusCode != FtpStatusCode.FileStatus)
                {
                    throw CreateExceptionFromResponse(status);
                }
                ftpResponse.LastModified = DateTime.ParseExact(desc.Substring(4), "yyyyMMddHHmmss", null);
                break;

            case WebRequestMethods.Ftp.MakeDirectory:
                if (status.StatusCode != FtpStatusCode.PathnameCreated)
                {
                    throw CreateExceptionFromResponse(status);
                }
                break;

            case ChangeDir:
                method = WebRequestMethods.Ftp.PrintWorkingDirectory;

                if (status.StatusCode != FtpStatusCode.FileActionOK)
                {
                    throw CreateExceptionFromResponse(status);
                }

                status = SendCommand(method);

                if (status.StatusCode != FtpStatusCode.PathnameCreated)
                {
                    throw CreateExceptionFromResponse(status);
                }
                break;

            case RenameFromCommand:
                method = WebRequestMethods.Ftp.Rename;
                if (status.StatusCode != FtpStatusCode.FileCommandPending)
                {
                    throw CreateExceptionFromResponse(status);
                }
                // Pass an empty string if RenameTo wasn't specified
                status = SendCommand(RenameToCommand, renameTo != null ? renameTo : String.Empty);
                if (status.StatusCode != FtpStatusCode.FileActionOK)
                {
                    throw CreateExceptionFromResponse(status);
                }
                break;

            case WebRequestMethods.Ftp.DeleteFile:
                if (status.StatusCode != FtpStatusCode.FileActionOK)
                {
                    throw CreateExceptionFromResponse(status);
                }
                break;
            }

            State = RequestState.Finished;
        }
コード例 #12
0
        // Probably we could do better having here a regex
        private Socket SetupPassiveConnection(string statusDescription)
        {
            // Current response string
            string response = statusDescription;

            if (response.Length < 4)
            {
                throw new WebException("Cannot open passive data connection");
            }

            // Look for first digit after code
            int i;

            for (i = 3; i < response.Length && !Char.IsDigit(response[i]); i++)
            {
                ;
            }
            if (i >= response.Length)
            {
                throw new WebException("Cannot open passive data connection");
            }

            // Get six elements
            string[] digits = response.Substring(i).Split(new char[] { ',' }, 6);
            if (digits.Length != 6)
            {
                throw new WebException("Cannot open passive data connection");
            }

            // Clean non-digits at the end of last element
            int j;

            for (j = digits[5].Length - 1; j >= 0 && !Char.IsDigit(digits[5][j]); j--)
            {
                ;
            }
            if (j < 0)
            {
                throw new WebException("Cannot open passive data connection");
            }

            digits[5] = digits[5].Substring(0, j + 1);

            IPAddress ip;

            try
            {
                ip = IPAddress.Parse(String.Join(".", digits, 0, 4));
            }
            catch (FormatException)
            {
                throw new WebException("Cannot open passive data connection");
            }

            // Get the port
            int p1, p2, port;

#if SSHARP
            if (!TryParsers.Int32TryParse(digits[4], out p1) || !TryParsers.Int32TryParse(digits[5], out p2))
#else
            if (!Int32.TryParse(digits[4], out p1) || !Int32.TryParse(digits[5], out p2))
#endif
            { throw new WebException("Cannot open passive data connection"); }

            port = (p1 << 8) + p2;             // p1 * 256 + p2
            //port = p1 * 256 + p2;
            if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
            {
                throw new WebException("Cannot open passive data connection");
            }

            IPEndPoint ep = new IPEndPoint(ip, port);
#if SSHARP
            CrestronClientSocket sock = new CrestronClientSocket();
#else
            Socket sock = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
#endif
            try
            {
                sock.Connect(ep);
            }
            catch (SocketException)
            {
                sock.Close();
                throw new WebException("Cannot open passive data connection");
            }

            return(sock);
        }