/// <summary> /// Query the web service for the current IP Address /// </summary> /// <returns>An awaitable Task</returns> public async Task GetCurrentIPAddress() { using (var client = new HttpClient { BaseAddress = new Uri("https://api.ipify.org") }) { await client.GetAsync(string.Empty).ContinueWith( async responseTask => { if (responseTask.IsCompleted && responseTask.Result.IsSuccessStatusCode) { var address = await responseTask.Result.Content.ReadAsStringAsync().ConfigureAwait(false); var result = new IPAddressResult { IPAddress = address, Checked = DateTime.Now, Changed = this.History.LastOrDefault()?.IPAddress != address }; this.history.Add(result); } }).ConfigureAwait(false); } }
/// <summary> /// Parse a string as a new <see cref="IPAddressResult"/> /// </summary> /// <param name="value">The string to be parsed</param> /// <returns>A formatted <see cref="IPAddressResult"/> object</returns> /// <exception cref="ArgumentNullException">Thrown if the supplied value is null or empty</exception> /// <exception cref="FormatException">Thrown if any of the elements within the value are invalid</exception> public static IPAddressResult Parse(string value) { if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException(nameof(value), $"A value must be provided for {nameof(value)}"); } string[] parts = value.Split(new[] { " | " }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 3) { throw new FormatException($"The supplied value ('{value}') is not in the expected format"); } string address = parts[0].Trim(); Regex addressChecker = new Regex(@"((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}"); if (!addressChecker.IsMatch(address)) { throw new FormatException("The 'IP Address' element is not a valid IP v4 address"); } DateTime date; if (parts[1].Length != 14 || !DateTime.TryParse(parts[1], out date)) { throw new FormatException("The 'Date Checked' element is not a valid DateTime value"); } bool changed; if (parts[2].Length > 5 || parts[2].Length < 4 || !bool.TryParse(parts[2], out changed)) { throw new FormatException("The 'Changed' element is not a valid value"); } var result = new IPAddressResult { IPAddress = address, Checked = date, Changed = changed }; return result; }
/// <summary> /// Attempt to parse a string as a new <see cref="IPAddressResult"/> /// </summary> /// <param name="value">The string to be parsed</param> /// <param name="result">An <see cref="IPAddressResult"/> object to be populated</param> /// <returns><c>True</c> if the string was parsed successfully; <c>False</c> if not</returns> public static bool TryParse(string value, out IPAddressResult result) { try { result = Parse(value); return true; } catch { result = null; return false; } }