move old lib; create new PCL with utilities

This commit is contained in:
2013-10-28 21:05:10 +01:00
parent de81634646
commit 3e6d93d495
27 changed files with 628 additions and 260 deletions
@@ -0,0 +1,93 @@
using RestSharp;
using System;
using System.Collections.Generic;
using UptimeSharp.Models;
namespace UptimeSharp
{
/// <summary>
/// UptimeClient
/// </summary>
public partial class UptimeClient
{
/// <summary>
/// Retrieves alerts from UptimeRobot
/// </summary>
/// <param name="alertIDs">Retrieve specified alert contacts by supplying IDs for them.</param>
/// <returns></returns>
public List<Alert> GetAlerts(string[] alertIDs = null)
{
Parameter alerts = Parameter("alertcontacts", alertIDs != null ? string.Join("-", alertIDs) : null);
return Get<AlertResponse>("getAlertContacts", alerts).Items;
}
/// <summary>
/// Retrieves an alert from UptimeRobot
/// </summary>
/// <param name="alertID">The alertID.</param>
/// <returns></returns>
public Alert GetAlert(string alertID)
{
List<Alert> alerts = GetAlerts(new string[] { alertID });
return alerts.ToArray().Length > 0 ? alerts[0] : null;
}
/// <summary>
/// Adds an alert.
/// mobile/SMS alert contacts are not supported yet, see: http://www.uptimerobot.com/api.asp#methods
/// </summary>
/// <param name="type">The type.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public bool AddAlert(AlertType type, string value)
{
if (type == AlertType.SMS || type == AlertType.Twitter)
{
throw new UptimeSharpException("AlertType.SMS and AlertType.Twitter are not supported by the UptimeRobot API");
}
return Get<DefaultResponse>("newAlertContact",
Parameter("alertContactType", (int)type),
Parameter("alertContactValue", value)
).Status;
}
/// <summary>
/// Adds an alert.
/// mobile/SMS alert contacts are not supported yet, see: http://www.uptimerobot.com/api.asp#methods
/// </summary>
/// <param name="alert">The alert.</param>
/// <returns></returns>
public bool AddAlert(Alert alert)
{
return AddAlert(alert.Type, alert.Value);
}
/// <summary>
/// Removes an alert.
/// </summary>
/// <param name="alertID">The alert ID.</param>
/// <returns></returns>
public bool DeleteAlert(string alertID)
{
return Get<DefaultResponse>("deleteAlertContact", Parameter("alertContactID", alertID)).Status;
}
/// <summary>
/// Removes an alert.
/// </summary>
/// <param name="alert">The alert.</param>
/// <returns></returns>
public bool DeleteAlert(Alert alert)
{
return DeleteAlert(alert.ID);
}
}
}
@@ -0,0 +1,162 @@
using RestSharp;
using System.Collections.Generic;
using UptimeSharp.Models;
namespace UptimeSharp
{
/// <summary>
/// UptimeClient
/// </summary>
public partial class UptimeClient
{
/// <summary>
/// Retrieves specified monitors from UptimeRobot
/// </summary>
/// <param name="monitors">monitor list</param>
/// <param name="customUptimeRatio">The custom uptime ratio.</param>
/// <param name="showLog">if set to <c>true</c> [show log].</param>
/// <param name="showAlerts">if set to <c>true</c> [show alerts].</param>
/// <returns>
/// Monitor List
/// </returns>
public List<Monitor> GetMonitors(int[] monitorIDs = null, float[] customUptimeRatio = null, bool showLog = false, bool showAlerts = true)
{
RetrieveParameters parameters = new RetrieveParameters()
{
Monitors = monitorIDs,
CustomUptimeRatio = customUptimeRatio,
ShowAlerts = showAlerts,
ShowLog = showLog
};
return Get<RetrieveResponse>("getMonitors", parameters.Convert()).Items;
}
/// <summary>
/// Retrieves a monitor from UptimeRobot
/// </summary>
/// <param name="monitorId">a specific monitor ID</param>
/// <param name="customUptimeRatio">The custom uptime ratio.</param>
/// <param name="showLog">if set to <c>true</c> [show log].</param>
/// <param name="showAlerts">if set to <c>true</c> [show alerts].</param>
/// <returns>
/// The Monitor
/// </returns>
public Monitor GetMonitor(int monitorId, float[] customUptimeRatio = null, bool showLog = false, bool showAlerts = true)
{
List<Monitor> monitors = GetMonitors(new int[] { monitorId }, customUptimeRatio, showLog, showAlerts);
return monitors.ToArray().Length > 0 ? monitors[0] : null;
}
/// <summary>
/// Deletes a monitor
/// </summary>
/// <param name="monitorId">a specific monitor ID</param>
/// <returns>
/// Success state
/// </returns>
public bool DeleteMonitor(int monitorId)
{
return Get<DefaultResponse>("deleteMonitor", Parameter("monitorID", monitorId)).Status;
}
/// <summary>
/// Deletes a monitor
/// </summary>
/// <param name="monitor">The monitor.</param>
/// <returns>
/// Success state
/// </returns>
public bool DeleteMonitor(Monitor monitor)
{
return DeleteMonitor(monitor.ID);
}
/// <summary>
/// Creates a monitor.
/// </summary>
/// <param name="name">The name of the new monitor.</param>
/// <param name="uri">The URI or IP to watch.</param>
/// <param name="type">The type of the monitor.</param>
/// <param name="subtype">The subtype of the monitor (if port).</param>
/// <param name="port">The port (only for Subtype.Custom).</param>
/// <param name="keywordValue">The keyword value.</param>
/// <param name="keywordType">Type of the keyword.</param>
/// <param name="alerts">An ID list of existing alerts to notify.</param>
/// <param name="HTTPUsername">The HTTP username.</param>
/// <param name="HTTPPassword">The HTTP password.</param>
/// <returns>
/// Success state
/// </returns>
public bool AddMonitor(string name, string uri, Type type = Type.HTTP, Subtype subtype = Subtype.Unknown,
int? port = null, string keywordValue = null, KeywordType keywordType = KeywordType.Unknown,
string[] alerts = null, string HTTPUsername = null, string HTTPPassword = null)
{
MonitorParameters parameters = new MonitorParameters()
{
Name = name,
Uri = uri,
Type = type,
Subtype = subtype,
Port = port,
KeywordType = keywordType,
KeywordValue = keywordValue,
Alerts = alerts,
HTTPPassword = HTTPPassword,
HTTPUsername = HTTPUsername
};
return Get<DefaultResponse>("newMonitor", parameters.Convert()).Status;
}
/// <summary>
/// Edits a monitor.
/// </summary>
/// <param name="monitor">The monitor.</param>
/// <returns>
/// Success state
/// </returns>
public bool ModifyMonitor(Monitor monitor)
{
List<string> alerts = null;
if (monitor.Alerts != null)
{
monitor.Alerts.ForEach(item => alerts.Add(item.ID));
}
MonitorParameters parameters = new MonitorParameters()
{
Name = monitor.Name,
Uri = monitor.UriString != null ? monitor.UriString : null,
Port = monitor.Port,
HTTPPassword = monitor.HTTPPassword,
HTTPUsername = monitor.HTTPUsername,
KeywordType = monitor.KeywordType,
KeywordValue = monitor.KeywordValue,
Subtype = monitor.Subtype,
Alerts = alerts != null ? alerts.ToArray() : null
};
List<Parameter> paramList = parameters.Convert();
// fix bad behaviour in API if no subtype is submitted
if(parameters.Subtype == Subtype.Unknown)
{
paramList.Add(Parameter("monitorSubType", 0));
}
paramList.Add(Parameter("monitorID", monitor.ID));
return Get<DefaultResponse>("editMonitor", paramList).Status;
}
}
}
@@ -0,0 +1,85 @@
using RestSharp;
using RestSharp.Deserializers;
using ServiceStack.Text;
using System;
using System.Net;
namespace UptimeSharp
{
/// <summary>
/// Custom JSON Deserializer which implements ServiceStack.Text
/// </summary>
internal class JsonDeserializer : IDeserializer
{
public const string JsonContentType = "application/json";
/// <summary>
/// Deserializes the specified response.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="response">The response.</param>
/// <returns></returns>
public T Deserialize<T>(IRestResponse response)
{
return JsonSerializer.DeserializeFromString<T>(response.Content);
}
/// <summary>
/// Adds custom deserialization for specific types.
/// </summary>
public static void AddCustomDeserialization()
{
// generate correct Uri format
JsConfig<Uri>.DeSerializeFn = value =>
{
Uri uri;
try
{
uri = new Uri(value);
}
catch
{
uri = null;
}
return uri;
};
}
/// <summary>
/// Gets or sets the date format.
/// </summary>
/// <value>
/// The date format.
/// </value>
public string DateFormat { get; set; }
/// <summary>
/// Gets or sets the namespace.
/// </summary>
/// <value>
/// The namespace.
/// </value>
public string Namespace { get; set; }
/// <summary>
/// Gets or sets the root element.
/// </summary>
/// <value>
/// The root element.
/// </value>
public string RootElement { get; set; }
/// <summary>
/// Gets the type of the content.
/// </summary>
/// <value>
/// The type of the content.
/// </value>
public string ContentType
{
get { return JsonContentType; }
}
}
}
+96
View File
@@ -0,0 +1,96 @@
using System.Runtime.Serialization;
namespace UptimeSharp.Models
{
/// <summary>
/// The Alert Model
/// </summary>
[DataContract]
public class Alert
{
/// <summary>
/// Gets or sets the ID.
/// </summary>
/// <value>
/// The ID.
/// </value>
[DataMember(Name = "id")]
public string ID { get; set; }
/// <summary>
/// Gets or sets the alert type.
/// </summary>
/// <value>
/// The name.
/// </value>
[DataMember(Name = "type")]
public AlertType Type { get; set; }
/// <summary>
/// Gets or sets the alert status.
/// </summary>
/// <value>
/// The status.
/// </value>
[DataMember(Name = "status")]
public AlertStatus Status { get; set; }
/// <summary>
/// Gets or sets the alert value.
/// </summary>
/// <value>
/// The value - Phone Number / E-Mail / Account
/// </value>
[DataMember(Name = "value")]
public string Value { get; set; }
}
/// <summary>
/// The type of the alert contact notified.
/// </summary>
public enum AlertType
{
/// <summary>
/// SMS
/// </summary>
SMS = 1,
/// <summary>
/// E-Mail
/// </summary>
Email = 2,
/// <summary>
/// Twitter DM
/// </summary>
Twitter = 3,
/// <summary>
/// Boxcar
/// </summary>
Boxcar = 4
}
/// <summary>
/// The status of the alert contact.
/// </summary>
public enum AlertStatus
{
/// <summary>
/// Unknown
/// </summary>
Unknown,
/// <summary>
/// Not activated
/// </summary>
NotActicated = 0,
/// <summary>
/// Paused
/// </summary>
Paused = 1,
/// <summary>
/// Active
/// </summary>
Active = 2
}
}
+65
View File
@@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace UptimeSharp.Models
{
/// <summary>
/// The Log Model
/// </summary>
[DataContract]
public class Log
{
/// <summary>
/// Gets or sets the log type.
/// </summary>
/// <value>
/// The type.
/// </value>
[DataMember(Name = "type")]
public LogType Type { get; set; }
/// <summary>
/// Gets or sets the date time, when the log action appeared.
/// </summary>
/// <value>
/// The date.
/// </value>
[DataMember(Name = "datetime")]
public DateTime Date { get; set; }
/// <summary>
/// Gets or sets the alerts, which were notified when the log action appeared.
/// </summary>
/// <value>
/// The alert contacts.
/// </value>
[DataMember(Name = "alertcontact")]
public List<Alert> Alerts { get; set; }
}
/// <summary>
/// The type of the log entry.
/// </summary>
public enum LogType
{
/// <summary>
/// Down
/// </summary>
Down = 1,
/// <summary>
/// Up
/// </summary>
Up = 2,
/// <summary>
/// Started
/// </summary>
Started = 98,
/// <summary>
/// Paused
/// </summary>
Paused = 99
}
}
+288
View File
@@ -0,0 +1,288 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Net;
using ServiceStack.Text;
using RestSharp;
namespace UptimeSharp.Models
{
/// <summary>
/// The Monitor Model implementation
/// </summary>
[DataContract]
public class Monitor
{
/// <summary>
/// Gets or sets the ID.
/// </summary>
/// <value>
/// The ID.
/// </value>
[DataMember(Name = "id")]
public int ID { get; set; }
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>
/// The name.
/// </value>
[DataMember(Name = "friendlyname")]
public string Name { get; set; }
/// <summary>
/// Gets or sets the URI.
/// </summary>
/// <value>
/// The URI.
/// </value>
[DataMember(Name = "url")]
public string UriString { get; set; }
/// <summary>
/// Gets the URI.
/// </summary>
/// <value>
/// The URI.
/// </value>
[IgnoreDataMember]
public Uri Uri
{
get
{
Uri uri;
try
{
uri = new Uri(UriString);
}
catch
{
uri = null;
}
return uri;
}
}
/// <summary>
/// Gets or sets the port.
/// Only for port monitoring.
/// </summary>
/// <value>
/// The port.
/// </value>
[DataMember(Name = "port")]
public int? Port { get; set; }
/// <summary>
/// Gets or sets the uptime.
/// </summary>
/// <value>
/// Uptime ratio of the monitor calculated since the monitor is created.
/// </value>
[DataMember(Name = "alltimeuptimeratio")]
public float Uptime { get; set; }
/// <summary>
/// Gets or sets the uptime custom.
/// </summary>
/// <value>
/// The uptime ratio of the monitor for the given periods
/// </value>
[DataMember(Name = "customuptimeratio")]
public float? UptimeCustom { get; set; }
/// <summary>
/// Gets or sets the HTTP password.
/// </summary>
/// <value>
/// The HTTP password.
/// </value>
[DataMember(Name = "httppassword")]
public string HTTPPassword { get; set; }
/// <summary>
/// Gets or sets the HTTP username.
/// </summary>
/// <value>
/// The HTTP username.
/// </value>
[DataMember(Name = "httpusername")]
public string HTTPUsername { get; set; }
/// <summary>
/// Gets or sets the type of the keyword.
/// </summary>
/// <value>
/// The type of the keyword.
/// </value>
[DataMember(Name = "keywordtype")]
public KeywordType KeywordType { get; set; }
/// <summary>
/// Gets or sets the keyword value.
/// </summary>
/// <value>
/// The keyword value.
/// </value>
[DataMember(Name = "keywordvalue")]
public string KeywordValue { get; set; }
/// <summary>
/// Gets or sets the status.
/// </summary>
/// <value>
/// The status.
/// </value>
[DataMember(Name = "status")]
public Status Status { get; set; }
/// <summary>
/// Gets or sets the type.
/// </summary>
/// <value>
/// The type.
/// </value>
[DataMember(Name = "type")]
public Type Type { get; set; }
/// <summary>
/// Gets or sets the subtype.
/// </summary>
/// <value>
/// The subtype.
/// </value>
[DataMember(Name = "subtype")]
public Subtype Subtype { get; set; }
/// <summary>
/// Gets or sets the alerts.
/// </summary>
/// <value>
/// The alert contacts.
/// </value>
[DataMember(Name = "alertcontact")]
public List<Alert> Alerts { get; set; }
/// <summary>
/// Gets or sets the log.
/// </summary>
/// <value>
/// The log with dates and associated alert contacts.
/// </value>
[DataMember(Name = "log")]
public List<Log> Log { get; set; }
}
/// <summary>
/// The status of the monitor
/// </summary>
public enum Status
{
/// <summary>
/// Paused
/// </summary>
Pause = 0,
/// <summary>
/// Not checked yet
/// </summary>
NotChecked = 1,
/// <summary>
/// Up
/// </summary>
Up = 2,
/// <summary>
/// Seems down
/// </summary>
SeemsDown = 8,
/// <summary>
/// Down
/// </summary>
Down = 9
}
/// <summary>
/// The type of the monitor
/// </summary>
public enum Type
{
/// <summary>
/// HTTP
/// </summary>
HTTP = 1,
/// <summary>
/// Keyword
/// </summary>
Keyword = 2,
/// <summary>
/// Ping
/// </summary>
Ping = 3,
/// <summary>
/// Port
/// </summary>
Port = 4
}
/// <summary>
/// Shows which pre-defined port/service is monitored or if a custom port is monitored.
/// </summary>
public enum Subtype
{
/// <summary>
/// Unknown
/// </summary>
Unknown,
/// <summary>
/// HTTP
/// </summary>
HTTP = 1,
/// <summary>
/// HTTPS
/// </summary>
HTTPS = 2,
/// <summary>
/// FTP
/// </summary>
FTP = 3,
/// <summary>
/// SMTP
/// </summary>
SMTP = 4,
/// <summary>
/// POP3
/// </summary>
POP3 = 5,
/// <summary>
/// IMAP
/// </summary>
IMAP = 6,
/// <summary>
/// Custom Port
/// </summary>
Custom = 99
}
/// <summary>
/// Shows if the monitor will be flagged as down when the keyword exists or not exists
/// </summary>
public enum KeywordType
{
/// <summary>
/// Unknown
/// </summary>
Unknown,
/// <summary>
/// Exists
/// </summary>
Exists = 1,
/// <summary>
/// Exists not
/// </summary>
NotExists = 2
}
}
@@ -0,0 +1,141 @@
using RestSharp;
using System;
using System.Collections.Generic;
namespace UptimeSharp.Models
{
/// <summary>
/// All parameters which can be passed for monitor modifications
/// </summary>
internal class MonitorParameters
{
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>
/// The name.
/// </value>
public string Name { get; set; }
/// <summary>
/// Gets or sets the URI.
/// </summary>
/// <value>
/// The URI.
/// </value>
public string Uri { get; set; }
/// <summary>
/// Gets or sets the port.
/// Only for port monitoring.
/// </summary>
/// <value>
/// The port.
/// </value>
public int? Port { get; set; }
/// <summary>
/// Gets or sets the HTTP password.
/// </summary>
/// <value>
/// The HTTP password.
/// </value>
public string HTTPPassword { get; set; }
/// <summary>
/// Gets or sets the HTTP username.
/// </summary>
/// <value>
/// The HTTP username.
/// </value>
public string HTTPUsername { get; set; }
/// <summary>
/// Gets or sets the type of the keyword.
/// </summary>
/// <value>
/// The type of the keyword.
/// </value>
public KeywordType KeywordType { get; set; }
/// <summary>
/// Gets or sets the keyword value.
/// </summary>
/// <value>
/// The keyword value.
/// </value>
public string KeywordValue { get; set; }
/// <summary>
/// Gets or sets the type.
/// </summary>
/// <value>
/// The type.
/// </value>
public Type Type { get; set; }
/// <summary>
/// Gets or sets the subtype.
/// </summary>
/// <value>
/// The subtype.
/// </value>
public Subtype Subtype { get; set; }
/// <summary>
/// Gets or sets the alerts.
/// </summary>
/// <value>
/// The alert contacts.
/// </value>
public string[] Alerts { get; set; }
/// <summary>
/// Converts this instance to a parameter list.
/// </summary>
/// <returns>Parameter list</returns>
public List<Parameter> Convert()
{
List<Parameter> parameters = new List<Parameter>();
parameters.Add(UptimeClient.Parameter("monitorFriendlyName", Name));
parameters.Add(UptimeClient.Parameter("monitorURL", Uri));
if ((int)Type != 0)
{
parameters.Add(UptimeClient.Parameter("monitorType", (int)Type));
}
// special params for port listener
if (Type == Type.Port && Subtype != Subtype.Unknown)
{
parameters.Add(UptimeClient.Parameter("monitorSubType", (int)Subtype));
if (Subtype == Subtype.Custom && Port.HasValue)
{
parameters.Add(UptimeClient.Parameter("monitorPort", Port));
}
}
// keyword listener
if (Type == Type.Keyword && !string.IsNullOrEmpty(KeywordValue))
{
parameters.Add(UptimeClient.Parameter("monitorKeywordType", (int)KeywordType));
parameters.Add(UptimeClient.Parameter("monitorKeywordValue", KeywordValue));
}
// HTTP basic auth credentials
parameters.Add(UptimeClient.Parameter("monitorHTTPUsername", HTTPUsername));
parameters.Add(UptimeClient.Parameter("monitorHTTPPassword", HTTPPassword));
// alert notifications
if (Alerts != null && Alerts.Length > 0)
{
parameters.Add(UptimeClient.Parameter("monitorAlertContacts", string.Join("-", Alerts)));
}
return parameters;
}
}
}
@@ -0,0 +1,75 @@
using RestSharp;
using System;
using System.Collections.Generic;
namespace UptimeSharp.Models
{
/// <summary>
/// All parameters which can be passed for monitor retrieval
/// </summary>
internal class RetrieveParameters
{
/// <summary>
/// List of monitor ids
/// </summary>
/// <value>
/// The monitors.
/// </value>
public int[] Monitors { get; set; }
/// <summary>
/// Defines the number of days to calculate the uptime ratio
/// </summary>
/// <value>
/// The custom uptime ratio.
/// </value>
public float[] CustomUptimeRatio { get; set; }
/// <summary>
/// Defines if the logs of each monitor will be returned
/// </summary>
/// <value>
/// The log bool.
/// </value>
public bool? ShowLog { get; set; }
/// <summary>
/// Defines if the alert contacts set for the monitor to be returned
/// </summary>
/// <value>
/// The alert contacts bool.
/// </value>
public bool? ShowAlerts { get; set; }
/// <summary>
/// Converts this instance to a parameter list.
/// </summary>
/// <returns>Parameter list</returns>
public List<Parameter> Convert()
{
List<Parameter> parameters = new List<Parameter>();
if (Monitors != null && Monitors.Length > 0)
{
parameters.Add(UptimeClient.Parameter("monitors", String.Join("-", Monitors)));
}
if (CustomUptimeRatio != null && CustomUptimeRatio.Length > 0)
{
parameters.Add(UptimeClient.Parameter("customUptimeRatio", String.Join("-", CustomUptimeRatio)));
}
parameters.Add(UptimeClient.Parameter("showMonitorAlertContacts", (bool)ShowAlerts ? "1" : "0"));
if (ShowLog.HasValue)
{
string showLog = (bool)ShowLog ? "1" : "0";
parameters.Add(UptimeClient.Parameter("logs", showLog));
parameters.Add(UptimeClient.Parameter("alertContacts", showLog));
parameters.Add(UptimeClient.Parameter("showTimezone", showLog));
}
return parameters;
}
}
}
@@ -0,0 +1,37 @@
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace UptimeSharp.Models
{
/// <summary>
/// Alert Response
/// </summary>
[DataContract]
internal class AlertResponse : ResponseBase
{
/// <summary>
/// Gets or sets the item dictionary.
/// The list is 2 layers deep, so this one is necessary :-/
/// </summary>
/// <value>
/// The item dictionary.
/// </value>
[DataMember(Name = "alertcontacts")]
public Dictionary<string, List<Alert>> ItemDictionary { get; set; }
/// <summary>
/// Gets the items.
/// </summary>
/// <value>
/// The items.
/// </value>
[IgnoreDataMember]
public List<Alert> Items
{
get
{
return ItemDictionary["alertcontact"];
}
}
}
}
@@ -0,0 +1,11 @@
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace UptimeSharp.Models
{
/// <summary>
/// Default Response
/// </summary>
[DataContract]
internal class DefaultResponse : ResponseBase {}
}
@@ -0,0 +1,54 @@
using System.Runtime.Serialization;
namespace UptimeSharp.Models
{
/// <summary>
/// Base for Responses
/// </summary>
[DataContract]
internal class ResponseBase
{
/// <summary>
/// Gets or sets the error code.
/// </summary>
/// <value>
/// The error code.
/// </value>
[DataMember(Name = "id")]
public string ErrorCode { get; set; }
/// <summary>
/// Gets or sets the error message.
/// </summary>
/// <value>
/// The error message.
/// </value>
[DataMember(Name = "message")]
public string ErrorMessage { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="ResponseBase"/> is status.
/// </summary>
/// <value>
/// "ok" or "fail"
/// </value>
[DataMember(Name = "stat")]
public string RawStatus { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="ResponseBase"/> is status.
/// </summary>
/// <value>
/// <c>true</c> if status is OK; otherwise, <c>false</c>.
/// </value>
[IgnoreDataMember]
public bool Status
{
get
{
return RawStatus == "ok";
}
}
}
}
@@ -0,0 +1,37 @@
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace UptimeSharp.Models
{
/// <summary>
/// Monitor Response
/// </summary>
[DataContract]
internal class RetrieveResponse : ResponseBase
{
/// <summary>
/// Gets or sets the item dictionary.
/// The list is 2 layers deep, so this one is necessary :-/
/// </summary>
/// <value>
/// The item dictionary.
/// </value>
[DataMember(Name = "monitors")]
public Dictionary<string, List<Monitor>> ItemDictionary { get; set; }
/// <summary>
/// Gets the items.
/// </summary>
/// <value>
/// The items.
/// </value>
[IgnoreDataMember]
public List<Monitor> Items
{
get
{
return ItemDictionary != null ? ItemDictionary["monitor"] : null;
}
}
}
}
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("UptimeSharp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("cee")]
[assembly: AssemblyProduct("UptimeSharp")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fe70c634-cebd-44b0-8287-1d75385058cf")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
+211
View File
@@ -0,0 +1,211 @@
using RestSharp;
using System;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
namespace UptimeSharp
{
/// <summary>
/// UptimeClient
/// </summary>
public partial class UptimeClient
{
/// <summary>
/// REST client used for the API communication
/// </summary>
protected readonly RestClient _restClient;
/// <summary>
/// The base URL for the UptimeRobot API
/// </summary>
protected static Uri baseUri = new Uri("http://api.uptimerobot.com/");
/// <summary>
/// Accessor for the UptimeRebot API key
/// see: http://http://www.uptimerobot.com/api.asp
/// </summary>
public string ApiKey { get; set; }
/// <summary>
/// Returns all associated data from the last request
/// </summary>
public IRestResponse LastRequestData { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="UptimeClient"/> class.
/// </summary>
/// <param name="apiKey">The API key</param>
public UptimeClient(string apiKey)
{
// assign public properties
ApiKey = apiKey;
// initialize REST client
_restClient = new RestClient(baseUri.ToString());
// add default parameters to each request
_restClient.AddDefaultParameter("apiKey", ApiKey);
// defines the response format (according to the UptimeRobot docs)
_restClient.AddDefaultParameter("format", "json");
// UptimeRobot returns by default JSON-P when json-formatting is set
// with this param it can return raw JSON
_restClient.AddDefaultParameter("noJsonCallback", "1");
// custom JSON deserializer (ServiceStack.Text)
_restClient.AddHandler("application/json", new JsonDeserializer());
// add custom deserialization lambdas
JsonDeserializer.AddCustomDeserialization();
}
/// <summary>
/// Makes a typed HTTP REST request to the API
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="request">The request.</param>
/// <returns></returns>
protected T Request<T>(RestRequest request) where T : new()
{
// fix content type if wrong determined by RestSharp
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
IRestResponse<T> response = _restClient.Execute<T>(request);
LastRequestData = response;
ValidateResponse<T>(response);
return response.Data;
}
/// <summary>
/// Fetches a typed resource
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="resource">Requested resource</param>
/// <param name="parameters">Additional GET parameters</param>
/// <returns></returns>
protected T Get<T>(string resource, List<Parameter> parameters = null) where T : class, new()
{
// UptimeRobot uses GET for all of its endpoints
var request = new RestRequest(resource, Method.GET);
// enumeration for params
if (parameters != null)
{
parameters.ForEach(
param => {
if(param.Value != null)
{
request.AddParameter(param);
}
}
);
}
// do the request
return Request<T>(request);
}
/// <summary>
/// Fetches a typed resource
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="resource">Requested resource</param>
/// <param name="parameter">The parameters.</param>
/// <returns></returns>
protected T Get<T>(string resource, params Parameter[] parameters) where T : class, new()
{
List<Parameter> parameterList = new List<Parameter>();
parameterList.AddRange(parameters);
return Get<T>(resource, parameterList);
}
/// <summary>
/// Creates a RestSharp.Parameter instance.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
internal static Parameter Parameter(string name, object value)
{
return new Parameter()
{
Name = name,
Value = value,
Type = ParameterType.GetOrPost
};
}
/// <summary>
/// Validates the response.
/// </summary>
/// <param name="response">The response.</param>
/// <returns></returns>
/// <exception cref="UptimeSharpException">
/// Error retrieving response
/// </exception>
protected void ValidateResponse<T>(IRestResponse<T> response) where T : new()
{
Type responseType = response.Data.GetType();
// get status property from ResponseBase POCO
PropertyInfo statusProp = responseType.GetProperty("Status");
object status = statusProp.GetValue(response.Data, null);
// Error from UptimeSharp
if (status.Equals(false))
{
// get error properties from response
PropertyInfo errorProp = responseType.GetProperty("ErrorMessage");
object error = errorProp.GetValue(response.Data, null);
PropertyInfo errorCodeProp = responseType.GetProperty("ErrorCode");
object errorCode = errorCodeProp.GetValue(response.Data, null);
// create exception
UptimeSharpException exception = new UptimeSharpException(
"UptimeRobot Exception: {0} (Code: {1})\n{2}",
response.ErrorException,
error,
errorCode,
"http://uptimerobot.com/api.asp#errorMessages"
);
// add custom pocket fields
exception.Error = error.ToString();
exception.ErrorCode = Convert.ToInt32(errorCode);
// add to generic exception data
exception.Data.Add("Error", error);
exception.Data.Add("ErrorCode", errorCode);
throw exception;
}
// HTTP Request Error
else if (response.StatusCode != HttpStatusCode.OK)
{
throw new UptimeSharpException(
"Request Exception: {0} (Code: {1})",
response.ErrorException,
response.ErrorMessage,
response.StatusCode
);
}
// Exception by RestSharp
else if (response.ErrorException != null)
{
throw new UptimeSharpException("Error retrieving response", response.ErrorException);
}
}
}
}
@@ -0,0 +1,82 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{AF900ACF-DC2A-40AC-9614-B7C8C12E114C}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>UptimeSharp</RootNamespace>
<AssemblyName>UptimeSharp</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<StartupObject />
</PropertyGroup>
<ItemGroup>
<Reference Include="RestSharp">
<HintPath>..\packages\RestSharp.104.1\lib\net4\RestSharp.dll</HintPath>
</Reference>
<Reference Include="ServiceStack.Text">
<HintPath>..\packages\ServiceStack.Text.3.9.56\lib\net35\ServiceStack.Text.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="UptimeSharpException.cs" />
<Compile Include="Components\Alert.cs" />
<Compile Include="Components\Monitor.cs" />
<Compile Include="JsonDeserializer.cs" />
<Compile Include="Models\Alert.cs" />
<Compile Include="Models\Log.cs" />
<Compile Include="Models\Monitor.cs" />
<Compile Include="Models\Parameters\MonitorParameters.cs" />
<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\RetrieveResponse.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="UptimeClient.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
@@ -0,0 +1,79 @@
using System;
using System.Runtime.Serialization;
namespace UptimeSharp
{
/// <summary>
/// custom UptimeRobot API Exceptions
/// </summary>
public class UptimeSharpException : Exception
{
/// <summary>
/// Gets or sets the UptimeRobot error code.
/// </summary>
/// <value>
/// The pocket error code.
/// </value>
public int? ErrorCode { get; set; }
/// <summary>
/// Gets or sets the UptimeRobot error.
/// </summary>
/// <value>
/// The pocket error.
/// </value>
public string Error { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="UptimeSharpException"/> class.
/// </summary>
public UptimeSharpException()
: base() { }
/// <summary>
/// Initializes a new instance of the <see cref="UptimeSharpException"/> class.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public UptimeSharpException(string message)
: base(message) { }
/// <summary>
/// Initializes a new instance of the <see cref="UptimeSharpException" /> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="args">The arguments.</param>
public UptimeSharpException(string message, params object[] args)
: base(string.Format(message, args)) { }
/// <summary>
/// Initializes a new instance of the <see cref="UptimeSharpException"/> class.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param>
public UptimeSharpException(string message, Exception innerException)
: base(message, innerException) { }
/// <summary>
/// Initializes a new instance of the <see cref="UptimeSharpException"/> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="innerException">The inner exception.</param>
/// <param name="args">The arguments.</param>
public UptimeSharpException(string message, Exception innerException, params object[] args)
: base(string.Format(message, args), innerException) { }
/// <summary>
/// Initializes a new instance of the <see cref="UptimeSharpException"/> class.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
protected UptimeSharpException(SerializationInfo info, StreamingContext context)
: base(info, context) { }
}
}
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="RestSharp" version="104.1" targetFramework="net40" />
<package id="ServiceStack.Text" version="3.9.56" targetFramework="net40" />
</packages>