response validation; GetMonitors works now

This commit is contained in:
2014-02-01 12:21:06 +01:00
parent db71e456d9
commit adcf01da3d
11 changed files with 70 additions and 67 deletions
+2 -9
View File
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UptimeSharp.Models;
using Xunit;
@@ -75,15 +76,7 @@ namespace UptimeSharp.Tests
//));
List<Monitor> items = await client.GetMonitors();
Monitor monitor = null;
items.ForEach(item =>
{
if (item.Name == "test_5")
{
monitor = item;
}
});
Monitor monitor = items.SingleOrDefault(item => item.Name == "test_5");
Assert.True(
monitor != null
+2 -2
View File
@@ -65,7 +65,7 @@ namespace UptimeSharp
{ "alertContactValue", value }
});
return response.Status;
return response.Success;
}
@@ -102,7 +102,7 @@ namespace UptimeSharp
{ "alertContactID", alertID }
});
return response.Status;
return response.Success;
}
+4 -4
View File
@@ -41,7 +41,7 @@ namespace UptimeSharp
RetrieveResponse response = await Request<RetrieveResponse>("getMonitors", cancellationToken, parameters.Convert());
return response.Items;
return response.Items ?? new List<Models.Monitor>();
}
@@ -85,7 +85,7 @@ namespace UptimeSharp
{ "monitorID", monitorId.ToString() }
});
return response.Status;
return response.Success;
}
@@ -149,7 +149,7 @@ namespace UptimeSharp
};
DefaultResponse response = await Request<DefaultResponse>("newMonitor", cancellationToken, parameters.Convert());
return response.Status;
return response.Success;
}
@@ -195,7 +195,7 @@ namespace UptimeSharp
paramList.Add("monitorID", monitor.ID.ToString());
DefaultResponse response = await Request<DefaultResponse>("editMonitor", cancellationToken, paramList);
return response.Status;
return response.Success;
}
}
}
+1 -1
View File
@@ -7,7 +7,7 @@ namespace UptimeSharp.Models
/// Alert Response
/// </summary>
[JsonObject]
internal class AlertResponse : ResponseBase
internal class AlertResponse : Response
{
/// <summary>
/// Gets or sets the item dictionary.
@@ -6,5 +6,5 @@ namespace UptimeSharp.Models
/// Default Response
/// </summary>
[JsonObject]
internal class DefaultResponse : ResponseBase {}
internal class DefaultResponse : Response { }
}
+10
View File
@@ -0,0 +1,10 @@
namespace UptimeSharp.Models
{
internal interface IResponse
{
string ErrorCode { get; set; }
string ErrorMessage { get; set; }
string RawStatus { get; set; }
bool Success { get; }
}
}
@@ -6,7 +6,7 @@ namespace UptimeSharp.Models
/// Base for Responses
/// </summary>
[JsonObject]
internal class ResponseBase
internal class Response : IResponse
{
/// <summary>
@@ -28,7 +28,7 @@ namespace UptimeSharp.Models
public string ErrorMessage { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="ResponseBase"/> is status.
/// Gets or sets a value indicating whether this <see cref="Response"/> is status.
/// </summary>
/// <value>
/// "ok" or "fail"
@@ -37,13 +37,13 @@ namespace UptimeSharp.Models
public string RawStatus { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="ResponseBase"/> is status.
/// Gets or sets a value indicating whether this <see cref="Response"/> is success.
/// </summary>
/// <value>
/// <c>true</c> if status is OK; otherwise, <c>false</c>.
/// </value>
[JsonIgnore]
public bool Status
public bool Success
{
get { return RawStatus == "ok"; }
}
@@ -1,5 +1,5 @@
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace UptimeSharp.Models
{
@@ -7,7 +7,7 @@ namespace UptimeSharp.Models
/// Monitor Response
/// </summary>
[JsonObject]
internal class RetrieveResponse : ResponseBase
internal class RetrieveResponse : Response
{
/// <summary>
/// Gets or sets the item dictionary.
@@ -30,7 +30,7 @@ namespace UptimeSharp.Models
{
get
{
return ItemDictionary != null ? ItemDictionary["monitor"] : null;
return ItemDictionary != null ? ItemDictionary["monitor"] : null;
}
}
}
+39 -36
View File
@@ -8,6 +8,7 @@ using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using UptimeSharp.Models;
namespace UptimeSharp
{
@@ -54,6 +55,12 @@ namespace UptimeSharp
public Action<string> PreRequest { get; set; }
/// <summary>
/// The fail codes that don't raise exceptions
/// </summary>
private static readonly string[] successFailCodes = new string[] { "212", "221" };
/// <summary>
/// Initializes a new instance of the <see cref="UptimeClient"/> class.
/// </summary>
@@ -133,8 +140,11 @@ namespace UptimeSharp
throw new UptimeSharpException(exc.Message, exc);
}
// validate HTTP response
ValidateResponse(response);
// HTTP error
if (!response.IsSuccessStatusCode)
{
throw new UptimeSharpException("Request Exception: {0} (Code: {1})", response.ReasonPhrase, response.StatusCode.ToString());
}
// cache headers
lastHeaders = response.Headers;
@@ -145,8 +155,6 @@ namespace UptimeSharp
// cache response
lastResponseData = responseString;
responseString = responseString.Replace("[]", "{}");
// deserialize object
T parsedResponse = JsonConvert.DeserializeObject<T>(
responseString,
@@ -154,7 +162,7 @@ namespace UptimeSharp
{
Error = (object sender, ErrorEventArgs args) =>
{
throw new UptimeSharpException(String.Format("Parse error: {0}", args.ErrorContext.Error.Message));
throw new UptimeSharpException(String.Format("Parse Exception: {0}", args.ErrorContext.Error.Message));
},
Converters =
{
@@ -165,6 +173,9 @@ namespace UptimeSharp
}
);
// validate response
ValidateResponse(parsedResponse as IResponse);
return parsedResponse;
}
@@ -177,46 +188,38 @@ namespace UptimeSharp
/// <exception cref="UptimeSharpException">
/// Error retrieving response
/// </exception>
protected void ValidateResponse(HttpResponseMessage response)
internal void ValidateResponse(IResponse response)
{
// no error found
if (response.StatusCode == HttpStatusCode.OK)
// it's a success ;-)
if (response.Success)
{
return;
}
//string exceptionString = response.ReasonPhrase;
//bool isPocketError = response.Headers.Contains("X-Error");
// don't raise exceptions for minor error codes
if (successFailCodes.Contains(response.ErrorCode))
{
return;
}
//// fetch custom pocket headers
//string error = TryGetHeaderValue(response.Headers, "X-Error");
//int errorCode = Convert.ToInt32(TryGetHeaderValue(response.Headers, "X-Error-Code"));
// create exception
UptimeSharpException exception = new UptimeSharpException(
"UptimeRobot Exception: {0} (Code: {1})\n{2}",
null,
response.ErrorMessage,
response.ErrorCode,
"http://uptimerobot.com/api.asp#errorMessages"
);
//// create exception strings
//if (isPocketError)
//{
// exceptionString = String.Format("Pocket error: {0} ({1}) ", error, errorCode);
//}
//else
//{
// exceptionString = String.Format("Request error: {0} ({1})", response.ReasonPhrase, (int)response.StatusCode);
//}
// add custom fields
exception.Error = response.ErrorMessage;
exception.ErrorCode = response.ErrorCode;
//// create exception
//PocketException exception = new PocketException(exceptionString);
// add to generic exception data
exception.Data.Add("Error", response.ErrorMessage);
exception.Data.Add("ErrorCode", response.ErrorCode);
//if (isPocketError)
//{
// // add custom pocket fields
// exception.PocketError = error;
// exception.PocketErrorCode = errorCode;
// // add to generic exception data
// exception.Data.Add("X-Error", error);
// exception.Data.Add("X-Error-Code", errorCode);
//}
//throw exception;
throw exception;
}
}
}
+2 -1
View File
@@ -50,7 +50,8 @@
<Compile Include="Models\Parameters\RetrieveParameters.cs" />
<Compile Include="Models\Response\AlertResponse.cs" />
<Compile Include="Models\Response\DefaultResponse.cs" />
<Compile Include="Models\Response\ResponseBase.cs" />
<Compile Include="Models\Response\IResponse.cs" />
<Compile Include="Models\Response\Response.cs" />
<Compile Include="Models\Response\RetrieveResponse.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="UptimeClient.cs" />
@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
namespace UptimeSharp
{
@@ -17,7 +13,7 @@ namespace UptimeSharp
/// <value>
/// The pocket error code.
/// </value>
public int? ErrorCode { get; set; }
public string ErrorCode { get; set; }
/// <summary>
/// Gets or sets the UptimeRobot error.