Commits

Constantin Veretennicov committed 2a02a23

Add MediaRange.TryParse().

Comments (0)

Files changed (3)

src/AssemblyInfo.cs

 // The form "{Major}.{Minor}.*" will automatically update the build and revision,
 // and "{Major}.{Minor}.{Build}.*" will update just the revision.
 
-[assembly: AssemblyVersion("0.1.0.0")]
+[assembly: AssemblyVersion("0.1.1.0")]
 
 // The following attributes are used to specify the signing key for the assembly, 
 // if desired. See the Mono documentation for more information about signing.

src/CsConneg.MediaRange.cs

 
         public static MediaRange Parse(string formattedMediaRange)
         {
+            if (formattedMediaRange == null)
+            {
+                throw new ArgumentNullException("formattedMediaRange");
+            }
+
             var parts = formattedMediaRange.Split(new[] {'/'}, 2);
             var primaryType = parts[0];
             var formattedSubTypeWithParams = parts[1];
             return new MediaRange(primaryType, subType);
         }
 
+        public static bool TryParse(
+            string formattedMediaRange,
+            out MediaRange parsedMediaRange)
+        {
+            try
+            {
+                parsedMediaRange = MediaRange.Parse(formattedMediaRange);
+                return true;
+            }
+            catch (Exception)
+            {
+                parsedMediaRange = null;
+                return false;
+            }
+        }
+
         public string PrimaryType { get; private set; }
         public string SubType { get; private set; }
         public IEnumerable<KeyValuePair<string, string>> Params { get { return this.@params; }}

tests/CsConneg.MediaRangeTests.cs

 
             foreach (var @case in cases)
             {
-                var parsed = MediaRange.Parse(@case.Input);
-                Assert.That(parsed, Is.EqualTo(@case.Expected));
+                {
+                    var parsed = MediaRange.Parse(@case.Input);
+                    Assert.That(parsed, Is.EqualTo(@case.Expected));
+                }
+
+                {
+                    MediaRange parsed;
+                    Assert.IsTrue(MediaRange.TryParse(@case.Input, out parsed));
+                    Assert.That(parsed, Is.EqualTo(@case.Expected));
+                }
             }
         }
 
+        [Test, ExpectedException(typeof(ArgumentNullException))]
+        public void Media_range_throws_on_parsing_null()
+        {
+            MediaRange.Parse(null);
+        }
+
+        [Test] public void Media_range_returns_false_on_tryparsing_null()
+        {
+            MediaRange mr;
+            Assert.IsFalse(MediaRange.TryParse(null, out mr));
+        }
+
         [Test] public void Media_range_formats_correctly()
         {
             var cases = new[]