Compare commits
67 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a94448091f | |||
| b4ba06b969 | |||
| 20620cdb30 | |||
| 92d225f7af | |||
| ba0a62b1f6 | |||
| 5923e8ceaa | |||
| 1aa88d558d | |||
| 614c6a40f9 | |||
| 5d8fab4e7a | |||
| e4807bf764 | |||
| 47d7ecaa46 | |||
| 427e726eeb | |||
| e8d4705a38 | |||
| 9033d7a761 | |||
| dfa9373223 | |||
| 83e4cb5767 | |||
| effcbe1d94 | |||
| c8de45410e | |||
| b73a57c197 | |||
| e25d04e5d9 | |||
| 1b5b9bfcfd | |||
| f24cec3d1e | |||
| 76af40f35c | |||
| 320266ad22 | |||
| 651538980d | |||
| 056d43f4d6 | |||
| 1a66f6f760 | |||
| 4af8482717 | |||
| 42e5a9ef39 | |||
| 29ffceb920 | |||
| 2f9bda6c76 | |||
| 26a2a6edf5 | |||
| 29800942bb | |||
| 6f3700eecf | |||
| adcf01da3d | |||
| db71e456d9 | |||
| ba1feaa55d | |||
| 8363a78ef4 | |||
| 7c922fc53b | |||
| 6fb98a33ba | |||
| 913eaa6319 | |||
| aede734694 | |||
| e3bead82bb | |||
| a901e53972 | |||
| 9ecb00fceb | |||
| d14c43eadb | |||
| 498765d1b0 | |||
| 127da64ec5 | |||
| f14e60a36e | |||
| 9bbaafb528 | |||
| c1cb0cb505 | |||
| 3e6d93d495 | |||
| de81634646 | |||
| 5cc471cf3d | |||
| ca19648286 | |||
| 67f6996b94 | |||
| 60a4d6cdc7 | |||
| c00dd42d08 | |||
| 5a2b1ef153 | |||
| 2d39955208 | |||
| 04340667ab | |||
| 0edb565514 | |||
| 53d8a38f55 | |||
| 295867b84b | |||
| e4f6fe2928 | |||
| 6f29cadd26 | |||
| 4ce3e726c5 |
@@ -0,0 +1,23 @@
|
||||
# Auto detect text files and perform LF normalization
|
||||
* text
|
||||
|
||||
# Don't check these into the repo as LF to work around TeamCity bug
|
||||
*.xml -text
|
||||
*.targets -text
|
||||
|
||||
# Custom for Visual Studio
|
||||
*.cs diff=csharp
|
||||
*.sln merge=union
|
||||
*.csproj merge=union
|
||||
*.vbproj merge=union
|
||||
*.fsproj merge=union
|
||||
*.dbproj merge=union
|
||||
|
||||
# Denote all files that are truly binary and should not be modified.
|
||||
*.dll binary
|
||||
*.exe binary
|
||||
*.png binary
|
||||
*.ico binary
|
||||
*.snk binary
|
||||
*.pdb binary
|
||||
*.svg binary
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 10 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 8.7 KiB |
@@ -0,0 +1,25 @@
|
||||
### 3.0.0 (2014-04-07)
|
||||
|
||||
- Support for Universal apps (dropped SL and WP7 support)
|
||||
|
||||
### 2.1.0 (2014-02-28)
|
||||
|
||||
- Support for Response Times
|
||||
- Support for Web Hooks alert type
|
||||
- Fix log date conversion
|
||||
|
||||
### 2.0.0 (2014-02-02)
|
||||
|
||||
- Re-publish UptimeSharp as a newly created PCL with support for multiple platforms
|
||||
|
||||
### 0.2.0 (2013-08-28)
|
||||
|
||||
- Added request validation
|
||||
|
||||
### 0.1.1 (2013-08-26)
|
||||
|
||||
- Adding a Port monitor works now
|
||||
|
||||
### 0.1.0 (2013-08-25)
|
||||
|
||||
- Initial release
|
||||
@@ -1,25 +1,285 @@
|
||||
# UptimeSharp
|
||||

