예제 #1
0
        /// <summary>
        /// Returns the operating system for the input <see cref="OperatingSystem"/>.
        /// </summary>
        public static string GetName(OperatingSystem operatingSystem)
        {
            ArgumentGuard.NotNull(operatingSystem, nameof(operatingSystem));

            switch (operatingSystem.Platform)
            {
            case PlatformID.Win32NT:
            case PlatformID.Win32S:
            case PlatformID.Win32Windows:
                return(Windows);

            case PlatformID.MacOSX:
                return(Macintosh);

            default:
                return(Unknown);
            }
        }
예제 #2
0
        /// <summary>
        /// Encodes and adds the input query argument to the input URI and returns the resulting
        /// URI.
        /// </summary>
        public static Uri AddUriQueryArg(this Uri uri, string name, string value)
        {
            ArgumentGuard.NotNull(uri, nameof(uri));
            ArgumentGuard.TrimNotEmpty(ref name, nameof(name));
            ArgumentGuard.TrimNotNull(ref value, nameof(value));

            var fragment = "{0}={1}".Fmt(name, UrlEncode(value));
            var query    = uri.Query.Trim();

            if (query.Length == 0)
            {
                query = "?" + fragment;
            }
            else
            {
                query = query + "&" + fragment;
            }

            return(new Uri(uri.GetLeftPart(UriPartial.Path) + query));
        }
예제 #3
0
        /// <summary>
        /// Appends the specified text to the text file at the specified path.
        /// </summary>
        /// <param name="path">File path</param>
        /// <param name="text">Text to append</param>
        /// <param name="newLine">Whether to add a new line at the end of the text</param>
        public static void AppendToTextFile(string path, string text, bool newLine = true)
        {
            ArgumentGuard.NotNull(path, nameof(path));
            ArgumentGuard.NotNull(text, nameof(text));

            if (newLine)
            {
                text += Environment.NewLine;
            }

            if (!File.Exists(path))
            {
                WriteTextFile(path, text, true);
                return;
            }

            using (var sw = File.AppendText(path))
            {
                sw.Write(text);
            }
        }
예제 #4
0
        /// <summary>
        /// Returns all the bytes of the input stream.
        /// </summary>
        public static byte[] ReadToEnd(this Stream stream, int bufferSize = 1024, int length = 0, long maxLength = 0)
        {
            ArgumentGuard.NotNull(stream, nameof(stream));

            using (var ms = length == 0 ? new MemoryStream() : new MemoryStream(length))
            {
                byte[] array = new byte[bufferSize];
                int    count;
                long   maxPosition  = maxLength - bufferSize;
                bool   stillReading = true;
                while (stillReading && (count = stream.Read(array, 0, array.Length)) != 0)
                {
                    if (maxLength > 0 && ms.Position >= maxPosition)
                    {
                        stillReading = false;
                        count        = (int)Math.Max(0, maxLength - ms.Position);
                    }
                    ms.Write(array, 0, count);
                }
                return(ms.ToArray());
            }
        }
예제 #5
0
        public static T DeserializeBody <T>(
            this HttpResponseMessage response,
            bool dispose,
            JsonSerializer serializer,
            params int[] validStatuses)
        {
            ArgumentGuard.NotNull(response, nameof(response));

            serializer = serializer ?? JsonUtils.Serializer;

            if (response.StatusCode != HttpStatusCode.OK &&
                !validStatuses.Contains((int)response.StatusCode))
            {
                var msg = "Unexpected status: {0} {1}"
                          .Fmt((int)response.StatusCode, response.ReasonPhrase);
                throw new WebException(msg, WebExceptionStatus.ProtocolError);
            }

            using (var s = response.Content.ReadAsStreamAsync().Result)
            {
                var json = new StreamReader(s).ReadToEnd();

                try
                {
                    var body = serializer.Deserialize <T>(json);
                    if (dispose)
                    {
                        response.Dispose();
                    }

                    return(body);
                }
                catch (Exception ex)
                {
                    throw new FormatException("Failed to deserialize '{0}'".Fmt(json), ex);
                }
            }
        }
예제 #6
0
        /// <summary>
        /// Appends the specified text to the text file at the specified path.
        /// </summary>
        /// <param name="path">File path</param>
        /// <param name="lines">Text to append</param>
        public static void AppendToTextFile(string path, string[] lines)
        {
            ArgumentGuard.NotNull(path, nameof(path));
            ArgumentGuard.NotNull(lines, nameof(lines));

            StringBuilder sb = new StringBuilder(2000);

            foreach (string line in lines)
            {
                sb.Append(line).AppendLine();
            }

            if (!File.Exists(path))
            {
                WriteTextFile(path, sb.ToString(), true);
                return;
            }

            using (var sw = File.AppendText(path))
            {
                sw.Write(sb.ToString());
            }
        }
예제 #7
0
 public static void TrimNotEmpty(ref string param, string paramName)
 {
     ArgumentGuard.NotNull(param, paramName);
     param = param.Trim();
     ArgumentGuard.NotEmpty(param, paramName);
 }