|
||||
|
||||
> Under development - don't use yet!
|
||||
**UptimeSharp** is a .NET portable class library that integrates the [UptimeRobot API](http://www.uptimerobot.com/api.asp).
|
||||
|
||||
**UptimeSharp** is a C#.NET class library, that integrates the [UptimeRobot API](http://http://www.uptimerobot.com/api.asp).
|
||||
The wrapper consists of the following parts:
|
||||
|
||||
- Get and modify monitors
|
||||
- Get and modify alert contacts
|
||||
- Register accounts (unofficial)
|
||||
|
||||
## Install UptimeSharp using [NuGet](https://www.nuget.org/packages/UptimeSharp/)
|
||||
|
||||
```
|
||||
Install-Package UptimeSharp
|
||||
```
|
||||
|
||||
## Usage Example
|
||||
|
||||
Get your [API Key UptimeRobot](http://uptimerobot.com/dashboard#mySettings) (right section - "API Settings")
|
||||
|
||||
Include the UptimeSharp namespace and it's associated models:
|
||||
|
||||
```csharp
|
||||
using UptimeSharp;
|
||||
using UptimeSharp.Models;
|
||||
```
|
||||
|
||||
Initialize UptimeClient with:
|
||||
|
||||
```csharp
|
||||
UptimeClient _client = new UptimeClient("[YOUR_API_KEY]");
|
||||
```
|
||||
|
||||
Do a simple request - e.g. get all your monitors:
|
||||
|
||||
```csharp
|
||||
List<Monitor> monitors = await _client.GetMonitors()
|
||||
|
||||
monitors.ForEach(
|
||||
item => Debug.WriteLine(item.Name + " | " + item.Type)
|
||||
);
|
||||
```
|
||||
|
||||
Which will output:
|
||||
|
||||
frontendplay | HTTP
|
||||
google | Keyword
|
||||
localhost | Ping
|
||||
...
|
||||
|
||||
|
||||
## Constructor
|
||||
|
||||
```csharp
|
||||
UptimeClient(string apiKey)
|
||||
```
|
||||
|
||||
Get your [API Key UptimeRobot](http://uptimerobot.com/dashboard#mySettings) (left section under "API Information").
|
||||
<br>Automatic authentication is not available in the moment, but the integration in the API is planned according to UptimeRobot.
|
||||
|
||||
|
||||
## Retrieve
|
||||
|
||||
Get list of all monitors:
|
||||
|
||||
```csharp
|
||||
List<Monitor> items = await _client.GetMonitors();
|
||||
```
|
||||
|
||||
Get monitors by ID - or a single monitor:
|
||||
|
||||
```csharp
|
||||
List<Monitor> items = await _client.GetMonitors(new string[]{ "12891", "98711" });
|
||||
// or
|
||||
Monitor item = await _client.GetMonitor("12891");
|
||||
```
|
||||
|
||||
Provide additional params for more data:
|
||||
|
||||
```csharp
|
||||
List<Monitor> items = await _client.GetMonitors(
|
||||
monitorIDs: new string[]{ "12891", "98711" },
|
||||
customUptimeRatio: new float[] { 7, 30, 45 },
|
||||
includeDetails: true
|
||||
);
|
||||
```
|
||||
|
||||
`monitorIDs`: You can remove this parameter if you want to retrieve all monitors _(default: null)_
|
||||
<br>
|
||||
`customUptimeRatio`: the number of days to calculate the uptime ratio(s) for _(default: null)_
|
||||
<br>
|
||||
`includeDetails`: include log, alerts and response times, if true _(default: false)_
|
||||
<br>
|
||||
|
||||
|
||||
## Add
|
||||
|
||||
Adds/creates a new monitor.
|
||||
|
||||
```csharp
|
||||
Task<Monitor> AddMonitor(
|
||||
string name,
|
||||
string target,
|
||||
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
|
||||
)
|
||||
```
|
||||
|
||||
Example - Watch a SMTP Server:
|
||||
|
||||
```csharp
|
||||
Monitor monitor = await _client.AddMonitor(
|
||||
name: "cee",
|
||||
target: "127.0.0.1",
|
||||
type: Type.Port,
|
||||
subtype: Subtype.SMTP
|
||||
);
|
||||
```
|
||||
|
||||
`name`: A friendly name for the new monitor
|
||||
<br>
|
||||
`target`: The URI or IP to watch
|
||||
<br>
|
||||
`type`: The type of the monitor (see [# Monitor Types](#monitor-types))
|
||||
<br>
|
||||
`subtype`: The subtype of the monitor (only for Type.Port) (see [# Monitor Types](#monitor-types))
|
||||
<br>
|
||||
`port`: The port (only for Subtype.Custom)
|
||||
<br>
|
||||
`keywordValue`: The keyword value (for Type.Keyword)
|
||||
<br>
|
||||
`keywordType`: Type of the keyword (for Type.Keyword)
|
||||
<br>
|
||||
`alerts`: An ID list of existing alerts to notify
|
||||
<br>
|
||||
`HTTPUsername`: The HTTP username
|
||||
<br>
|
||||
`HTTPPassword`: The HTTP password
|
||||
|
||||
As you can see, a lot of these parameters are only available if you've specified the correct `Type`.
|
||||
<br>
|
||||
If you've selected `Type.Port` for example, UptimeSharp will ignore the `keywordValue` and `keywordType` parameters, even if you submitted valid ones.
|
||||
|
||||
|
||||
## Delete
|
||||
|
||||
Delete a monitor by ID:
|
||||
|
||||
```csharp
|
||||
bool isSuccess = await _client.DeleteMonitor("12891");
|
||||
```
|
||||
|
||||
Delete a monitor by a Monitor instance:
|
||||
|
||||
```csharp
|
||||
// Monitor myMonitor = ...
|
||||
bool isSuccess = await _client.DeleteMonitor(myMonitor);
|
||||
```
|
||||
|
||||
|
||||
## Modify
|
||||
|
||||
In order to modify an existing monitor, just alter the properties of the Monitor instance and call the `ModifyMonitor` method:
|
||||
|
||||
```csharp
|
||||
// Monitor myMonitor = ...
|
||||
myMonitor.Name = "my new name :-)";
|
||||
bool isSuccess = await _client.ModifyMonitor(myMonitor);
|
||||
```
|
||||
|
||||
**Important:** It is not possible to alter the `Type` of a monitor after its creation! In case you want to do this, you have to delete the monitor and create a new one with the changed type.
|
||||
|
||||
### Modify Alerts
|
||||
|
||||
Retrieve all alerts:
|
||||
|
||||
```csharp
|
||||
List<Alert> items = await _client.GetAlerts();
|
||||
```
|
||||
|
||||
Retrieve alerts by IDs:
|
||||
|
||||
```csharp
|
||||
List<Alert> items = await _client.GetAlerts(new string[]{ "12897", "98711" });
|
||||
```
|
||||
|
||||
Retrieve a specific alert:
|
||||
|
||||
```csharp
|
||||
Alert item = await _client.GetAlert("12897");
|
||||
```
|
||||
|
||||
Adds an alert _(Due to UptimeRobot API limitations SMS and Twitter alert contact types are not supported yet)_:
|
||||
|
||||
```csharp
|
||||
Alert alert = await _client.AddAlert(AlertType.Email, "uptimesharp@outlook.com");
|
||||
```
|
||||
|
||||
Adds an alert from instance:
|
||||
|
||||
```csharp
|
||||
// Alert myAlert = ...
|
||||
Alert alert = await _client.AddAlert(myAlert);
|
||||
```
|
||||
|
||||
Deletes an alert:
|
||||
|
||||
```csharp
|
||||
bool isSuccess = await _client.DeleteAlert("12897");
|
||||
```
|
||||
|
||||
Deletes an alert from instance:
|
||||
|
||||
```csharp
|
||||
// Alert myAlert = ...
|
||||
bool isSuccess = await _client.DeleteAlert(myAlert);
|
||||
```
|
||||
|
||||
## Monitor Types
|
||||
|
||||
- [HTTP](#http-monitoring)
|
||||
- [Keyword](#keyword)
|
||||
- [Ping](#ping)
|
||||
- [Port](#port)
|
||||
|
||||
### HTTP Monitoring
|
||||
|
||||
Simple HTTP monitor which requests the webpage every 5 minutes and checks for HTTP Status 200 OK.
|
||||
|
||||
### Keyword Monitoring
|
||||
|
||||
The keyword monitor is sniffing the page content if a specified keyword exists/not exists.
|
||||
|
||||
The keyword is submitted via the **keywordValue** parameter. The **keywordType** parameter specifies if the value should exist or not exist.
|
||||
|
||||
### Ping Monitoring
|
||||
|
||||
This type lets you monitor a server by pinging it.
|
||||
|
||||
### Port Monitoring
|
||||
|
||||
If you want to monitor a port, you need to specify a **subType** which is a common port a custom one:
|
||||
|
||||
- HTTP :80
|
||||
- HTTPS :443
|
||||
- FTP :21
|
||||
- SMTP :25
|
||||
- POP3 :110
|
||||
- IMAP :143
|
||||
- Custom Port (use the "port" parameter, if this option is selected)
|
||||
|
||||
---
|
||||
|
||||
## Release History
|
||||
|
||||
- 2013-08-13 v0.1.0 initial
|
||||
## Supported platforms
|
||||
|
||||
UptimeSharp is a **Portable Class Library**, therefore it's compatible with multiple platforms and Universal Apps:
|
||||
|
||||
- **.NET** >= 4.5 (including WPF)
|
||||
- **Windows Phone** (Silverlight + WinPRT) >= 8
|
||||
- **Windows Store** >= 8
|
||||
- **Xamarin** iOS + Android
|
||||
- _WP7 and Silverlight are dropped in 4.0, use UptimeSharp < 3.0, if you want to support them_
|
||||
|
||||
## Dependencies
|
||||
|
||||
- [RestSharp](http://restsharp.org/)
|
||||
- [ServiceStack.Text](https://github.com/ServiceStack/ServiceStack.Text)
|
||||
- [Microsoft.Bcl.Async](https://www.nuget.org/packages/Microsoft.Bcl.Async/)
|
||||
- [Microsoft.Net.Http](https://www.nuget.org/packages/Microsoft.Net.Http/)
|
||||
- [Newtonsoft.Json](https://www.nuget.org/packages/Newtonsoft.Json/)
|
||||
- [PropertyChanged.Fody](https://github.com/Fody/PropertyChanged)
|
||||
|
||||
## Contributors
|
||||
| [](http://twitter.com/artistandsocial "Follow @artistandsocial on Twitter") |
|
||||
|---|
|
||||
| [Tobias Klika @ceee](https://github.com/ceee) |
|
||||
|
||||
| [](https://github.com/ceee "Tobias Klika") |
|
||||
|---|
|
||||
| [ceee](https://github.com/ceee) |
|
||||
## License
|
||||
|
||||
[MIT License](https://github.com/ceee/UptimeSharp/blob/master/LICENSE-MIT)
|
||||
|
||||
@@ -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,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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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 {}
|
||||
}
|
||||
+19
@@ -8,6 +8,25 @@ namespace UptimeSharp.Models
|
||||
[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>
|
||||
@@ -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")]
|
||||
@@ -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) { }
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
@@ -0,0 +1,67 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Xunit;
|
||||
|
||||
namespace UptimeSharp.Tests
|
||||
{
|
||||
public class AccountTest : TestsBase
|
||||
{
|
||||
public AccountTest() : base() { }
|
||||
|
||||
|
||||
[Fact]
|
||||
public async Task IsAvailabilityCheckWorking()
|
||||
{
|
||||
Assert.False(await client.IsEmailAvailable("cee@live.at"));
|
||||
Assert.True(await client.IsEmailAvailable(Guid.NewGuid().ToString() + "@live.at"));
|
||||
|
||||
await ThrowsAsync<ArgumentNullException>(async () =>
|
||||
{
|
||||
await client.IsEmailAvailable("");
|
||||
});
|
||||
|
||||
await ThrowsAsync<ArgumentException>(async () =>
|
||||
{
|
||||
await client.IsEmailAvailable("opiu@opiuast");
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
[Fact]
|
||||
public async Task IsAccountRegistrationWorking()
|
||||
{
|
||||
Assert.True(await client.RegisterAccount("my name", Guid.NewGuid().ToString() + "@live.at", "123456"));
|
||||
Assert.False(await client.RegisterAccount("my name", "cee@live.at", "123456"));
|
||||
|
||||
await ThrowsAsync<ArgumentNullException>(async () =>
|
||||
{
|
||||
await client.RegisterAccount("", "cee@live.at", "poiuadfafo");
|
||||
});
|
||||
|
||||
await ThrowsAsync<ArgumentNullException>(async () =>
|
||||
{
|
||||
await client.RegisterAccount("my name", "", "poiuadfafo");
|
||||
});
|
||||
|
||||
await ThrowsAsync<ArgumentNullException>(async () =>
|
||||
{
|
||||
await client.RegisterAccount("my name", "cee@live.at", "");
|
||||
});
|
||||
|
||||
await ThrowsAsync<ArgumentException>(async () =>
|
||||
{
|
||||
await client.RegisterAccount("my name", "opiu@opiuast", "password");
|
||||
});
|
||||
|
||||
await ThrowsAsync<ArgumentException>(async () =>
|
||||
{
|
||||
await client.RegisterAccount("my", "cee@live.at", "password");
|
||||
});
|
||||
|
||||
await ThrowsAsync<ArgumentException>(async () =>
|
||||
{
|
||||
await client.RegisterAccount("my name", "cee@live.at", "pass");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,106 +1,79 @@
|
||||
using NUnit.Framework;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using UptimeSharp.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace UptimeSharp.Tests
|
||||
{
|
||||
[TestFixture]
|
||||
public class AlertsTest
|
||||
public class AlertsTest : TestsBase
|
||||
{
|
||||
UptimeClient client;
|
||||
|
||||
// this API key is associated with the test account uptimesharp@outlook.com
|
||||
// please don't abuse it and create your own if you want to test the project!
|
||||
string APIKey = "u97240-a24c634b3b84f1af602628e8";
|
||||
public AlertsTest() : base() { }
|
||||
|
||||
|
||||
[SetUp]
|
||||
public void Setup()
|
||||
[Fact]
|
||||
public async Task AddInvalidAlertWithTypeSms()
|
||||
{
|
||||
client = new UptimeClient(APIKey);
|
||||
await ThrowsAsync<UptimeSharpException>(async () =>
|
||||
{
|
||||
await client.AddAlert(Models.AlertType.SMS, "+436601289172");
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
[TearDown]
|
||||
public void Teardown()
|
||||
[Fact]
|
||||
public async Task AddInvalidAlertWithTypeTwitter()
|
||||
{
|
||||
List<Alert> alerts = client.GetAlerts();
|
||||
alerts.ForEach(alert => client.DeleteAlert(alert));
|
||||
await ThrowsAsync<UptimeSharpException>(async () =>
|
||||
{
|
||||
await client.AddAlert(Models.AlertType.Twitter, "artistandsocial");
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
[Test]
|
||||
[ExpectedException(typeof(APIException))]
|
||||
public void AddInvalidAlertWithTypeSms()
|
||||
{
|
||||
client.AddAlert(Models.AlertType.SMS, "+436601289172");
|
||||
}
|
||||
|
||||
|
||||
[Test]
|
||||
[ExpectedException(typeof(APIException))]
|
||||
public void AddInvalidAlertWithTypeTwitter()
|
||||
{
|
||||
client.AddAlert(Models.AlertType.Twitter, "artistandsocial");
|
||||
}
|
||||
|
||||
|
||||
[Test]
|
||||
public void AddAndRemoveAlerts()
|
||||
[Fact]
|
||||
public async Task AddAndRemoveAlerts()
|
||||
{
|
||||
string email = "example@ceecore.com";
|
||||
|
||||
Assert.IsTrue(client.AddAlert(AlertType.Email, email), "Response should be true for adding a new alert");
|
||||
Assert.NotNull(await client.AddAlert(AlertType.Email, email));
|
||||
|
||||
Alert origin = GetOriginAlert(email);
|
||||
Alert origin = await GetOriginAlert(email);
|
||||
|
||||
Assert.AreEqual(email, origin.Value, "Retrieved alert should have the value (example@ceecore.com) which was submitted");
|
||||
Assert.AreEqual(AlertType.Email, origin.Type, "Retrieved alert should have the type (email) which was submitted");
|
||||
Assert.Equal(email, origin.Value);
|
||||
Assert.Equal(AlertType.Email, origin.Type);
|
||||
|
||||
client.DeleteAlert(origin);
|
||||
await client.DeleteAlert(origin);
|
||||
|
||||
origin = GetOriginAlert(email);
|
||||
origin = await GetOriginAlert(email);
|
||||
|
||||
Assert.IsNull(origin, "Alert should have been deleted");
|
||||
Assert.Null(origin);
|
||||
}
|
||||
|
||||
|
||||
[Test]
|
||||
public void AddAndRetrieveSpecificAlerts()
|
||||
[Fact]
|
||||
public async Task AddAndRetrieveSpecificAlerts()
|
||||
{
|
||||
Assert.IsTrue(
|
||||
client.AddAlert(AlertType.Email, "example1@ceecore.com"),
|
||||
"Response should be true for adding a new alert (email 1)"
|
||||
);
|
||||
Assert.IsTrue(
|
||||
client.AddAlert(AlertType.Boxcar, "example@ceecore.com"),
|
||||
"Response should be true for adding a new alert (bocar 4)"
|
||||
);
|
||||
Alert alert1;
|
||||
Alert alert2;
|
||||
Alert alert3;
|
||||
|
||||
List<Alert> alerts = client.GetAlerts();
|
||||
Assert.NotNull(alert1 = await client.AddAlert(AlertType.Email, "example1@ceecore.com"));
|
||||
Assert.NotNull(alert2 = await client.AddAlert(AlertType.Boxcar, "example2@ceecore.com"));
|
||||
Assert.NotNull(alert3 = await client.AddAlert(AlertType.WebHook, "http://ceecore.com?"));
|
||||
|
||||
Assert.GreaterOrEqual(alerts.ToArray().Length, 2, "Alerts length should be at least 2", alerts);
|
||||
|
||||
List<Alert> specificAlerts = client.GetAlerts(new int[] { alerts[0].ID, alerts[1].ID });
|
||||
|
||||
Assert.AreEqual(2, specificAlerts.ToArray().Length, "Specific alerts length should be 2", specificAlerts);
|
||||
}
|
||||
|
||||
|
||||
private Alert GetOriginAlert(string value)
|
||||
{
|
||||
List<Alert> alerts = client.GetAlerts();
|
||||
Alert origin = null;
|
||||
|
||||
alerts.ForEach(alert =>
|
||||
try
|
||||
{
|
||||
if (alert.Value == value)
|
||||
{
|
||||
origin = alert;
|
||||
}
|
||||
});
|
||||
await client.DeleteAlert(alert1);
|
||||
await client.DeleteAlert(alert2);
|
||||
await client.DeleteAlert(alert3);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
return origin;
|
||||
|
||||
private async Task<Alert> GetOriginAlert(string value)
|
||||
{
|
||||
return (await client.GetAlerts()).FirstOrDefault(item => item.Value == value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,32 +1,18 @@
|
||||
using NUnit.Framework;
|
||||
using System.Collections.Generic;
|
||||
using UptimeSharp.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace UptimeSharp.Tests
|
||||
{
|
||||
[TestFixture]
|
||||
public class ClientTest
|
||||
public class ClientTest : TestsBase
|
||||
{
|
||||
UptimeClient client;
|
||||
|
||||
// this API key is associated with the test account uptimesharp@outlook.com
|
||||
// please don't abuse it and create your own if you want to test the project!
|
||||
string APIKey = "u97240-a24c634b3b84f1af602628e8";
|
||||
public ClientTest() : base() { }
|
||||
|
||||
|
||||
[SetUp]
|
||||
public void Setup()
|
||||
{
|
||||
client = new UptimeClient(APIKey);
|
||||
}
|
||||
|
||||
|
||||
[Test]
|
||||
[Fact]
|
||||
public void Initialize()
|
||||
{
|
||||
Assert.IsNull(client.LastRequestData, "LastRequestData should be null on init");
|
||||
Assert.Null(client.lastResponseData);
|
||||
|
||||
Assert.AreEqual(APIKey, client.ApiKey, "API Key should be correctly assigned");
|
||||
Assert.Equal(APIKey, client.ApiKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,57 +1,126 @@
|
||||
using NUnit.Framework;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using UptimeSharp.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace UptimeSharp.Tests
|
||||
{
|
||||
[TestFixture]
|
||||
public class MonitorsTest
|
||||
public class MonitorsTest : TestsBase
|
||||
{
|
||||
UptimeClient client;
|
||||
|
||||
// this API key is associated with the test account uptimesharp@outlook.com
|
||||
// please don't abuse it and create your own if you want to test the project!
|
||||
string APIKey = "u97240-a24c634b3b84f1af602628e8";
|
||||
public MonitorsTest() : base() { }
|
||||
|
||||
|
||||
[SetUp]
|
||||
public void Setup()
|
||||
[Fact]
|
||||
public async void AddHTTPMonitor()
|
||||
{
|
||||
//client = new UptimeClient(APIKey);
|
||||
Monitor monitor;
|
||||
Assert.NotNull(monitor = await client.AddMonitor(
|
||||
name: "test_1",
|
||||
target: "http://test1.com"
|
||||
));
|
||||
|
||||
await client.DeleteMonitor(monitor);
|
||||
}
|
||||
|
||||
|
||||
[TearDown]
|
||||
public void Teardown()
|
||||
[Fact]
|
||||
public async Task AddKeywordMonitor()
|
||||
{
|
||||
//List<Alert> alerts = client.RetrieveAlerts();
|
||||
//alerts.ForEach(alert => client.DeleteAlert(alert));
|
||||
Monitor monitor;
|
||||
Assert.NotNull(monitor = await client.AddMonitor(
|
||||
name: "test_2",
|
||||
target: "http://test2.com",
|
||||
type: Models.Type.Keyword,
|
||||
keywordType: KeywordType.Exists,
|
||||
keywordValue: "test"
|
||||
));
|
||||
|
||||
await client.DeleteMonitor(monitor);
|
||||
}
|
||||
|
||||
|
||||
//bool result = client.Delete(775853599);
|
||||
[Fact]
|
||||
public async Task AddPingMonitor()
|
||||
{
|
||||
Monitor monitor;
|
||||
Assert.NotNull(monitor = await client.AddMonitor(
|
||||
name: "test_3",
|
||||
target: "http://test3.com",
|
||||
type: Models.Type.Ping
|
||||
));
|
||||
|
||||
//bool result = client.Create("apitest", "http://pocketsharp.com", Models.Type.HTTP);
|
||||
//client.Add("apiKeywordTest", "http://frontendplay.com", "frontendplay", KeywordType.NotExists);
|
||||
await client.DeleteMonitor(monitor);
|
||||
}
|
||||
|
||||
//client.DeleteAlert(2014599);
|
||||
//bool result = client.AddAlert(AlertType.Email, "klika@live.at");
|
||||
|
||||
//bool x = client.Add(
|
||||
// name: "testx",
|
||||
// uri: "http://google.at",
|
||||
// type: Models.Type.Keyword,
|
||||
// keywordType: KeywordType.Exists,
|
||||
// keywordValue: "goog"
|
||||
//);
|
||||
//List<Monitor> monitors = client.Retrieve(showLog: true);
|
||||
//List<Alert> alerts = client.RetrieveAlerts();
|
||||
//System.Console.WriteLine(monitor.ID + " " + monitor.Name);
|
||||
//alerts.ForEach(item => System.Console.WriteLine(item.ID + " " + item.Type.ToString() + " " + item.Value));
|
||||
[Fact]
|
||||
public async Task AddPortMonitor()
|
||||
{
|
||||
Monitor monitor;
|
||||
Assert.NotNull(monitor = await client.AddMonitor(
|
||||
name: "test_4",
|
||||
target: "127.0.0.1",
|
||||
type: Models.Type.Port,
|
||||
subtype: Subtype.Custom,
|
||||
port: 50004
|
||||
));
|
||||
|
||||
//monitor.Name = "HALLOOO";
|
||||
//bool result = client.Modify(monitor);
|
||||
await client.DeleteMonitor(monitor);
|
||||
}
|
||||
|
||||
//monitors.ForEach(item => System.Console.WriteLine(item.ID + " " + item.Name + " " + item.Status));
|
||||
|
||||
[Fact]
|
||||
public async Task GetMonitors()
|
||||
{
|
||||
Monitor monitor;
|
||||
Assert.NotNull(monitor = await client.AddMonitor(
|
||||
name: "test_5",
|
||||
target: "255.0.0.1",
|
||||
type: Models.Type.Port,
|
||||
subtype: Subtype.HTTP
|
||||
));
|
||||
|
||||
Assert.True(
|
||||
monitor != null
|
||||
&& monitor.Target == "255.0.0.1"
|
||||
&& monitor.Type == Models.Type.Port
|
||||
&& monitor.Subtype == Subtype.HTTP);
|
||||
|
||||
monitor = await client.GetMonitor(monitor.ID);
|
||||
|
||||
Assert.True(
|
||||
monitor != null
|
||||
&& monitor.Target == "255.0.0.1"
|
||||
&& monitor.Type == Models.Type.Port
|
||||
&& monitor.Subtype == Subtype.HTTP);
|
||||
|
||||
await client.DeleteMonitor(monitor);
|
||||
}
|
||||
|
||||
|
||||
[Fact]
|
||||
public async Task ModifyAMonitor()
|
||||
{
|
||||
Assert.NotNull(await client.AddMonitor(
|
||||
name: "test_6",
|
||||
target: "http://test6.com"
|
||||
));
|
||||
|
||||
List<Monitor> items = await client.GetMonitors();
|
||||
Monitor monitor = items.SingleOrDefault(item => item.Name == "test_6");
|
||||
|
||||
Assert.NotNull(monitor);
|
||||
|
||||
monitor.Name = "updated_test_6";
|
||||
|
||||
Assert.True(await client.ModifyMonitor(monitor));
|
||||
|
||||
monitor = await client.GetMonitor(monitor.ID);
|
||||
|
||||
Assert.Equal(monitor.Name, "updated_test_6");
|
||||
|
||||
await client.DeleteMonitor(monitor);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
@@ -10,7 +9,7 @@ using System.Runtime.InteropServices;
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("UptimeSharp.Tests")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2013")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2014")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
@@ -32,5 +31,5 @@ using System.Runtime.InteropServices;
|
||||
// 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")]
|
||||
[assembly: AssemblyVersion("1.1.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.1.0.0")]
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Xunit;
|
||||
|
||||
namespace UptimeSharp.Tests
|
||||
{
|
||||
public class TestsBase : IDisposable
|
||||
{
|
||||
protected UptimeClient client;
|
||||
|
||||
// this API key is associated with the test account uptimesharp@outlook.com
|
||||
// please don't abuse it and create your own if you want to test the project!
|
||||
protected string APIKey = "u97240-a24c634b3b84f1af602628e8";
|
||||
|
||||
|
||||
// setup
|
||||
public TestsBase()
|
||||
{
|
||||
client = new UptimeClient(APIKey);
|
||||
}
|
||||
|
||||
|
||||
// teardown
|
||||
public void Dispose() { }
|
||||
|
||||
|
||||
// async throws
|
||||
public static async Task ThrowsAsync<TException>(Func<Task> func)
|
||||
{
|
||||
var expected = typeof(TException);
|
||||
System.Type actual = null;
|
||||
try
|
||||
{
|
||||
await func();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
actual = e.GetType();
|
||||
}
|
||||
Assert.Equal(expected, actual);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,8 +9,9 @@
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>UptimeSharp.Tests</RootNamespace>
|
||||
<AssemblyName>UptimeSharp.Tests</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
|
||||
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<TargetFrameworkProfile />
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
@@ -20,6 +21,7 @@
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<Prefer32Bit>false</Prefer32Bit>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
@@ -28,43 +30,63 @@
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<Prefer32Bit>false</Prefer32Bit>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="nunit.framework">
|
||||
<HintPath>..\packages\NUnit.2.6.2\lib\nunit.framework.dll</HintPath>
|
||||
<Reference Include="Microsoft.Threading.Tasks">
|
||||
<HintPath>..\packages\Microsoft.Bcl.Async.1.0.165\lib\net45\Microsoft.Threading.Tasks.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="RestSharp, Version=104.1.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\packages\RestSharp.104.1\lib\net4\RestSharp.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="ServiceStack.Text, Version=3.9.58.0, Culture=neutral, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\packages\ServiceStack.Text.3.9.58\lib\net35\ServiceStack.Text.dll</HintPath>
|
||||
<Reference Include="Microsoft.Threading.Tasks.Extensions">
|
||||
<HintPath>..\packages\Microsoft.Bcl.Async.1.0.165\lib\net45\Microsoft.Threading.Tasks.Extensions.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Net" />
|
||||
<Reference Include="System.Net.Http" />
|
||||
<Reference Include="System.Net.Http.Extensions">
|
||||
<HintPath>..\packages\Microsoft.Net.Http.2.2.18\lib\net45\System.Net.Http.Extensions.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Net.Http.Primitives, Version=4.2.18.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\packages\Microsoft.Net.Http.2.2.18\lib\net45\System.Net.Http.Primitives.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Net.Http.WebRequest" />
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Xml" />
|
||||
<Reference Include="xunit">
|
||||
<HintPath>..\packages\xunit.1.9.2\lib\net20\xunit.dll</HintPath>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="AccountTest.cs" />
|
||||
<Compile Include="AlertsTest.cs" />
|
||||
<Compile Include="ClientTest.cs" />
|
||||
<Compile Include="MonitorsTest.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="TestsBase.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="app.config" />
|
||||
<None Include="packages.config" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\UptimeSharp\UptimeSharp.csproj">
|
||||
<Project>{af900acf-dc2a-40ac-9614-b7c8c12e114c}</Project>
|
||||
<Project>{ec1e656d-4966-499a-9edd-9db56137bf62}</Project>
|
||||
<Name>UptimeSharp</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<Import Project="..\packages\Microsoft.Bcl.Build.1.0.13\tools\Microsoft.Bcl.Build.targets" Condition="Exists('..\packages\Microsoft.Bcl.Build.1.0.13\tools\Microsoft.Bcl.Build.targets')" />
|
||||
<Target Name="EnsureBclBuildImported" BeforeTargets="BeforeBuild" Condition="'$(BclBuildImported)' == ''">
|
||||
<Error Condition="!Exists('..\packages\Microsoft.Bcl.Build.1.0.13\tools\Microsoft.Bcl.Build.targets')" Text="This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=317567." HelpKeyword="BCLBUILD2001" />
|
||||
<Error Condition="Exists('..\packages\Microsoft.Bcl.Build.1.0.13\tools\Microsoft.Bcl.Build.targets')" Text="The build restored NuGet packages. Build the project again to include these packages in the build. For more information, see http://go.microsoft.com/fwlink/?LinkID=317568." HelpKeyword="BCLBUILD2002" />
|
||||
</Target>
|
||||
<!-- 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">
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<runtime>
|
||||
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Net.Http.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.2.18.0" newVersion="4.2.18.0" />
|
||||
</dependentAssembly>
|
||||
</assemblyBinding>
|
||||
</runtime>
|
||||
</configuration>
|
||||
@@ -1,6 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="NUnit" version="2.6.2" targetFramework="net40" />
|
||||
<package id="RestSharp" version="104.1" targetFramework="net40" />
|
||||
<package id="ServiceStack.Text" version="3.9.58" targetFramework="net40" />
|
||||
<package id="Microsoft.Bcl" version="1.1.6" targetFramework="net45" />
|
||||
<package id="Microsoft.Bcl.Async" version="1.0.165" targetFramework="net45" />
|
||||
<package id="Microsoft.Bcl.Build" version="1.0.13" targetFramework="net45" />
|
||||
<package id="Microsoft.Net.Http" version="2.2.18" targetFramework="net45" />
|
||||
<package id="xunit" version="1.9.2" targetFramework="net40" />
|
||||
</packages>
|
||||
+9
-7
@@ -1,24 +1,26 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio 2012
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UptimeSharp", "UptimeSharp\UptimeSharp.csproj", "{AF900ACF-DC2A-40AC-9614-B7C8C12E114C}"
|
||||
EndProject
|
||||
# Visual Studio 2013
|
||||
VisualStudioVersion = 12.0.30324.0
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UptimeSharp.Tests", "UptimeSharp.Tests\UptimeSharp.Tests.csproj", "{7AB536B7-1A99-44A7-B5AA-E36E9C7F09F4}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UptimeSharp", "UptimeSharp\UptimeSharp.csproj", "{EC1E656D-4966-499A-9EDD-9DB56137BF62}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{AF900ACF-DC2A-40AC-9614-B7C8C12E114C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{AF900ACF-DC2A-40AC-9614-B7C8C12E114C}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{AF900ACF-DC2A-40AC-9614-B7C8C12E114C}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{AF900ACF-DC2A-40AC-9614-B7C8C12E114C}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{7AB536B7-1A99-44A7-B5AA-E36E9C7F09F4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{7AB536B7-1A99-44A7-B5AA-E36E9C7F09F4}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{7AB536B7-1A99-44A7-B5AA-E36E9C7F09F4}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{7AB536B7-1A99-44A7-B5AA-E36E9C7F09F4}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{EC1E656D-4966-499A-9EDD-9DB56137BF62}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{EC1E656D-4966-499A-9EDD-9DB56137BF62}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{EC1E656D-4966-499A-9EDD-9DB56137BF62}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{EC1E656D-4966-499A-9EDD-9DB56137BF62}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
using System;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace UptimeSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// custom UptimeRobot API Exceptions
|
||||
/// </summary>
|
||||
public class APIException : Exception
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the UptimeRobot error code.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The pocket error code.
|
||||
/// </value>
|
||||
public int? UptimeErrorCode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the UptimeRobot error.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The pocket error.
|
||||
/// </value>
|
||||
public string UptimeError { get; set; }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="APIException"/> class.
|
||||
/// </summary>
|
||||
public APIException()
|
||||
: base() { }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="APIException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="message">The message that describes the error.</param>
|
||||
public APIException(string message)
|
||||
: base(message) { }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="APIException"/> 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 APIException(string message, Exception innerException)
|
||||
: base(message, innerException) { }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="APIException"/> 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 APIException(SerializationInfo info, StreamingContext context)
|
||||
: base(info, context) { }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace UptimeSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// UptimeClient
|
||||
/// </summary>
|
||||
public partial class UptimeClient
|
||||
{
|
||||
private Regex isEmailRegex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,10}))$", RegexOptions.IgnoreCase);
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether a e-mail is available.
|
||||
/// </summary>
|
||||
/// <param name="email">The email.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="System.ArgumentNullException">Please provide an e-mail address</exception>
|
||||
/// <exception cref="System.ArgumentException">Please provide a valid e-mail address</exception>
|
||||
public async Task<bool> IsEmailAvailable(string email, CancellationToken cancellationToken = default(CancellationToken))
|
||||
{
|
||||
if (String.IsNullOrEmpty(email))
|
||||
{
|
||||
throw new ArgumentNullException("Please provide an e-mail address");
|
||||
}
|
||||
|
||||
if (!isEmailRegex.IsMatch(email))
|
||||
{
|
||||
throw new ArgumentException("Please provide a valid e-mail address");
|
||||
}
|
||||
|
||||
return (await AccountRequest("checkUserEmail", cancellationToken, new Dictionary<string, string>()
|
||||
{
|
||||
{ "userEmail", email }
|
||||
})).Success;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Registers the account.
|
||||
/// </summary>
|
||||
/// <param name="fullName">The full name (min. 3 chars).</param>
|
||||
/// <param name="email">The email address.</param>
|
||||
/// <param name="password">The password (min. 6 chars).</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="System.ArgumentNullException">Please provide all parameters (username, email and password)</exception>
|
||||
/// <exception cref="System.ArgumentException">
|
||||
/// Please provide a valid e-mail address
|
||||
/// or
|
||||
/// Name must be at least 3 characters
|
||||
/// or
|
||||
/// Username must be at least 6 characters
|
||||
/// </exception>
|
||||
public async Task<bool> RegisterAccount(string fullName, string email, string password, CancellationToken cancellationToken = default(CancellationToken))
|
||||
{
|
||||
if (String.IsNullOrEmpty(email) || String.IsNullOrEmpty(fullName) || String.IsNullOrEmpty(password))
|
||||
{
|
||||
throw new ArgumentNullException("Please provide all parameters (username, email and password)");
|
||||
}
|
||||
|
||||
if (!isEmailRegex.IsMatch(email))
|
||||
{
|
||||
throw new ArgumentException("Please provide a valid e-mail address");
|
||||
}
|
||||
|
||||
if (fullName.Length < 3)
|
||||
{
|
||||
throw new ArgumentException("Name must be at least 3 characters");
|
||||
}
|
||||
|
||||
if (password.Length < 6)
|
||||
{
|
||||
throw new ArgumentException("Username must be at least 6 characters");
|
||||
}
|
||||
|
||||
return (await AccountRequest("newUser", cancellationToken, new Dictionary<string, string>()
|
||||
{
|
||||
{ "userFirstLastName", fullName },
|
||||
{ "userEmail", email },
|
||||
{ "userPassword", password }
|
||||
}, true)).Success;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
using RestSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using UptimeSharp.Models;
|
||||
|
||||
namespace UptimeSharp
|
||||
@@ -14,12 +14,17 @@ namespace UptimeSharp
|
||||
/// Retrieves alerts from UptimeRobot
|
||||
/// </summary>
|
||||
/// <param name="alertIDs">Retrieve specified alert contacts by supplying IDs for them.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns></returns>
|
||||
public List<Alert> GetAlerts(int[] alertIDs = null)
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
public async Task<List<Alert>> GetAlerts(string[] alertIDs = null, CancellationToken cancellationToken = default(CancellationToken))
|
||||
{
|
||||
Parameter alerts = Parameter("alertcontacts", alertIDs != null ? string.Join("-", alertIDs) : null);
|
||||
AlertResponse response = await Request<AlertResponse>("getAlertContacts", cancellationToken, new Dictionary<string, string>()
|
||||
{
|
||||
{ "alertcontacts", alertIDs != null ? string.Join("-", alertIDs) : null }
|
||||
});
|
||||
|
||||
return Get<AlertResponse>("getAlertContacts", alerts).Items;
|
||||
return response.Items ?? new List<Alert>();
|
||||
}
|
||||
|
||||
|
||||
@@ -27,33 +32,46 @@ namespace UptimeSharp
|
||||
/// Retrieves an alert from UptimeRobot
|
||||
/// </summary>
|
||||
/// <param name="alertID">The alertID.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns></returns>
|
||||
public Alert GetAlert(int alertID)
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
public async Task<Alert> GetAlert(string alertID, CancellationToken cancellationToken = default(CancellationToken))
|
||||
{
|
||||
List<Alert> alerts = GetAlerts(new int[] { alertID });
|
||||
List<Alert> alerts = await GetAlerts(new string[] { alertID }, cancellationToken);
|
||||
|
||||
return alerts.ToArray().Length > 0 ? alerts[0] : null;
|
||||
return alerts != null && alerts.Count > 0 ? alerts[0] : null;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Adds an alert.
|
||||
/// mobile/SMS alert contacts are not supported yet, see: http://www.uptimerobot.com/api.asp#methods
|
||||
/// SMS & Twitter 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>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns></returns>
|
||||
public bool AddAlert(AlertType type, string value)
|
||||
/// <exception cref="UptimeSharpException">AlertType.SMS and AlertType.Twitter are not supported by the UptimeRobot API</exception>
|
||||
public async Task<Alert> AddAlert(AlertType type, string value, CancellationToken cancellationToken = default(CancellationToken))
|
||||
{
|
||||
if (type == AlertType.SMS || type == AlertType.Twitter)
|
||||
{
|
||||
throw new APIException("AlertType.SMS and AlertType.Twitter are not supported by the UptimeRobot API");
|
||||
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;
|
||||
Alert alert = (await Request<AddAlertResponse>("newAlertContact", cancellationToken, new Dictionary<string, string>()
|
||||
{
|
||||
{ "alertContactType", ((int)type).ToString() },
|
||||
{ "alertContactValue", value }
|
||||
})).Alert;
|
||||
|
||||
if (alert != null)
|
||||
{
|
||||
alert.Type = type;
|
||||
alert.Value = value;
|
||||
}
|
||||
|
||||
return alert;
|
||||
}
|
||||
|
||||
|
||||
@@ -62,10 +80,12 @@ namespace UptimeSharp
|
||||
/// mobile/SMS alert contacts are not supported yet, see: http://www.uptimerobot.com/api.asp#methods
|
||||
/// </summary>
|
||||
/// <param name="alert">The alert.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns></returns>
|
||||
public bool AddAlert(Alert alert)
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
public async Task<Alert> AddAlert(Alert alert, CancellationToken cancellationToken = default(CancellationToken))
|
||||
{
|
||||
return AddAlert(alert.Type, alert.Value);
|
||||
return await AddAlert(alert.Type, alert.Value, cancellationToken);
|
||||
}
|
||||
|
||||
|
||||
@@ -73,10 +93,21 @@ namespace UptimeSharp
|
||||
/// Removes an alert.
|
||||
/// </summary>
|
||||
/// <param name="alertID">The alert ID.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns></returns>
|
||||
public bool DeleteAlert(int alertID)
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
public async Task<bool> DeleteAlert(string alertID, CancellationToken cancellationToken = default(CancellationToken))
|
||||
{
|
||||
return Get<DefaultResponse>("deleteAlertContact", Parameter("alertContactID", alertID)).Status;
|
||||
// try to delete main alert
|
||||
if (alertID.StartsWith("0"))
|
||||
{
|
||||
throw new UptimeSharpException("Can't delete main alert");
|
||||
}
|
||||
|
||||
return (await Request<DefaultResponse>("deleteAlertContact", cancellationToken, new Dictionary<string, string>()
|
||||
{
|
||||
{ "alertContactID", alertID }
|
||||
})).Success;
|
||||
}
|
||||
|
||||
|
||||
@@ -84,10 +115,12 @@ namespace UptimeSharp
|
||||
/// Removes an alert.
|
||||
/// </summary>
|
||||
/// <param name="alert">The alert.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns></returns>
|
||||
public bool DeleteAlert(Alert alert)
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
public async Task<bool> DeleteAlert(Alert alert, CancellationToken cancellationToken = default(CancellationToken))
|
||||
{
|
||||
return DeleteAlert((int)alert.ID);
|
||||
return await DeleteAlert(alert.ID, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
using RestSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using UptimeSharp.Models;
|
||||
|
||||
namespace UptimeSharp
|
||||
@@ -13,24 +16,35 @@ namespace UptimeSharp
|
||||
/// <summary>
|
||||
/// Retrieves specified monitors from UptimeRobot
|
||||
/// </summary>
|
||||
/// <param name="monitors">monitor list</param>
|
||||
/// <param name="monitorIDs">The monitor IDs.</param>
|
||||
/// <param name="includeDetails">if set to <c>true</c> [include details (log, alerts and response times)].</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>
|
||||
/// <param name="responseTimesAverage">The response times average in minutes, which is used as the calculation base for the response times.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>
|
||||
/// Monitor List
|
||||
/// </returns>
|
||||
public List<Monitor> GetMonitors(int[] monitors = null, float[] customUptimeRatio = null, bool showLog = false, bool showAlerts = true)
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
public async Task<List<Models.Monitor>> GetMonitors(
|
||||
string[] monitorIDs = null,
|
||||
bool includeDetails = true,
|
||||
float[] customUptimeRatio = null,
|
||||
int responseTimesAverage = 0,
|
||||
CancellationToken cancellationToken = default(CancellationToken))
|
||||
{
|
||||
RetrieveParameters parameters = new RetrieveParameters()
|
||||
{
|
||||
Monitors = monitors,
|
||||
Monitors = monitorIDs,
|
||||
CustomUptimeRatio = customUptimeRatio,
|
||||
ShowAlerts = showAlerts,
|
||||
ShowLog = showLog
|
||||
ShowAlerts = includeDetails,
|
||||
ShowLog = includeDetails,
|
||||
ShowResponseTimes = includeDetails,
|
||||
ResponseTimeAverage = responseTimesAverage
|
||||
};
|
||||
|
||||
return Get<RetrieveResponse>("getMonitors", parameters.Convert()).Items;
|
||||
RetrieveResponse response = await Request<RetrieveResponse>("getMonitors", cancellationToken, parameters.Convert());
|
||||
|
||||
return response.Items ?? new List<Models.Monitor>();
|
||||
}
|
||||
|
||||
|
||||
@@ -38,17 +52,24 @@ namespace UptimeSharp
|
||||
/// Retrieves a monitor from UptimeRobot
|
||||
/// </summary>
|
||||
/// <param name="monitorId">a specific monitor ID</param>
|
||||
/// <param name="includeDetails">if set to <c>true</c> [include details (log, alerts and response times)].</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>
|
||||
/// <param name="responseTimesAverage">The response times average in minutes, which is used as the calculation base for the response times.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>
|
||||
/// The Monitor
|
||||
/// </returns>
|
||||
public Monitor GetMonitor(int monitorId, float[] customUptimeRatio = null, bool showLog = false, bool showAlerts = true)
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
public async Task<Models.Monitor> GetMonitor(
|
||||
string monitorId,
|
||||
bool includeDetails = true,
|
||||
float[] customUptimeRatio = null,
|
||||
int responseTimesAverage = 0,
|
||||
CancellationToken cancellationToken = default(CancellationToken))
|
||||
{
|
||||
List<Monitor> monitors = GetMonitors(new int[] { monitorId }, customUptimeRatio, showLog, showAlerts);
|
||||
List<Models.Monitor> monitors = await GetMonitors(new string[] { monitorId }, includeDetails, customUptimeRatio, responseTimesAverage, cancellationToken);
|
||||
|
||||
return monitors.ToArray().Length > 0 ? monitors[0] : null;
|
||||
return monitors != null && monitors.Count > 0 ? monitors[0] : null;
|
||||
}
|
||||
|
||||
|
||||
@@ -59,9 +80,13 @@ namespace UptimeSharp
|
||||
/// <returns>
|
||||
/// Success state
|
||||
/// </returns>
|
||||
public bool DeleteMonitor(int monitorId)
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
public async Task<bool> DeleteMonitor(string monitorId, CancellationToken cancellationToken = default(CancellationToken))
|
||||
{
|
||||
return Get<DefaultResponse>("deleteMonitor", Parameter("monitorID", monitorId)).Status;
|
||||
return (await Request<DefaultResponse>("deleteMonitor", cancellationToken, new Dictionary<string, string>()
|
||||
{
|
||||
{ "monitorID", monitorId }
|
||||
})).Success;
|
||||
}
|
||||
|
||||
|
||||
@@ -72,9 +97,10 @@ namespace UptimeSharp
|
||||
/// <returns>
|
||||
/// Success state
|
||||
/// </returns>
|
||||
public bool DeleteMonitor(Monitor monitor)
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
public async Task<bool> DeleteMonitor(Models.Monitor monitor, CancellationToken cancellationToken = default(CancellationToken))
|
||||
{
|
||||
return DeleteMonitor(monitor.ID);
|
||||
return await DeleteMonitor(monitor.ID, cancellationToken);
|
||||
}
|
||||
|
||||
|
||||
@@ -82,27 +108,38 @@ namespace UptimeSharp
|
||||
/// 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="target">The URI or IP to watch.</param>
|
||||
/// <param name="type">The type of the monitor.</param>
|
||||
/// <param name="subtype">The subtype of the port.</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">A ID list of existing alerts to notify.</param>
|
||||
/// <param name="HTTPPassword">The HTTP password.</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>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>
|
||||
/// Success state
|
||||
/// New Monitor (without details)
|
||||
/// </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,
|
||||
int[] alerts = null, string HTTPPassword = null, string HTTPUsername = null)
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
public async Task<Models.Monitor> AddMonitor(
|
||||
string name,
|
||||
string target,
|
||||
Models.Type type = Models.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,
|
||||
CancellationToken cancellationToken = default(CancellationToken))
|
||||
{
|
||||
|
||||
MonitorParameters parameters = new MonitorParameters()
|
||||
{
|
||||
Name = name,
|
||||
Uri = uri,
|
||||
Target = target,
|
||||
Type = type,
|
||||
Subtype = subtype,
|
||||
Port = port,
|
||||
@@ -113,7 +150,22 @@ namespace UptimeSharp
|
||||
HTTPUsername = HTTPUsername
|
||||
};
|
||||
|
||||
return Get<DefaultResponse>("newMonitor", parameters.Convert()).Status;
|
||||
Models.Monitor monitor = (await Request<AddMonitorResponse>("newMonitor", cancellationToken, parameters.Convert())).Monitor;
|
||||
|
||||
if (monitor != null)
|
||||
{
|
||||
monitor.Name = name;
|
||||
monitor.Target = target;
|
||||
monitor.Type = type;
|
||||
monitor.Subtype = subtype;
|
||||
monitor.Port = port;
|
||||
monitor.KeywordType = keywordType;
|
||||
monitor.KeywordValue = keywordValue;
|
||||
monitor.HTTPPassword = HTTPPassword;
|
||||
monitor.HTTPUsername = HTTPUsername;
|
||||
}
|
||||
|
||||
return monitor;
|
||||
}
|
||||
|
||||
|
||||
@@ -121,22 +173,24 @@ namespace UptimeSharp
|
||||
/// Edits a monitor.
|
||||
/// </summary>
|
||||
/// <param name="monitor">The monitor.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>
|
||||
/// Success state
|
||||
/// </returns>
|
||||
public bool ModifyMonitor(Monitor monitor)
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
public async Task<bool> ModifyMonitor(Models.Monitor monitor, CancellationToken cancellationToken = default(CancellationToken))
|
||||
{
|
||||
List<int> alerts = null;
|
||||
List<string> alerts = null;
|
||||
|
||||
if (monitor.Alerts != null)
|
||||
{
|
||||
monitor.Alerts.ForEach(item => alerts.Add((int)item.ID));
|
||||
alerts = monitor.Alerts.Select(item => item.ID).ToList();
|
||||
}
|
||||
|
||||
MonitorParameters parameters = new MonitorParameters()
|
||||
{
|
||||
Name = monitor.Name,
|
||||
Uri = monitor.UriString != null ? monitor.UriString : null,
|
||||
Target = monitor.Target != null ? monitor.Target : null,
|
||||
Port = monitor.Port,
|
||||
HTTPPassword = monitor.HTTPPassword,
|
||||
HTTPUsername = monitor.HTTPUsername,
|
||||
@@ -146,17 +200,81 @@ namespace UptimeSharp
|
||||
Alerts = alerts != null ? alerts.ToArray() : null
|
||||
};
|
||||
|
||||
List<Parameter> paramList = parameters.Convert();
|
||||
Dictionary<string, string> paramList = parameters.Convert();
|
||||
|
||||
// fix bad behaviour in API if no subtype is submitted
|
||||
if(parameters.Subtype == Subtype.Unknown)
|
||||
if (parameters.Subtype == Subtype.Unknown)
|
||||
{
|
||||
paramList.Add(Parameter("monitorSubType", 0));
|
||||
paramList.Add("monitorSubType", "0");
|
||||
}
|
||||
|
||||
paramList.Add(Parameter("monitorID", monitor.ID));
|
||||
paramList.Add("monitorID", monitor.ID.ToString());
|
||||
|
||||
return Get<DefaultResponse>("editMonitor", paramList).Status;
|
||||
return (await Request<DefaultResponse>("editMonitor", cancellationToken, paramList)).Success;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Pause a monitor
|
||||
/// </summary>
|
||||
/// <param name="monitorId">a specific monitor ID</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>
|
||||
/// Success state
|
||||
/// </returns>
|
||||
/// <exception cref="System.NotImplementedException">not available yet</exception>
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
public async Task<bool> PauseMonitor(string monitorId, CancellationToken cancellationToken = default(CancellationToken))
|
||||
{
|
||||
throw new NotImplementedException("not available yet");
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Pause a monitor
|
||||
/// </summary>
|
||||
/// <param name="monitor">The monitor.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>
|
||||
/// Success state
|
||||
/// </returns>
|
||||
/// <exception cref="System.NotImplementedException">not available yet</exception>
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
public async Task<bool> PauseMonitor(Models.Monitor monitor, CancellationToken cancellationToken = default(CancellationToken))
|
||||
{
|
||||
return await PauseMonitor(monitor.ID, cancellationToken);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Resume a monitor
|
||||
/// </summary>
|
||||
/// <param name="monitorId">a specific monitor ID</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>
|
||||
/// Success state
|
||||
/// </returns>
|
||||
/// <exception cref="System.NotImplementedException">not available yet</exception>
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
public async Task<bool> ResumeMonitor(string monitorId, CancellationToken cancellationToken = default(CancellationToken))
|
||||
{
|
||||
throw new NotImplementedException("not available yet");
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Resume a monitor
|
||||
/// </summary>
|
||||
/// <param name="monitor">The monitor.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>
|
||||
/// Success state
|
||||
/// </returns>
|
||||
/// <exception cref="System.NotImplementedException">not available yet</exception>
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
public async Task<bool> ResumeMonitor(Models.Monitor monitor, CancellationToken cancellationToken = default(CancellationToken))
|
||||
{
|
||||
return await ResumeMonitor(monitor.ID, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<Weavers>
|
||||
<PropertyChanged />
|
||||
</Weavers>
|
||||
@@ -0,0 +1,270 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using UptimeSharp.Models;
|
||||
|
||||
namespace UptimeSharp
|
||||
{
|
||||
public interface IUptimeClient
|
||||
{
|
||||
/// <summary>
|
||||
/// Accessor for the UptimeRebot API key
|
||||
/// see: http://www.uptimerobot.com/api
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The API key.
|
||||
/// </value>
|
||||
string ApiKey { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Action which is executed before every request
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The pre request callback.
|
||||
/// </value>
|
||||
Action<string> PreRequest { get; set; }
|
||||
|
||||
|
||||
#region Monitors
|
||||
/// <summary>
|
||||
/// Retrieves specified monitors from UptimeRobot
|
||||
/// </summary>
|
||||
/// <param name="monitorIDs">The monitor IDs.</param>
|
||||
/// <param name="includeDetails">if set to <c>true</c> [include details (log, alerts and response times)].</param>
|
||||
/// <param name="customUptimeRatio">The custom uptime ratio.</param>
|
||||
/// <param name="responseTimesAverage">The response times average in minutes, which is used as the calculation base for the response times.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>
|
||||
/// Monitor List
|
||||
/// </returns>
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
Task<List<Models.Monitor>> GetMonitors(
|
||||
string[] monitorIDs = null,
|
||||
bool includeDetails = true,
|
||||
float[] customUptimeRatio = null,
|
||||
int responseTimesAverage = 0,
|
||||
CancellationToken cancellationToken = default(CancellationToken));
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves a monitor from UptimeRobot
|
||||
/// </summary>
|
||||
/// <param name="monitorId">a specific monitor ID</param>
|
||||
/// <param name="includeDetails">if set to <c>true</c> [include details (log, alerts and response times)].</param>
|
||||
/// <param name="customUptimeRatio">The custom uptime ratio.</param>
|
||||
/// <param name="responseTimesAverage">The response times average in minutes, which is used as the calculation base for the response times.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>
|
||||
/// The Monitor
|
||||
/// </returns>
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
Task<Models.Monitor> GetMonitor(
|
||||
string monitorId,
|
||||
bool includeDetails = true,
|
||||
float[] customUptimeRatio = null,
|
||||
int responseTimesAverage = 0,
|
||||
CancellationToken cancellationToken = default(CancellationToken));
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a monitor
|
||||
/// </summary>
|
||||
/// <param name="monitorId">a specific monitor ID</param>
|
||||
/// <returns>
|
||||
/// Success state
|
||||
/// </returns>
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
Task<bool> DeleteMonitor(string monitorId, CancellationToken cancellationToken = default(CancellationToken));
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a monitor
|
||||
/// </summary>
|
||||
/// <param name="monitor">The monitor.</param>
|
||||
/// <returns>
|
||||
/// Success state
|
||||
/// </returns>
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
Task<bool> DeleteMonitor(Models.Monitor monitor, CancellationToken cancellationToken = default(CancellationToken));
|
||||
|
||||
/// <summary>
|
||||
/// Creates a monitor.
|
||||
/// </summary>
|
||||
/// <param name="name">The name of the new monitor.</param>
|
||||
/// <param name="target">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>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>
|
||||
/// New Monitor (without details)
|
||||
/// </returns>
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
Task<Models.Monitor> AddMonitor(
|
||||
string name,
|
||||
string target,
|
||||
Models.Type type = Models.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,
|
||||
CancellationToken cancellationToken = default(CancellationToken));
|
||||
|
||||
/// <summary>
|
||||
/// Edits a monitor.
|
||||
/// </summary>
|
||||
/// <param name="monitor">The monitor.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>
|
||||
/// Success state
|
||||
/// </returns>
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
Task<bool> ModifyMonitor(Models.Monitor monitor, CancellationToken cancellationToken = default(CancellationToken));
|
||||
|
||||
/// <summary>
|
||||
/// Pause a monitor
|
||||
/// </summary>
|
||||
/// <param name="monitorId">a specific monitor ID</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>
|
||||
/// Success state
|
||||
/// </returns>
|
||||
/// <exception cref="System.NotImplementedException">not available yet</exception>
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
Task<bool> PauseMonitor(string monitorId, CancellationToken cancellationToken = default(CancellationToken));
|
||||
|
||||
/// <summary>
|
||||
/// Pause a monitor
|
||||
/// </summary>
|
||||
/// <param name="monitor">The monitor.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>
|
||||
/// Success state
|
||||
/// </returns>
|
||||
/// <exception cref="System.NotImplementedException">not available yet</exception>
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
Task<bool> PauseMonitor(Models.Monitor monitor, CancellationToken cancellationToken = default(CancellationToken));
|
||||
|
||||
/// <summary>
|
||||
/// Resume a monitor
|
||||
/// </summary>
|
||||
/// <param name="monitorId">a specific monitor ID</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>
|
||||
/// Success state
|
||||
/// </returns>
|
||||
/// <exception cref="System.NotImplementedException">not available yet</exception>
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
Task<bool> ResumeMonitor(string monitorId, CancellationToken cancellationToken = default(CancellationToken));
|
||||
|
||||
/// <summary>
|
||||
/// Resume a monitor
|
||||
/// </summary>
|
||||
/// <param name="monitor">The monitor.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>
|
||||
/// Success state
|
||||
/// </returns>
|
||||
/// <exception cref="System.NotImplementedException">not available yet</exception>
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
Task<bool> ResumeMonitor(Models.Monitor monitor, CancellationToken cancellationToken = default(CancellationToken));
|
||||
#endregion
|
||||
|
||||
|
||||
#region Alerts
|
||||
/// <summary>
|
||||
/// Retrieves alerts from UptimeRobot
|
||||
/// </summary>
|
||||
/// <param name="alertIDs">Retrieve specified alert contacts by supplying IDs for them.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
Task<List<Alert>> GetAlerts(string[] alertIDs = null, CancellationToken cancellationToken = default(CancellationToken));
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves an alert from UptimeRobot
|
||||
/// </summary>
|
||||
/// <param name="alertID">The alertID.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
Task<Alert> GetAlert(string alertID, CancellationToken cancellationToken = default(CancellationToken));
|
||||
|
||||
/// <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>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="UptimeSharpException">AlertType.SMS and AlertType.Twitter are not supported by the UptimeRobot API</exception>
|
||||
Task<Alert> AddAlert(AlertType type, string value, CancellationToken cancellationToken = default(CancellationToken));
|
||||
|
||||
/// <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>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
Task<Alert> AddAlert(Alert alert, CancellationToken cancellationToken = default(CancellationToken));
|
||||
|
||||
/// <summary>
|
||||
/// Removes an alert.
|
||||
/// </summary>
|
||||
/// <param name="alertID">The alert ID.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
Task<bool> DeleteAlert(string alertID, CancellationToken cancellationToken = default(CancellationToken));
|
||||
|
||||
/// <summary>
|
||||
/// Removes an alert.
|
||||
/// </summary>
|
||||
/// <param name="alert">The alert.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="UptimeSharpException"></exception>
|
||||
Task<bool> DeleteAlert(Alert alert, CancellationToken cancellationToken = default(CancellationToken));
|
||||
#endregion
|
||||
|
||||
|
||||
#region Account
|
||||
/// <summary>
|
||||
/// Determines whether a e-mail is available.
|
||||
/// </summary>
|
||||
/// <param name="email">The email.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="System.ArgumentNullException">Please provide an e-mail address</exception>
|
||||
/// <exception cref="System.ArgumentException">Please provide a valid e-mail address</exception>
|
||||
Task<bool> IsEmailAvailable(string email, CancellationToken cancellationToken = default(CancellationToken));
|
||||
|
||||
/// <summary>
|
||||
/// Registers the account.
|
||||
/// </summary>
|
||||
/// <param name="fullName">The full name (min. 3 chars).</param>
|
||||
/// <param name="email">The email address.</param>
|
||||
/// <param name="password">The password (min. 6 chars).</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="System.ArgumentNullException">Please provide all parameters (username, email and password)</exception>
|
||||
/// <exception cref="System.ArgumentException">
|
||||
/// Please provide a valid e-mail address
|
||||
/// or
|
||||
/// Name must be at least 3 characters
|
||||
/// or
|
||||
/// Username must be at least 6 characters
|
||||
/// </exception>
|
||||
Task<bool> RegisterAccount(string fullName, string email, string password, CancellationToken cancellationToken = default(CancellationToken));
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+35
-12
@@ -1,11 +1,15 @@
|
||||
using System.Runtime.Serialization;
|
||||
using Newtonsoft.Json;
|
||||
using PropertyChanged;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace UptimeSharp.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// The Alert Model
|
||||
/// </summary>
|
||||
[DataContract]
|
||||
[JsonObject]
|
||||
[ImplementPropertyChanged]
|
||||
[DebuggerDisplay("Type = {Type}, Value = {Value}")]
|
||||
public class Alert
|
||||
{
|
||||
/// <summary>
|
||||
@@ -14,8 +18,8 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The ID.
|
||||
/// </value>
|
||||
[DataMember(Name = "id")]
|
||||
public int ID { get; set; }
|
||||
[JsonProperty("id")]
|
||||
public string ID { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the alert type.
|
||||
@@ -23,7 +27,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The name.
|
||||
/// </value>
|
||||
[DataMember(Name = "type")]
|
||||
[JsonProperty("type")]
|
||||
public AlertType Type { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -32,7 +36,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The status.
|
||||
/// </value>
|
||||
[DataMember(Name = "status")]
|
||||
[JsonProperty("status")]
|
||||
public AlertStatus Status { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -41,8 +45,23 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The value - Phone Number / E-Mail / Account
|
||||
/// </value>
|
||||
[DataMember(Name = "value")]
|
||||
[JsonProperty("value")]
|
||||
public string Value { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether [is main alert].
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <c>true</c> if [is main alert]; otherwise, <c>false</c>.
|
||||
/// </value>
|
||||
[JsonIgnore]
|
||||
public bool IsMainAlert
|
||||
{
|
||||
get
|
||||
{
|
||||
return ID.StartsWith("0");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -52,6 +71,10 @@ namespace UptimeSharp.Models
|
||||
/// </summary>
|
||||
public enum AlertType
|
||||
{
|
||||
/// <summary>
|
||||
/// Unknown
|
||||
/// </summary>
|
||||
Unknown,
|
||||
/// <summary>
|
||||
/// SMS
|
||||
/// </summary>
|
||||
@@ -67,7 +90,11 @@ namespace UptimeSharp.Models
|
||||
/// <summary>
|
||||
/// Boxcar
|
||||
/// </summary>
|
||||
Boxcar = 4
|
||||
Boxcar = 4,
|
||||
/// <summary>
|
||||
/// Web Hook
|
||||
/// </summary>
|
||||
WebHook = 5
|
||||
}
|
||||
|
||||
|
||||
@@ -76,10 +103,6 @@ namespace UptimeSharp.Models
|
||||
/// </summary>
|
||||
public enum AlertStatus
|
||||
{
|
||||
/// <summary>
|
||||
/// Unknown
|
||||
/// </summary>
|
||||
Unknown,
|
||||
/// <summary>
|
||||
/// Not activated
|
||||
/// </summary>
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
using System;
|
||||
using Newtonsoft.Json;
|
||||
using PropertyChanged;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace UptimeSharp.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// The Log Model
|
||||
/// </summary>
|
||||
[DataContract]
|
||||
[JsonObject]
|
||||
[ImplementPropertyChanged]
|
||||
public class Log
|
||||
{
|
||||
/// <summary>
|
||||
@@ -16,7 +18,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The type.
|
||||
/// </value>
|
||||
[DataMember(Name = "type")]
|
||||
[JsonProperty("type")]
|
||||
public LogType Type { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -25,7 +27,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The date.
|
||||
/// </value>
|
||||
[DataMember(Name = "datetime")]
|
||||
[JsonProperty("datetime")]
|
||||
public DateTime Date { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -34,7 +36,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The alert contacts.
|
||||
/// </value>
|
||||
[DataMember(Name = "alertcontact")]
|
||||
[JsonProperty("alertcontact")]
|
||||
public List<Alert> Alerts { get; set; }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,18 +1,16 @@
|
||||
using System;
|
||||
using Newtonsoft.Json;
|
||||
using PropertyChanged;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Net;
|
||||
using ServiceStack.Text;
|
||||
using RestSharp;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace UptimeSharp.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// The Monitor Model implementation
|
||||
/// </summary>
|
||||
[DataContract]
|
||||
[JsonObject]
|
||||
[ImplementPropertyChanged]
|
||||
[DebuggerDisplay("Name = {Name}, Target = {Target}")]
|
||||
public class Monitor
|
||||
{
|
||||
/// <summary>
|
||||
@@ -21,8 +19,8 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The ID.
|
||||
/// </value>
|
||||
[DataMember(Name = "id")]
|
||||
public int ID { get; set; }
|
||||
[JsonProperty("id")]
|
||||
public string ID { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name.
|
||||
@@ -30,41 +28,17 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The name.
|
||||
/// </value>
|
||||
[DataMember(Name = "friendlyname")]
|
||||
[JsonProperty("friendlyname")]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the URI.
|
||||
/// Gets the target URI/IP.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The URI.
|
||||
/// The target URI/IP.
|
||||
/// </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;
|
||||
}
|
||||
}
|
||||
[JsonProperty("url")]
|
||||
public string Target { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the port.
|
||||
@@ -73,7 +47,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The port.
|
||||
/// </value>
|
||||
[DataMember(Name = "port")]
|
||||
[JsonProperty("port")]
|
||||
public int? Port { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -82,7 +56,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// Uptime ratio of the monitor calculated since the monitor is created.
|
||||
/// </value>
|
||||
[DataMember(Name = "alltimeuptimeratio")]
|
||||
[JsonProperty("alltimeuptimeratio")]
|
||||
public float Uptime { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -91,7 +65,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The uptime ratio of the monitor for the given periods
|
||||
/// </value>
|
||||
[DataMember(Name = "customuptimeratio")]
|
||||
[JsonProperty("customuptimeratio")]
|
||||
public float? UptimeCustom { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -100,7 +74,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The HTTP password.
|
||||
/// </value>
|
||||
[DataMember(Name = "httppassword")]
|
||||
[JsonProperty("httppassword")]
|
||||
public string HTTPPassword { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -109,7 +83,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The HTTP username.
|
||||
/// </value>
|
||||
[DataMember(Name = "httpusername")]
|
||||
[JsonProperty("httpusername")]
|
||||
public string HTTPUsername { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -118,7 +92,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The type of the keyword.
|
||||
/// </value>
|
||||
[DataMember(Name = "keywordtype")]
|
||||
[JsonProperty("keywordtype")]
|
||||
public KeywordType KeywordType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -127,7 +101,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The keyword value.
|
||||
/// </value>
|
||||
[DataMember(Name = "keywordvalue")]
|
||||
[JsonProperty("keywordvalue")]
|
||||
public string KeywordValue { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -136,7 +110,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The status.
|
||||
/// </value>
|
||||
[DataMember(Name = "status")]
|
||||
[JsonProperty("status")]
|
||||
public Status Status { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -145,7 +119,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The type.
|
||||
/// </value>
|
||||
[DataMember(Name = "type")]
|
||||
[JsonProperty("type")]
|
||||
public Type Type { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -154,7 +128,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The subtype.
|
||||
/// </value>
|
||||
[DataMember(Name = "subtype")]
|
||||
[JsonProperty("subtype")]
|
||||
public Subtype Subtype { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -163,7 +137,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The alert contacts.
|
||||
/// </value>
|
||||
[DataMember(Name = "alertcontact")]
|
||||
[JsonProperty("alertcontact")]
|
||||
public List<Alert> Alerts { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -172,8 +146,17 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The log with dates and associated alert contacts.
|
||||
/// </value>
|
||||
[DataMember(Name = "log")]
|
||||
[JsonProperty("log")]
|
||||
public List<Log> Log { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the response times.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The response times.
|
||||
/// </value>
|
||||
[JsonProperty("responsetime")]
|
||||
public List<ResponseTime> ResponseTimes { get; set; }
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
using RestSharp;
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace UptimeSharp.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// All parameters which can be passed for monitor modifications
|
||||
/// </summary>
|
||||
internal class MonitorParameters
|
||||
[DataContract]
|
||||
internal class MonitorParameters : Parameters
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the name.
|
||||
@@ -15,6 +16,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The name.
|
||||
/// </value>
|
||||
[DataMember(Name = "monitorFriendlyName")]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -23,7 +25,8 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The URI.
|
||||
/// </value>
|
||||
public string Uri { get; set; }
|
||||
[DataMember(Name = "monitorURL")]
|
||||
public string Target { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the port.
|
||||
@@ -32,6 +35,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The port.
|
||||
/// </value>
|
||||
[DataMember(Name = "monitorPort")]
|
||||
public int? Port { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -40,6 +44,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The HTTP password.
|
||||
/// </value>
|
||||
[DataMember(Name = "monitorHTTPPassword")]
|
||||
public string HTTPPassword { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -48,6 +53,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The HTTP username.
|
||||
/// </value>
|
||||
[DataMember(Name = "monitorHTTPUsername")]
|
||||
public string HTTPUsername { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -56,6 +62,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The type of the keyword.
|
||||
/// </value>
|
||||
[DataMember(Name = "monitorKeywordType")]
|
||||
public KeywordType KeywordType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -64,6 +71,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The keyword value.
|
||||
/// </value>
|
||||
[DataMember(Name = "monitorKeywordValue")]
|
||||
public string KeywordValue { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -72,6 +80,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The type.
|
||||
/// </value>
|
||||
[DataMember(Name = "monitorType")]
|
||||
public Type Type { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -80,6 +89,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The subtype.
|
||||
/// </value>
|
||||
[DataMember(Name = "monitorSubType")]
|
||||
public Subtype Subtype { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -88,51 +98,54 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The alert contacts.
|
||||
/// </value>
|
||||
public int[] Alerts { get; set; }
|
||||
|
||||
[DataMember(Name = "monitorAlertContacts")]
|
||||
public string[] Alerts { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Converts this instance to a parameter list.
|
||||
/// Converts an object to a list of HTTP Get parameters.
|
||||
/// </summary>
|
||||
/// <returns>Parameter list</returns>
|
||||
public List<Parameter> Convert()
|
||||
/// <returns></returns>
|
||||
public Dictionary<string, string> Convert()
|
||||
{
|
||||
List<Parameter> parameters = new List<Parameter>();
|
||||
Dictionary<string, string> parameters = new Dictionary<string, string>();
|
||||
|
||||
parameters.Add(UptimeClient.Parameter("monitorFriendlyName", Name));
|
||||
parameters.Add(UptimeClient.Parameter("monitorURL", Uri));
|
||||
parameters.Add("monitorFriendlyName", Name);
|
||||
parameters.Add("monitorURL", Target);
|
||||
|
||||
if ((int)Type != 0)
|
||||
{
|
||||
parameters.Add(UptimeClient.Parameter("monitorType", (int)Type));
|
||||
parameters.Add("monitorType", ((int)Type).ToString());
|
||||
}
|
||||
|
||||
// special params for port listener
|
||||
if (Type == Type.Port && Subtype != Subtype.Unknown && Port.HasValue)
|
||||
if (Type == Type.Port && Subtype != Subtype.Unknown)
|
||||
{
|
||||
parameters.Add(UptimeClient.Parameter("monitorSubType", (int)Subtype));
|
||||
parameters.Add("monitorSubType", ((int)Subtype).ToString());
|
||||
|
||||
if (Subtype == Subtype.Custom)
|
||||
if (Subtype == Subtype.Custom && Port.HasValue)
|
||||
{
|
||||
parameters.Add(UptimeClient.Parameter("monitorPort", Port));
|
||||
parameters.Add("monitorPort", ((int)Port).ToString());
|
||||
}
|
||||
}
|
||||
|
||||
// keyword listener
|
||||
if (Type == Type.Keyword && !string.IsNullOrEmpty(KeywordValue))
|
||||
if (Type == Type.Keyword && !String.IsNullOrEmpty(KeywordValue))
|
||||
{
|
||||
parameters.Add(UptimeClient.Parameter("monitorKeywordType", (int)KeywordType));
|
||||
parameters.Add(UptimeClient.Parameter("monitorKeywordValue", KeywordValue));
|
||||
parameters.Add("monitorKeywordType", ((int)KeywordType).ToString());
|
||||
parameters.Add("monitorKeywordValue", KeywordValue);
|
||||
}
|
||||
|
||||
// HTTP basic auth credentials
|
||||
parameters.Add(UptimeClient.Parameter("monitorHTTPUsername", HTTPUsername));
|
||||
parameters.Add(UptimeClient.Parameter("monitorHTTPPassword", HTTPPassword));
|
||||
if (!String.IsNullOrEmpty(HTTPUsername))
|
||||
{
|
||||
parameters.Add("monitorHTTPUsername", HTTPUsername);
|
||||
parameters.Add("monitorHTTPPassword", HTTPPassword);
|
||||
}
|
||||
|
||||
// alert notifications
|
||||
if (Alerts != null && Alerts.Length > 0)
|
||||
{
|
||||
parameters.Add(UptimeClient.Parameter("monitorAlertContacts", string.Join("-", Alerts)));
|
||||
parameters.Add("monitorAlertContacts", String.Join("-", Alerts));
|
||||
}
|
||||
|
||||
return parameters;
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace UptimeSharp.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// Parameter
|
||||
/// </summary>
|
||||
internal class Parameters
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts an object to a list of HTTP Get parameters.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public Dictionary<string, string> Convert()
|
||||
{
|
||||
// store HTTP parameters here
|
||||
Dictionary<string, string> parameterDict = new Dictionary<string, string>();
|
||||
|
||||
// get object properties
|
||||
IEnumerable<MemberInfo> properties = this.GetType()
|
||||
.GetTypeInfo()
|
||||
.DeclaredMembers
|
||||
.Where(p => p.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(DataMemberAttribute)) != null);
|
||||
|
||||
// gather attributes of object
|
||||
foreach (MemberInfo memberInfo in properties)
|
||||
{
|
||||
DataMemberAttribute attribute = (DataMemberAttribute)memberInfo.GetCustomAttributes(typeof(DataMemberAttribute), false).FirstOrDefault();
|
||||
string name = attribute.Name ?? memberInfo.Name.ToLower();
|
||||
object value = null;
|
||||
|
||||
if (memberInfo is FieldInfo)
|
||||
{
|
||||
value = ((FieldInfo)memberInfo).GetValue(this);
|
||||
}
|
||||
else
|
||||
{
|
||||
value = ((PropertyInfo)memberInfo).GetValue(this, null);
|
||||
}
|
||||
|
||||
// invalid parameter
|
||||
if (value == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// empty array
|
||||
if (value is Array && (value as Array).Length == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// convert array to comma-seperated list
|
||||
else if (value is IEnumerable)
|
||||
{
|
||||
value = String.Join("-", ((IEnumerable)value).Cast<object>().Select(x => x.ToString()).ToArray());
|
||||
}
|
||||
|
||||
// convert booleans
|
||||
if (value is bool)
|
||||
{
|
||||
value = System.Convert.ToBoolean(value) ? "1" : "0";
|
||||
}
|
||||
|
||||
// convert DateTime to UNIX timestamp
|
||||
if (value is DateTime)
|
||||
{
|
||||
value = (int)((DateTime)value - new DateTime(1970, 1, 1)).TotalSeconds;
|
||||
}
|
||||
|
||||
if (value is Enum)
|
||||
{
|
||||
value = (int)value;
|
||||
}
|
||||
|
||||
parameterDict.Add(name, value.ToString());
|
||||
}
|
||||
|
||||
return parameterDict;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
using RestSharp;
|
||||
using System;
|
||||
|
||||
using System.Collections.Generic;
|
||||
|
||||
using System.Runtime.Serialization;
|
||||
namespace UptimeSharp.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// All parameters which can be passed for monitor retrieval
|
||||
/// </summary>
|
||||
internal class RetrieveParameters
|
||||
[DataContract]
|
||||
internal class RetrieveParameters : Parameters
|
||||
{
|
||||
/// <summary>
|
||||
/// List of monitor ids
|
||||
@@ -15,7 +15,8 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The monitors.
|
||||
/// </value>
|
||||
public int[] Monitors { get; set; }
|
||||
[DataMember(Name = "monitors")]
|
||||
public string[] Monitors { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Defines the number of days to calculate the uptime ratio
|
||||
@@ -23,6 +24,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The custom uptime ratio.
|
||||
/// </value>
|
||||
[DataMember(Name = "customUptimeRatio")]
|
||||
public float[] CustomUptimeRatio { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -31,6 +33,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The log bool.
|
||||
/// </value>
|
||||
[DataMember(Name = "logs")]
|
||||
public bool? ShowLog { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -39,34 +42,39 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The alert contacts bool.
|
||||
/// </value>
|
||||
[DataMember(Name = "showMonitorAlertContacts")]
|
||||
public bool? ShowAlerts { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Defines if the resonse times for each monitor will be returned
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The alert contacts bool.
|
||||
/// </value>
|
||||
[DataMember(Name = "responseTimes")]
|
||||
public bool? ShowResponseTimes { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Converts this instance to a parameter list.
|
||||
/// Gets or sets the response time interval in minutes.
|
||||
/// </summary>
|
||||
/// <returns>Parameter list</returns>
|
||||
public List<Parameter> Convert()
|
||||
/// <value>
|
||||
/// The response time interval.
|
||||
/// </value>
|
||||
[DataMember(Name = "responseTimesAverage")]
|
||||
public int? ResponseTimeAverage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Converts an object to a list of HTTP Get parameters.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public Dictionary<string, string> 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"));
|
||||
Dictionary<string, string> parameters = base.Convert();
|
||||
|
||||
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));
|
||||
parameters.Add("alertContacts", parameters["logs"]);
|
||||
parameters.Add("showTimezone", parameters["logs"]);
|
||||
}
|
||||
|
||||
return parameters;
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace UptimeSharp.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// Account Response
|
||||
/// </summary>
|
||||
[JsonObject]
|
||||
internal class AccountResponse : Response { }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace UptimeSharp.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// Add Alert Response
|
||||
/// </summary>
|
||||
[JsonObject]
|
||||
internal class AddAlertResponse : Response
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the alert.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The alert.
|
||||
/// </value>
|
||||
[JsonProperty("alertcontact")]
|
||||
public Alert Alert { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace UptimeSharp.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// Add Monitor Response
|
||||
/// </summary>
|
||||
[JsonObject]
|
||||
internal class AddMonitorResponse : Response
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the monitor.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The monitor.
|
||||
/// </value>
|
||||
[JsonProperty("monitor")]
|
||||
public Monitor Monitor { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.Serialization;
|
||||
using Newtonsoft.Json;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace UptimeSharp.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// Alert Response
|
||||
/// </summary>
|
||||
[DataContract]
|
||||
internal class AlertResponse : ResponseBase
|
||||
[JsonObject]
|
||||
internal class AlertResponse : Response
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the item dictionary.
|
||||
@@ -16,7 +16,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The item dictionary.
|
||||
/// </value>
|
||||
[DataMember(Name = "alertcontacts")]
|
||||
[JsonProperty("alertcontacts")]
|
||||
public Dictionary<string, List<Alert>> ItemDictionary { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -25,7 +25,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The items.
|
||||
/// </value>
|
||||
[IgnoreDataMember]
|
||||
[JsonIgnore]
|
||||
public List<Alert> Items
|
||||
{
|
||||
get
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.Serialization;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace UptimeSharp.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// Default Response
|
||||
/// </summary>
|
||||
[DataContract]
|
||||
internal class DefaultResponse : ResponseBase {}
|
||||
[JsonObject]
|
||||
internal class DefaultResponse : Response { }
|
||||
}
|
||||
|
||||
@@ -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; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace UptimeSharp.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// Base for Responses
|
||||
/// </summary>
|
||||
[JsonObject]
|
||||
internal class Response : IResponse
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the error code.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The error code.
|
||||
/// </value>
|
||||
[JsonProperty("id")]
|
||||
public string ErrorCode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the error message.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The error message.
|
||||
/// </value>
|
||||
[JsonProperty("message")]
|
||||
public string ErrorMessage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether this <see cref="Response"/> is status.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// "ok" or "fail"
|
||||
/// </value>
|
||||
[JsonProperty("stat")]
|
||||
public string RawStatus { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 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 Success
|
||||
{
|
||||
get { return RawStatus == "ok"; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.Serialization;
|
||||
using Newtonsoft.Json;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace UptimeSharp.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// Monitor Response
|
||||
/// </summary>
|
||||
[DataContract]
|
||||
internal class RetrieveResponse : ResponseBase
|
||||
[JsonObject]
|
||||
internal class RetrieveResponse : Response
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the item dictionary.
|
||||
@@ -16,7 +16,7 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The item dictionary.
|
||||
/// </value>
|
||||
[DataMember(Name = "monitors")]
|
||||
[JsonProperty("monitors")]
|
||||
public Dictionary<string, List<Monitor>> ItemDictionary { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -25,12 +25,12 @@ namespace UptimeSharp.Models
|
||||
/// <value>
|
||||
/// The items.
|
||||
/// </value>
|
||||
[IgnoreDataMember]
|
||||
[JsonIgnore]
|
||||
public List<Monitor> Items
|
||||
{
|
||||
get
|
||||
{
|
||||
return ItemDictionary["monitor"];
|
||||
return ItemDictionary != null ? ItemDictionary["monitor"] : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
|
||||
namespace UptimeSharp.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// The Response Time POCO
|
||||
/// </summary>
|
||||
[JsonObject]
|
||||
public class ResponseTime
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the response time in milliseconds.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The type.
|
||||
/// </value>
|
||||
[JsonProperty("value")]
|
||||
public int Time { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the date time, when the response time was saved.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The date.
|
||||
/// </value>
|
||||
[JsonProperty("datetime")]
|
||||
public DateTime Date { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,36 +1,26 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// 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: AssemblyDescription("UptimeSharp is a .NET portable class library that integrates the UptimeRobot API")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("cee")]
|
||||
[assembly: AssemblyProduct("UptimeSharp")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2013")]
|
||||
[assembly: AssemblyCopyright("Copyright © cee 2014")]
|
||||
[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
|
||||
// Minor Version
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
// You can specify all the values or you can default the Build and Revision Numbers
|
||||
// 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")]
|
||||
[assembly: AssemblyVersion("3.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("3.0.0.0")]
|
||||
+251
-119
@@ -1,19 +1,41 @@
|
||||
using RestSharp;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using UptimeSharp.Models;
|
||||
|
||||
namespace UptimeSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// UptimeClient
|
||||
/// </summary>
|
||||
public partial class UptimeClient
|
||||
public partial class UptimeClient : IUptimeClient
|
||||
{
|
||||
/// <summary>
|
||||
/// REST client used for the API communication
|
||||
/// </summary>
|
||||
protected readonly RestClient _restClient;
|
||||
protected readonly HttpClient _restClient;
|
||||
|
||||
/// <summary>
|
||||
/// REST client used for the account communication
|
||||
/// </summary>
|
||||
protected readonly HttpClient _accountClient;
|
||||
|
||||
/// <summary>
|
||||
/// Caches HTTP headers from last response
|
||||
/// </summary>
|
||||
private HttpResponseHeaders lastHeaders;
|
||||
|
||||
/// <summary>
|
||||
/// Caches JSON data from last response
|
||||
/// </summary>
|
||||
public string lastResponseData;
|
||||
|
||||
/// <summary>
|
||||
/// The base URL for the UptimeRobot API
|
||||
@@ -21,126 +43,241 @@ namespace UptimeSharp
|
||||
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
|
||||
/// The account base URL for the UptimeRobot API
|
||||
/// Does not use the official API endpoint
|
||||
/// </summary>
|
||||
protected static Uri accountBaseUri = new Uri("http://uptimerobot.com/inc/dml/userDML.php");
|
||||
|
||||
/// <summary>
|
||||
/// Accessor for the UptimeRebot API key
|
||||
/// see: http://www.uptimerobot.com/api
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The API key.
|
||||
/// </value>
|
||||
public string ApiKey { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Returns all associated data from the last request
|
||||
/// Action which is executed before every request
|
||||
/// </summary>
|
||||
public IRestResponse LastRequestData { get; private set; }
|
||||
/// <value>
|
||||
/// The pre request callback.
|
||||
/// </value>
|
||||
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>
|
||||
/// <param name="apiKey">The API key</param>
|
||||
public UptimeClient(string apiKey)
|
||||
/// <param name="handler">The HttpMessage handler.</param>
|
||||
/// <param name="timeout">Request timeout (in seconds).</param>
|
||||
public UptimeClient(string apiKey, HttpMessageHandler handler = null, int? timeout = null)
|
||||
{
|
||||
// assign public properties
|
||||
ApiKey = apiKey;
|
||||
|
||||
// initialize REST client
|
||||
_restClient = new RestClient(baseUri.ToString());
|
||||
_restClient = new HttpClient(handler ?? new HttpClientHandler()
|
||||
{
|
||||
AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
|
||||
});
|
||||
_accountClient = new HttpClient(handler ?? new HttpClientHandler()
|
||||
{
|
||||
AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
|
||||
});
|
||||
|
||||
// add default parameters to each request
|
||||
_restClient.AddDefaultParameter("apiKey", ApiKey);
|
||||
if (timeout.HasValue)
|
||||
{
|
||||
_restClient.Timeout = TimeSpan.FromSeconds(timeout.Value);
|
||||
_accountClient.Timeout = TimeSpan.FromSeconds(timeout.Value);
|
||||
}
|
||||
|
||||
// defines the response format (according to the UptimeRobot docs)
|
||||
_restClient.AddDefaultParameter("format", "json");
|
||||
_restClient.BaseAddress = baseUri;
|
||||
_accountClient.BaseAddress = accountBaseUri;
|
||||
|
||||
// defines the response format
|
||||
_restClient.DefaultRequestHeaders.Add("Accept", "application/json");
|
||||
_accountClient.DefaultRequestHeaders.Add("Accept", "application/json");
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Fetches a typed resource
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="method">Requested method (appended to base path)</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <param name="parameters">Additional POST parameters</param>
|
||||
/// <param name="isAccountRequest">if set to <c>true</c> [is account request].</param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="UptimeSharpException">
|
||||
/// </exception>
|
||||
protected async Task<T> Request<T>(string method, CancellationToken cancellationToken, Dictionary<string, string> parameters = null) where T : class, new()
|
||||
{
|
||||
HttpRequestMessage request;
|
||||
HttpResponseMessage response = null;
|
||||
|
||||
if (parameters == null)
|
||||
{
|
||||
parameters = new Dictionary<string, string>();
|
||||
}
|
||||
|
||||
// add api key to each request
|
||||
parameters.Add("apiKey", ApiKey);
|
||||
|
||||
// require UptimeRobot to respond with JSON formatting
|
||||
parameters.Add("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");
|
||||
parameters.Add("noJsonCallback", "1");
|
||||
|
||||
// custom JSON deserializer (ServiceStack.Text)
|
||||
_restClient.AddHandler("application/json", new JsonDeserializer());
|
||||
IEnumerable<string> paramEnumerable = parameters.Where(item => !String.IsNullOrEmpty(item.Value)).Select(item => Uri.EscapeDataString(item.Key) + "=" + Uri.EscapeDataString(item.Value));
|
||||
|
||||
// add custom deserialization lambdas
|
||||
JsonDeserializer.AddCustomDeserialization();
|
||||
}
|
||||
// content of the request
|
||||
request = new HttpRequestMessage(HttpMethod.Get, method + "?" + String.Join("&", paramEnumerable));
|
||||
|
||||
|
||||
/// <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(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)
|
||||
// call pre request action
|
||||
if (PreRequest != null)
|
||||
{
|
||||
parameters.ForEach(
|
||||
param => {
|
||||
if(param.Value != null)
|
||||
{
|
||||
request.AddParameter(param);
|
||||
}
|
||||
}
|
||||
);
|
||||
PreRequest(method);
|
||||
}
|
||||
|
||||
// do the request
|
||||
return Request<T>(request);
|
||||
// make async request
|
||||
try
|
||||
{
|
||||
response = await _restClient.SendAsync(request, cancellationToken);
|
||||
}
|
||||
catch (HttpRequestException exc)
|
||||
{
|
||||
throw new UptimeSharpException(exc.Message, exc);
|
||||
}
|
||||
|
||||
// HTTP error
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
throw new UptimeSharpException("Request Exception: {0} (Code: {1})", response.ReasonPhrase, response.StatusCode.ToString());
|
||||
}
|
||||
|
||||
// cache headers
|
||||
lastHeaders = response.Headers;
|
||||
|
||||
// read response
|
||||
string responseString = await response.Content.ReadAsStringAsync();
|
||||
T parsedResponse;
|
||||
|
||||
// fix buggy response by uptimerobot óÒ
|
||||
if (!String.IsNullOrEmpty(responseString))
|
||||
{
|
||||
responseString = responseString
|
||||
.Replace("}{", "},{") // nice one
|
||||
.Replace(",]", ""); // ok, this is a bummer!
|
||||
}
|
||||
|
||||
// cache response
|
||||
lastResponseData = responseString;
|
||||
|
||||
// deserialize object
|
||||
parsedResponse = JsonConvert.DeserializeObject<T>(
|
||||
responseString,
|
||||
new JsonSerializerSettings
|
||||
{
|
||||
Error = (object sender, ErrorEventArgs args) =>
|
||||
{
|
||||
throw new UptimeSharpException(String.Format("Parse Exception: {0}", args.ErrorContext.Error.Message));
|
||||
},
|
||||
Converters =
|
||||
{
|
||||
new BoolConverter(),
|
||||
new UnixDateTimeConverter(),
|
||||
new UriConverter(),
|
||||
new EnumConverter()
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// validate response
|
||||
ValidateResponse(parsedResponse as IResponse);
|
||||
|
||||
return parsedResponse;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Fetches a typed resource
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="resource">Requested resource</param>
|
||||
/// <param name="parameter">The parameters.</param>
|
||||
/// <param name="action">The action.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <param name="parameters">Additional POST parameters</param>
|
||||
/// <param name="isPost">if set to <c>true</c> [is post].</param>
|
||||
/// <returns></returns>
|
||||
protected T Get<T>(string resource, params Parameter[] parameters) where T : class, new()
|
||||
/// <exception cref="UptimeSharpException">
|
||||
/// </exception>
|
||||
internal async Task<AccountResponse> AccountRequest(string action, CancellationToken cancellationToken, Dictionary<string, string> parameters = null, bool isPost = false)
|
||||
{
|
||||
List<Parameter> parameterList = new List<Parameter>();
|
||||
parameterList.AddRange(parameters);
|
||||
HttpRequestMessage request;
|
||||
HttpResponseMessage response = null;
|
||||
|
||||
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>
|
||||
public static Parameter Parameter(string name, object value)
|
||||
{
|
||||
return new Parameter()
|
||||
if (parameters == null)
|
||||
{
|
||||
Name = name,
|
||||
Value = value,
|
||||
Type = ParameterType.GetOrPost
|
||||
parameters = new Dictionary<string, string>();
|
||||
}
|
||||
|
||||
if (!isPost)
|
||||
{
|
||||
IEnumerable<string> paramEnumerable = parameters.Where(item => !String.IsNullOrEmpty(item.Value)).Select(item => Uri.EscapeDataString(item.Key) + "=" + Uri.EscapeDataString(item.Value));
|
||||
request = new HttpRequestMessage(HttpMethod.Get, "?action=" + Uri.EscapeDataString(action) + "&" + String.Join("&", paramEnumerable));
|
||||
}
|
||||
else
|
||||
{
|
||||
request = new HttpRequestMessage(HttpMethod.Post, "?action=" + Uri.EscapeDataString(action))
|
||||
{
|
||||
Content = new FormUrlEncodedContent(parameters.Where(item => !String.IsNullOrEmpty(item.Value)))
|
||||
};
|
||||
}
|
||||
|
||||
// call pre request action
|
||||
if (PreRequest != null)
|
||||
{
|
||||
PreRequest(action);
|
||||
}
|
||||
|
||||
// make async request
|
||||
try
|
||||
{
|
||||
response = await _accountClient.SendAsync(request, cancellationToken);
|
||||
}
|
||||
catch (HttpRequestException exc)
|
||||
{
|
||||
throw new UptimeSharpException(exc.Message, exc);
|
||||
}
|
||||
|
||||
// HTTP error
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
throw new UptimeSharpException("Request Exception: {0} (Code: {1})", response.ReasonPhrase, response.StatusCode.ToString());
|
||||
}
|
||||
|
||||
// cache headers
|
||||
lastHeaders = response.Headers;
|
||||
|
||||
// read response
|
||||
string responseString = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// cache response
|
||||
lastResponseData = responseString;
|
||||
|
||||
// deserialize object
|
||||
return new AccountResponse()
|
||||
{
|
||||
RawStatus = responseString == "true" ? "ok" : "fail"
|
||||
};
|
||||
}
|
||||
|
||||
@@ -150,46 +287,41 @@ namespace UptimeSharp
|
||||
/// </summary>
|
||||
/// <param name="response">The response.</param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="APIException">
|
||||
/// <exception cref="UptimeSharpException">
|
||||
/// Error retrieving response
|
||||
/// </exception>
|
||||
protected void ValidateResponse(IRestResponse response)
|
||||
internal void ValidateResponse(IResponse response)
|
||||
{
|
||||
if (response.StatusCode != HttpStatusCode.OK)
|
||||
// it's a success ;-)
|
||||
if (response.Success)
|
||||
{
|
||||
//Parameter error = response.Headers[1];
|
||||
//Parameter errorCode = response.Headers[2];
|
||||
|
||||
//string exceptionString = response.Content;
|
||||
|
||||
//bool isPocketError = error.Name == "X-Error";
|
||||
|
||||
//// update message to include pocket response data
|
||||
//if (isPocketError)
|
||||
//{
|
||||
// exceptionString = exceptionString + "\nPocketResponse: (" + errorCode.Value + ") " + error.Value;
|
||||
//}
|
||||
|
||||
// create exception
|
||||
APIException exception = new APIException("Request Exception", response.ErrorException);
|
||||
|
||||
//if (isPocketError)
|
||||
//{
|
||||
// // add custom pocket fields
|
||||
// exception.PocketError = error.Value.ToString();
|
||||
// exception.PocketErrorCode = Convert.ToInt32(errorCode.Value);
|
||||
|
||||
// // add to generic exception data
|
||||
// exception.Data.Add(error.Name, error.Value);
|
||||
// exception.Data.Add(errorCode.Name, errorCode.Value);
|
||||
//}
|
||||
|
||||
throw exception;
|
||||
return;
|
||||
}
|
||||
else if (response.ErrorException != null)
|
||||
|
||||
// don't raise exceptions for minor error codes
|
||||
if (!String.IsNullOrEmpty(response.ErrorCode) && successFailCodes.Contains(response.ErrorCode))
|
||||
{
|
||||
throw new APIException("Error retrieving response", response.ErrorException);
|
||||
return;
|
||||
}
|
||||
|
||||
// create exception
|
||||
UptimeSharpException exception = new UptimeSharpException(
|
||||
"UptimeRobot Exception: {0} (Code: {1})\n{2}",
|
||||
null,
|
||||
response.ErrorMessage,
|
||||
response.ErrorCode,
|
||||
"http://uptimerobot.com/api.asp#errorMessages"
|
||||
);
|
||||
|
||||
// add custom fields
|
||||
exception.Error = response.ErrorMessage;
|
||||
exception.ErrorCode = response.ErrorCode;
|
||||
|
||||
// add to generic exception data
|
||||
exception.Data.Add("Error", response.ErrorMessage);
|
||||
exception.Data.Add("ErrorCode", response.ErrorCode);
|
||||
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,18 +2,41 @@
|
||||
<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>
|
||||
<MinimumVisualStudioVersion>11.0</MinimumVisualStudioVersion>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{AF900ACF-DC2A-40AC-9614-B7C8C12E114C}</ProjectGuid>
|
||||
<ProjectGuid>{EC1E656D-4966-499A-9EDD-9DB56137BF62}</ProjectGuid>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>UptimeSharp</RootNamespace>
|
||||
<AssemblyName>UptimeSharp</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
|
||||
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
|
||||
<TargetFrameworkProfile>Profile259</TargetFrameworkProfile>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<ProjectTypeGuids>{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
|
||||
<FileUpgradeFlags>
|
||||
</FileUpgradeFlags>
|
||||
<UpgradeBackupLocation>
|
||||
</UpgradeBackupLocation>
|
||||
<OldToolsVersion>4.0</OldToolsVersion>
|
||||
<PublishUrl>publish\</PublishUrl>
|
||||
<Install>true</Install>
|
||||
<InstallFrom>Disk</InstallFrom>
|
||||
<UpdateEnabled>false</UpdateEnabled>
|
||||
<UpdateMode>Foreground</UpdateMode>
|
||||
<UpdateInterval>7</UpdateInterval>
|
||||
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
|
||||
<UpdatePeriodically>false</UpdatePeriodically>
|
||||
<UpdateRequired>false</UpdateRequired>
|
||||
<MapFileExtensions>true</MapFileExtensions>
|
||||
<ApplicationRevision>0</ApplicationRevision>
|
||||
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
|
||||
<IsWebBootstrapper>false</IsWebBootstrapper>
|
||||
<UseApplicationTrust>false</UseApplicationTrust>
|
||||
<BootstrapperEnabled>true</BootstrapperEnabled>
|
||||
<NuGetPackageImportStamp>f5b16e91</NuGetPackageImportStamp>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
@@ -23,7 +46,6 @@
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
@@ -31,47 +53,87 @@
|
||||
<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" />
|
||||
<!-- A reference to the entire .NET Framework is automatically included -->
|
||||
<None Include="packages.config" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="APIException.cs" />
|
||||
<Compile Include="Components\Account.cs" />
|
||||
<Compile Include="Components\Alert.cs" />
|
||||
<Compile Include="Components\Monitor.cs" />
|
||||
<Compile Include="JsonDeserializer.cs" />
|
||||
<Compile Include="IUptimeClient.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\Parameters.cs" />
|
||||
<Compile Include="Models\Parameters\RetrieveParameters.cs" />
|
||||
<Compile Include="Models\ResponseTime.cs" />
|
||||
<Compile Include="Models\Response\AccountRepsonse.cs" />
|
||||
<Compile Include="Models\Response\AddAlertResonse.cs" />
|
||||
<Compile Include="Models\Response\AddMonitorResponse.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" />
|
||||
<Compile Include="Utilities\JsonExtensions.cs" />
|
||||
<Compile Include="Utilities\UptimeSharpException.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="packages.config" />
|
||||
<Reference Include="Microsoft.Threading.Tasks">
|
||||
<HintPath>..\packages\Microsoft.Bcl.Async.1.0.166\lib\portable-net45+win8+wp8+wpa81\Microsoft.Threading.Tasks.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="Microsoft.Threading.Tasks.Extensions">
|
||||
<HintPath>..\packages\Microsoft.Bcl.Async.1.0.166\lib\portable-net45+win8+wp8+wpa81\Microsoft.Threading.Tasks.Extensions.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="Newtonsoft.Json">
|
||||
<HintPath>..\packages\Newtonsoft.Json.6.0.2\lib\portable-net45+wp80+win8+wpa81\Newtonsoft.Json.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="PropertyChanged">
|
||||
<HintPath>..\packages\PropertyChanged.Fody.1.45.0.0\Lib\portable-net4+sl4+wp7+win8+MonoAndroid16+MonoTouch40\PropertyChanged.dll</HintPath>
|
||||
<Private>False</Private>
|
||||
</Reference>
|
||||
<Reference Include="System.Net.Http">
|
||||
<HintPath>..\packages\Microsoft.Net.Http.2.2.19\lib\portable-net40+sl4+win8+wp71+wpa81\System.Net.Http.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Net.Http.Extensions">
|
||||
<HintPath>..\packages\Microsoft.Net.Http.2.2.19\lib\portable-net40+sl4+win8+wp71+wpa81\System.Net.Http.Extensions.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Net.Http.Primitives">
|
||||
<HintPath>..\packages\Microsoft.Net.Http.2.2.19\lib\portable-net40+sl4+win8+wp71+wpa81\System.Net.Http.Primitives.dll</HintPath>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
<ItemGroup />
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<ItemGroup>
|
||||
<Content Include="FodyWeavers.xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">
|
||||
<Visible>False</Visible>
|
||||
<ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
|
||||
<Install>false</Install>
|
||||
</BootstrapperPackage>
|
||||
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
|
||||
<Visible>False</Visible>
|
||||
<ProductName>.NET Framework 3.5 SP1</ProductName>
|
||||
<Install>false</Install>
|
||||
</BootstrapperPackage>
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets" />
|
||||
<Import Project="..\packages\Fody.1.22.1\build\Fody.targets" Condition="Exists('..\packages\Fody.1.22.1\build\Fody.targets')" />
|
||||
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
|
||||
<PropertyGroup>
|
||||
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
|
||||
</PropertyGroup>
|
||||
<Error Condition="!Exists('..\packages\Fody.1.22.1\build\Fody.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Fody.1.22.1\build\Fody.targets'))" />
|
||||
</Target>
|
||||
<Import Project="..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets" Condition="Exists('..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" />
|
||||
<Target Name="EnsureBclBuildImported" BeforeTargets="BeforeBuild" Condition="'$(BclBuildImported)' == ''">
|
||||
<Error Condition="!Exists('..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" Text="This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=317567." HelpKeyword="BCLBUILD2001" />
|
||||
<Error Condition="Exists('..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" Text="The build restored NuGet packages. Build the project again to include these packages in the build. For more information, see http://go.microsoft.com/fwlink/?LinkID=317568." HelpKeyword="BCLBUILD2002" />
|
||||
</Target>
|
||||
<!-- 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">
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<?xml version="1.0"?>
|
||||
<package>
|
||||
<metadata>
|
||||
<id>$id$</id>
|
||||
<version>$version$</version>
|
||||
<title>$title$</title>
|
||||
<authors>$author$</authors>
|
||||
<owners>$author$</owners>
|
||||
<licenseUrl>https://raw.github.com/ceee/UptimeSharp/master/LICENSE-MIT</licenseUrl>
|
||||
<projectUrl>https://github.com/ceee/UptimeSharp</projectUrl>
|
||||
<iconUrl>https://raw.github.com/ceee/UptimeSharp/master/Assets/uptimesharp.png</iconUrl>
|
||||
<requireLicenseAcceptance>false</requireLicenseAcceptance>
|
||||
<description>UptimeSharp is a .NET portable class library that integrates the UptimeRobot API.</description>
|
||||
<language>en-US</language>
|
||||
<releaseNotes>
|
||||
<![CDATA[
|
||||
For full release notes see https://github.com/ceee/UptimeSharp/blob/master/CHANGELOG.md
|
||||
]]>
|
||||
</releaseNotes>
|
||||
<copyright>Copyright by cee, 2014</copyright>
|
||||
<tags>UptimeSharp UptimeRobot Uptime Robot Tobias Klika cee SDK Server</tags>
|
||||
</metadata>
|
||||
</package>
|
||||
@@ -0,0 +1,98 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
using System;
|
||||
using System.Globalization;
|
||||
|
||||
namespace UptimeSharp
|
||||
{
|
||||
|
||||
public class BoolConverter : JsonConverter
|
||||
{
|
||||
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
|
||||
{
|
||||
writer.WriteValue(((bool)value) ? 1 : 0);
|
||||
}
|
||||
|
||||
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
|
||||
{
|
||||
return reader.Value.ToString() == "1";
|
||||
}
|
||||
|
||||
public override bool CanConvert(Type objectType)
|
||||
{
|
||||
return objectType == typeof(bool);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public class UnixDateTimeConverter : DateTimeConverterBase
|
||||
{
|
||||
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
|
||||
{
|
||||
DateTime epoc = new DateTime(1970, 1, 1);
|
||||
var delta = (DateTime)value - epoc;
|
||||
|
||||
writer.WriteValue((long)delta.TotalSeconds);
|
||||
}
|
||||
|
||||
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
|
||||
{
|
||||
if (reader.Value.ToString() == "0")
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return DateTime.Parse(reader.Value.ToString(), CultureInfo.InvariantCulture).ToLocalTime();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public class UriConverter : JsonConverter
|
||||
{
|
||||
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
|
||||
{
|
||||
if (reader.TokenType == JsonToken.String && Uri.IsWellFormedUriString(reader.Value.ToString(), UriKind.Absolute))
|
||||
{
|
||||
return new Uri(reader.Value.ToString());
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
|
||||
{
|
||||
if (value == null)
|
||||
{
|
||||
writer.WriteNull();
|
||||
}
|
||||
else if (value is Uri)
|
||||
{
|
||||
writer.WriteValue(((Uri)value).OriginalString);
|
||||
}
|
||||
}
|
||||
|
||||
public override bool CanConvert(Type objectType)
|
||||
{
|
||||
return objectType.Equals(typeof(Uri));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public class EnumConverter : StringEnumConverter
|
||||
{
|
||||
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
|
||||
{
|
||||
string value = reader.Value.ToString();
|
||||
|
||||
if (String.IsNullOrEmpty(value))
|
||||
{
|
||||
return Enum.ToObject(objectType, 0);
|
||||
}
|
||||
|
||||
return base.ReadJson(reader, objectType, existingValue, serializer);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
using System;
|
||||
|
||||
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 string 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) { }
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,10 @@
|
||||
<?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" />
|
||||
<package id="Fody" version="1.22.1" targetFramework="portable-net45+win+wpa81+wp80" developmentDependency="true" />
|
||||
<package id="Microsoft.Bcl" version="1.1.7" targetFramework="portable-net45+win+wpa81+wp80" />
|
||||
<package id="Microsoft.Bcl.Async" version="1.0.166" targetFramework="portable-net45+win+wpa81+wp80" />
|
||||
<package id="Microsoft.Bcl.Build" version="1.0.14" targetFramework="portable-net45+win+wpa81+wp80" />
|
||||
<package id="Microsoft.Net.Http" version="2.2.19" targetFramework="portable-net45+win+wpa81+wp80" />
|
||||
<package id="Newtonsoft.Json" version="6.0.2" targetFramework="portable-net45+win+wpa81+wp80" />
|
||||
<package id="PropertyChanged.Fody" version="1.45.0.0" targetFramework="portable-win+net45+sl40+wp71" developmentDependency="true" requireReinstallation="True" />
|
||||
</packages>
|
||||
Reference in New Issue
Block a user