예제 #8
0
        /// <summary>
        /// Returns the full path to the folder containing the input assembly.
        /// </summary>
        public static string GetAssemblyFolder(Assembly assembly)
        {
            ArgumentGuard.NotNull(assembly, nameof(assembly));

            return(Path.GetFullPath(Path.GetDirectoryName(assembly.Location)));
        }
예제 #9
0
        /// <summary>
        /// Parses the input user-agent string.
        /// </summary>
        /// <param name="userAgent">User agent string to parse</param>
        /// <param name="unknowns">Whether to treat unknown products as <c>Unknown</c> or
        /// throw exceptions</param>
        public static UserAgent ParseUserAgentString(string userAgent, bool unknowns = true)
        {
            ArgumentGuard.NotNull(userAgent, nameof(userAgent));

            userAgent = userAgent.Trim();
            var result = new UserAgent();

            result.OriginalUserAgentString = userAgent;
            // OS
            var oss     = new Dictionary <string, Match>();
            var matches = OSRegex_.Matches(userAgent);

            foreach (Match m in matches)
            {
                oss[m.Groups["os"].Value.ToLowerInvariant()] = m;
            }

            Match osmatch = null;

            if (matches.Count == 0)
            {
                if (unknowns)
                {
                    result.OS = OSNames.Unknown;
                }
                else
                {
                    throw new NotSupportedException("Unknown OS: {0}".Fmt(userAgent));
                }
            }
            else
            {
                if (oss.Count > 1 && oss.ContainsKey("android"))
                {
                    osmatch = oss["android"];
                }
                else
                {
                    osmatch = oss.First().Value;
                }

                result.OS             = osmatch.Groups["os"].Value;
                result.OSMajorVersion = osmatch.Groups["major"].Value;
                result.OSMinorVersion = osmatch.Groups["minor"].Value;
                if (!string.IsNullOrWhiteSpace(result.OSMajorVersion) && string.IsNullOrWhiteSpace(result.OSMinorVersion))
                {
                    result.OSMinorVersion = "0";
                }
            }

            // OS Normalization
            if (result.OS.StartsWithOrdinal("CPU"))
            {
                result.OS = OSNames.IOS;
            }
            else if (result.OS == "Windows XP")
            {
                result.OS             = OSNames.Windows;
                result.OSMajorVersion = "5";
                result.OSMinorVersion = "1";
            }
            else if (result.OS == "Windows 2000")
            {
                result.OS             = OSNames.Windows;
                result.OSMajorVersion = "5";
                result.OSMinorVersion = "0";
            }
            else if (result.OS == "Windows NT")
            {
                result.OS = OSNames.Windows;
                if (result.OSMajorVersion == "6" && result.OSMinorVersion == "1")
                {
                    result.OSMajorVersion = "7";
                    result.OSMinorVersion = "0";
                }
                else if (string.IsNullOrWhiteSpace(result.OSMajorVersion))
                {
                    result.OSMajorVersion = "4";
                    result.OSMinorVersion = "0";
                }
            }
            else if (result.OS == "Mac_PowerPC")
            {
                result.OS = OSNames.Macintosh;
            }
            else if (result.OS == "CrOS")
            {
                result.OS = OSNames.ChromeOS;
            }

            // Browser
            var browserMatch = BrowserRegex_.Match(userAgent);

            result.Browser             = browserMatch.Groups["product"].Value;
            result.BrowserMajorVersion = browserMatch.Groups["major"].Value;
            result.BrowserMinorVersion = browserMatch.Groups["minor"].Value;

            var browserOK = browserMatch.Success;

            if (result.OS == OSNames.Windows)
            {
                var edgeMatch = Edge_.Match(userAgent);
                if (edgeMatch.Success)
                {
                    result.Browser             = BrowserNames.Edge;
                    result.BrowserMajorVersion = edgeMatch.Groups["major"].Value;
                    result.BrowserMinorVersion = edgeMatch.Groups["minor"].Value;
                }

                // IE11 and later is "hidden" on purpose.
                // http://blogs.msdn.com/b/ieinternals/archive/2013/09/21/
                //   internet-explorer-11-user-agent-string-ua-string-sniffing-
                //   compatibility-with-gecko-webkit.aspx
                var iematch = HiddenIE_.Match(userAgent);
                if (iematch.Success)
                {
                    result.Browser             = BrowserNames.IE;
                    result.BrowserMajorVersion = iematch.Groups["major"].Value;
                    result.BrowserMinorVersion = iematch.Groups["minor"].Value;

                    browserOK = true;
                }
            }

            if (!browserOK)
            {
                if (unknowns)
                {
                    result.Browser = "Unknown";
                }
                else
                {
                    throw new NotSupportedException("Unknown browser: {0}".Fmt(userAgent));
                }
            }

            // Explicit browser version (if available)
            var versionMatch = VerRegex_.Match(userAgent);

            if (versionMatch.Success)
            {
                result.BrowserMajorVersion = versionMatch.Groups["major"].Value;
                result.BrowserMinorVersion = versionMatch.Groups["minor"].Value;
            }

            return(result);
        }
예제 #10
0
 public Url(Uri baseUri)
     : base(ArgumentGuard.NotNull(baseUri, nameof(baseUri)).ToString())
 {
 }