move old lib; create new PCL with utilities

This commit is contained in:
2013-10-28 21:05:10 +01:00
parent de81634646
commit 3e6d93d495
27 changed files with 628 additions and 260 deletions
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("UptimeSharp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("cee")]
[assembly: AssemblyProduct("UptimeSharp")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fe70c634-cebd-44b0-8287-1d75385058cf")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
+211
View File
@@ -0,0 +1,211 @@
using RestSharp;
using System;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
namespace UptimeSharp
{
/// <summary>
/// UptimeClient
/// </summary>
public partial class UptimeClient
{
/// <summary>
/// REST client used for the API communication
/// </summary>
protected readonly RestClient _restClient;
/// <summary>
/// The base URL for the UptimeRobot API
/// </summary>
protected static Uri baseUri = new Uri("http://api.uptimerobot.com/");
/// <summary>
/// Accessor for the UptimeRebot API key
/// see: http://http://www.uptimerobot.com/api.asp
/// </summary>
public string ApiKey { get; set; }
/// <summary>
/// Returns all associated data from the last request
/// </summary>
public IRestResponse LastRequestData { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="UptimeClient"/> class.
/// </summary>
/// <param name="apiKey">The API key</param>
public UptimeClient(string apiKey)
{
// assign public properties
ApiKey = apiKey;
// initialize REST client
_restClient = new RestClient(baseUri.ToString());
// add default parameters to each request
_restClient.AddDefaultParameter("apiKey", ApiKey);
// defines the response format (according to the UptimeRobot docs)
_restClient.AddDefaultParameter("format", "json");
// UptimeRobot returns by default JSON-P when json-formatting is set
// with this param it can return raw JSON
_restClient.AddDefaultParameter("noJsonCallback", "1");
// custom JSON deserializer (ServiceStack.Text)
_restClient.AddHandler("application/json", new JsonDeserializer());
// add custom deserialization lambdas
JsonDeserializer.AddCustomDeserialization();
}
/// <summary>
/// Makes a typed HTTP REST request to the API
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="request">The request.</param>
/// <returns></returns>
protected T Request<T>(RestRequest request) where T : new()
{
// fix content type if wrong determined by RestSharp
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
IRestResponse<T> response = _restClient.Execute<T>(request);
LastRequestData = response;
ValidateResponse<T>(response);
return response.Data;
}
/// <summary>
/// Fetches a typed resource
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="resource">Requested resource</param>
/// <param name="parameters">Additional GET parameters</param>
/// <returns></returns>
protected T Get<T>(string resource, List<Parameter> parameters = null) where T : class, new()
{
// UptimeRobot uses GET for all of its endpoints
var request = new RestRequest(resource, Method.GET);
// enumeration for params
if (parameters != null)
{
parameters.ForEach(
param => {
if(param.Value != null)
{
request.AddParameter(param);
}
}
);
}
// do the request
return Request<T>(request);
}
/// <summary>
/// Fetches a typed resource
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="resource">Requested resource</param>
/// <param name="parameter">The parameters.</param>
/// <returns></returns>
protected T Get<T>(string resource, params Parameter[] parameters) where T : class, new()
{
List<Parameter> parameterList = new List<Parameter>();
parameterList.AddRange(parameters);
return Get<T>(resource, parameterList);
}
/// <summary>
/// Creates a RestSharp.Parameter instance.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
internal static Parameter Parameter(string name, object value)
{
return new Parameter()
{
Name = name,
Value = value,
Type = ParameterType.GetOrPost
};
}
/// <summary>
/// Validates the response.
/// </summary>
/// <param name="response">The response.</param>
/// <returns></returns>
/// <exception cref="UptimeSharpException">
/// Error retrieving response
/// </exception>
protected void ValidateResponse<T>(IRestResponse<T> response) where T : new()
{
Type responseType = response.Data.GetType();
// get status property from ResponseBase POCO
PropertyInfo statusProp = responseType.GetProperty("Status");
object status = statusProp.GetValue(response.Data, null);
// Error from UptimeSharp
if (status.Equals(false))
{
// get error properties from response
PropertyInfo errorProp = responseType.GetProperty("ErrorMessage");
object error = errorProp.GetValue(response.Data, null);
PropertyInfo errorCodeProp = responseType.GetProperty("ErrorCode");
object errorCode = errorCodeProp.GetValue(response.Data, null);
// create exception
UptimeSharpException exception = new UptimeSharpException(
"UptimeRobot Exception: {0} (Code: {1})\n{2}",
response.ErrorException,
error,
errorCode,
"http://uptimerobot.com/api.asp#errorMessages"
);
// add custom pocket fields
exception.Error = error.ToString();
exception.ErrorCode = Convert.ToInt32(errorCode);
// add to generic exception data
exception.Data.Add("Error", error);
exception.Data.Add("ErrorCode", errorCode);
throw exception;
}
// HTTP Request Error
else if (response.StatusCode != HttpStatusCode.OK)
{
throw new UptimeSharpException(
"Request Exception: {0} (Code: {1})",
response.ErrorException,
response.ErrorMessage,
response.StatusCode
);
}
// Exception by RestSharp
else if (response.ErrorException != null)
{
throw new UptimeSharpException("Error retrieving response", response.ErrorException);
}
}
}
}
@@ -0,0 +1,82 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{AF900ACF-DC2A-40AC-9614-B7C8C12E114C}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>UptimeSharp</RootNamespace>
<AssemblyName>UptimeSharp</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<StartupObject />
</PropertyGroup>
<ItemGroup>
<Reference Include="RestSharp">
<HintPath>..\packages\RestSharp.104.1\lib\net4\RestSharp.dll</HintPath>
</Reference>
<Reference Include="ServiceStack.Text">
<HintPath>..\packages\ServiceStack.Text.3.9.56\lib\net35\ServiceStack.Text.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="UptimeSharpException.cs" />
<Compile Include="Components\Alert.cs" />
<Compile Include="Components\Monitor.cs" />
<Compile Include="JsonDeserializer.cs" />
<Compile Include="Models\Alert.cs" />
<Compile Include="Models\Log.cs" />
<Compile Include="Models\Monitor.cs" />
<Compile Include="Models\Parameters\MonitorParameters.cs" />
<Compile Include="Models\Parameters\RetrieveParameters.cs" />
<Compile Include="Models\Response\AlertResponse.cs" />
<Compile Include="Models\Response\DefaultResponse.cs" />
<Compile Include="Models\Response\ResponseBase.cs" />
<Compile Include="Models\Response\RetrieveResponse.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="UptimeClient.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="RestSharp" version="104.1" targetFramework="net40" />
<package id="ServiceStack.Text" version="3.9.56" targetFramework="net40" />
</packages>
+18 -2
View File
@@ -30,6 +30,15 @@
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="Microsoft.Threading.Tasks">
<HintPath>..\packages\Microsoft.Bcl.Async.1.0.16\lib\net40\Microsoft.Threading.Tasks.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Threading.Tasks.Extensions">
<HintPath>..\packages\Microsoft.Bcl.Async.1.0.16\lib\net40\Microsoft.Threading.Tasks.Extensions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Threading.Tasks.Extensions.Desktop">
<HintPath>..\packages\Microsoft.Bcl.Async.1.0.16\lib\net40\Microsoft.Threading.Tasks.Extensions.Desktop.dll</HintPath>
</Reference>
<Reference Include="RestSharp, Version=104.1.0.0, Culture=neutral, processorArchitecture=MSIL"> <Reference Include="RestSharp, Version=104.1.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion> <SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\RestSharp.104.1\lib\net4\RestSharp.dll</HintPath> <HintPath>..\packages\RestSharp.104.1\lib\net4\RestSharp.dll</HintPath>
@@ -40,6 +49,13 @@
</Reference> </Reference>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="System.Net" />
<Reference Include="System.Runtime">
<HintPath>..\packages\Microsoft.Bcl.1.0.19\lib\net40\System.Runtime.dll</HintPath>
</Reference>
<Reference Include="System.Threading.Tasks">
<HintPath>..\packages\Microsoft.Bcl.1.0.19\lib\net40\System.Threading.Tasks.dll</HintPath>
</Reference>
<Reference Include="System.Xml.Linq" /> <Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" /> <Reference Include="Microsoft.CSharp" />
@@ -60,9 +76,9 @@
<None Include="packages.config" /> <None Include="packages.config" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\UptimeSharp\UptimeSharp.csproj"> <ProjectReference Include="..\UptimeSharp.OldClassLib\UptimeSharp.OldClassLib.csproj">
<Project>{af900acf-dc2a-40ac-9614-b7c8c12e114c}</Project> <Project>{af900acf-dc2a-40ac-9614-b7c8c12e114c}</Project>
<Name>UptimeSharp</Name> <Name>UptimeSharp.OldClassLib</Name>
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+1 -1
View File
@@ -1,7 +1,7 @@
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012 # Visual Studio 2012
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UptimeSharp", "UptimeSharp\UptimeSharp.csproj", "{AF900ACF-DC2A-40AC-9614-B7C8C12E114C}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UptimeSharp.OldClassLib", "UptimeSharp.OldClassLib\UptimeSharp.OldClassLib.csproj", "{AF900ACF-DC2A-40AC-9614-B7C8C12E114C}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UptimeSharp.Tests", "UptimeSharp.Tests\UptimeSharp.Tests.csproj", "{7AB536B7-1A99-44A7-B5AA-E36E9C7F09F4}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UptimeSharp.Tests", "UptimeSharp.Tests\UptimeSharp.Tests.csproj", "{7AB536B7-1A99-44A7-B5AA-E36E9C7F09F4}"
EndProject EndProject
+89
View File
@@ -0,0 +1,89 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Choose>
<When Condition="$(NCrunchOriginalSolutionDir) != '' And $(NCrunchOriginalSolutionDir) != '*Undefined*'">
<PropertyGroup>
<FodySolutionDir>$(NCrunchOriginalSolutionDir)</FodySolutionDir>
</PropertyGroup>
</When>
<When Condition="$(SolutionDir) != '' And $(SolutionDir) != '*Undefined*'">
<PropertyGroup>
<FodySolutionDir>$(SolutionDir)</FodySolutionDir>
</PropertyGroup>
</When>
<When Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">
<PropertyGroup>
<FodySolutionDir>$(MSBuildProjectDirectory)\..\</FodySolutionDir>
</PropertyGroup>
</When>
</Choose>
<Choose>
<When Condition="$(KeyOriginatorFile) != '' And $(KeyOriginatorFile) != '*Undefined*'">
<PropertyGroup>
<FodyKeyFilePath>$(KeyOriginatorFile)</FodyKeyFilePath>
</PropertyGroup>
</When>
<When Condition="$(AssemblyOriginatorKeyFile) != '' And $(AssemblyOriginatorKeyFile) != '*Undefined*'">
<PropertyGroup>
<FodyKeyFilePath>$(AssemblyOriginatorKeyFile)</FodyKeyFilePath>
</PropertyGroup>
</When>
<Otherwise >
<PropertyGroup>
<FodyKeyFilePath></FodyKeyFilePath>
</PropertyGroup>
</Otherwise>
</Choose>
<PropertyGroup>
<IntermediateDir>$(ProjectDir)$(IntermediateOutputPath)</IntermediateDir>
<FodyMessageImportance Condition="$(FodyMessageImportance) == '' Or $(FodyMessageImportance) == '*Undefined*'">Low</FodyMessageImportance>
<FodySignAssembly Condition="$(FodySignAssembly) == '' Or $(FodySignAssembly) == '*Undefined*'">$(SignAssembly)</FodySignAssembly>
<FodyPath Condition="$(FodyPath) == '' Or $(FodyPath) == '*Undefined*'">$(MSBuildThisFileDirectory)</FodyPath>
</PropertyGroup>
<UsingTask
TaskName="Fody.WeavingTask"
AssemblyFile="$(FodyPath)\Fody.dll" />
<Target
AfterTargets="AfterCompile"
Name="WinFodyTarget"
Condition=" '$(OS)' == 'Windows_NT'">
<Fody.WeavingTask
AssemblyPath="@(IntermediateAssembly)"
IntermediateDir="$(IntermediateDir)"
KeyFilePath="$(FodyKeyFilePath)"
MessageImportance="$(FodyMessageImportance)"
ProjectDirectory="$(ProjectDir)"
SolutionDir="$(FodySolutionDir)"
References="@(ReferencePath)"
SignAssembly="$(FodySignAssembly)"
ReferenceCopyLocalPaths="@(ReferenceCopyLocalPaths)"
DefineConstants="$(DefineConstants)"
/>
</Target>
<Target
AfterTargets="AfterBuild"
Name="NonWinFodyTarget"
Condition=" '$(OS)' != 'Windows_NT'">
<Fody.WeavingTask
AssemblyPath="$(TargetPath)"
IntermediateDir="$(IntermediateDir)"
KeyFilePath="$(FodyKeyFilePath)"
MessageImportance="$(FodyMessageImportance)"
ProjectDirectory="$(ProjectDir)"
SolutionDir="$(FodySolutionDir)"
References="@(ReferencePath)"
SignAssembly="$(FodySignAssembly)"
ReferenceCopyLocalPaths="$(ReferenceCopyLocalPaths)"
DefineConstants="$(DefineConstants)"
/>
</Target>
<!--Support for ncrunch-->
<ItemGroup>
<None Include="$(FodyPath)\*.*" />
</ItemGroup>
</Project>
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<Weavers>
<PropertyChanged />
</Weavers>
+4 -10
View File
@@ -1,4 +1,5 @@
using System.Reflection; using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
@@ -8,19 +9,12 @@ using System.Runtime.InteropServices;
[assembly: AssemblyTitle("UptimeSharp")] [assembly: AssemblyTitle("UptimeSharp")]
[assembly: AssemblyDescription("")] [assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")] [assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("cee")] [assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("UptimeSharp")] [assembly: AssemblyProduct("UptimeSharp")]
[assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")] [assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")] [assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// 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: // Version information for an assembly consists of the following four values:
// //
+4 -204
View File
@@ -1,211 +1,11 @@
using RestSharp; using System;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Linq;
using System.Reflection; using System.Text;
namespace UptimeSharp namespace UptimeSharp
{ {
/// <summary> class UptimeClient
/// 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);
}
}
} }
} }
+46 -41
View File
@@ -2,18 +2,21 @@
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <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')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup> <PropertyGroup>
<MinimumVisualStudioVersion>10.0</MinimumVisualStudioVersion>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{AF900ACF-DC2A-40AC-9614-B7C8C12E114C}</ProjectGuid> <ProjectGuid>{EC1E656D-4966-499A-9EDD-9DB56137BF62}</ProjectGuid>
<OutputType>Library</OutputType> <OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder> <AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>UptimeSharp</RootNamespace> <RootNamespace>UptimeSharp</RootNamespace>
<AssemblyName>UptimeSharp</AssemblyName> <AssemblyName>UptimeSharp</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Profile104</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<FodyPath>..\packages\Fody.1.17.4.0</FodyPath>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType> <DebugType>full</DebugType>
<Optimize>false</Optimize> <Optimize>false</Optimize>
@@ -23,7 +26,6 @@
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType> <DebugType>pdbonly</DebugType>
<Optimize>true</Optimize> <Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath> <OutputPath>bin\Release\</OutputPath>
@@ -31,47 +33,50 @@
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </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> <ItemGroup>
<!-- A reference to the entire .NET Framework is automatically included -->
<None Include="Fody.targets" />
<None Include="packages.config" /> <None Include="packages.config" />
</ItemGroup> </ItemGroup>
<ItemGroup /> <ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.Threading.Tasks">
<HintPath>..\packages\Microsoft.Bcl.Async.1.0.16\lib\portable-net40+sl4+win8+wp71\Microsoft.Threading.Tasks.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Threading.Tasks.Extensions">
<HintPath>..\packages\Microsoft.Bcl.Async.1.0.16\lib\portable-net40+sl4+win8+wp71\Microsoft.Threading.Tasks.Extensions.dll</HintPath>
</Reference>
<Reference Include="System.IO">
<HintPath>..\packages\Microsoft.Bcl.1.1.3\lib\portable-net40+sl4+win8+wp71\System.IO.dll</HintPath>
</Reference>
<Reference Include="System.Net.Http">
<HintPath>..\packages\Microsoft.Net.Http.2.2.15\lib\portable-net40+sl4+win8+wp71\System.Net.Http.dll</HintPath>
</Reference>
<Reference Include="System.Net.Http.Extensions">
<HintPath>..\packages\Microsoft.Net.Http.2.2.15\lib\portable-net40+sl4+win8+wp71\System.Net.Http.Extensions.dll</HintPath>
</Reference>
<Reference Include="System.Net.Http.Primitives">
<HintPath>..\packages\Microsoft.Net.Http.2.2.15\lib\portable-net40+sl4+win8+wp71\System.Net.Http.Primitives.dll</HintPath>
</Reference>
<Reference Include="System.Runtime">
<HintPath>..\packages\Microsoft.Bcl.1.1.3\lib\portable-net40+sl4+win8+wp71\System.Runtime.dll</HintPath>
</Reference>
<Reference Include="System.Threading.Tasks">
<HintPath>..\packages\Microsoft.Bcl.1.1.3\lib\portable-net40+sl4+win8+wp71\System.Threading.Tasks.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Content Include="FodyWeavers.xml" />
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets" />
<Import Project="..\packages\Microsoft.Bcl.Build.1.0.10\tools\Microsoft.Bcl.Build.targets" Condition="Exists('..\packages\Microsoft.Bcl.Build.1.0.10\tools\Microsoft.Bcl.Build.targets')" />
<Target Name="EnsureBclBuildImported" BeforeTargets="BeforeBuild" Condition="'$(BclBuildImported)' == ''">
<Error Condition="!Exists('..\packages\Microsoft.Bcl.Build.1.0.10\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.10\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>
<Import Project="Fody.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it. <!-- 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. Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild"> <Target Name="BeforeBuild">
+48
View File
@@ -0,0 +1,48 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
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 new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(Convert.ToDouble(reader.Value)).ToLocalTime();
}
}
}
@@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
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) { }
}
}
+7 -2
View File
@@ -1,5 +1,10 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="RestSharp" version="104.1" targetFramework="net40" /> <package id="Fody" version="1.17.4.0" targetFramework="portable-win+net45+sl40+wp71" />
<package id="ServiceStack.Text" version="3.9.56" targetFramework="net40" /> <package id="Microsoft.Bcl" version="1.1.3" targetFramework="portable-win+net45+sl40+wp71" />
<package id="Microsoft.Bcl.Async" version="1.0.16" targetFramework="portable-win+net45+sl40+wp71" />
<package id="Microsoft.Bcl.Build" version="1.0.10" targetFramework="portable-win+net45+sl40+wp71" />
<package id="Microsoft.Net.Http" version="2.2.15" targetFramework="portable-win+net45+sl40+wp71" />
<package id="Newtonsoft.Json" version="5.0.8" targetFramework="portable-win+net45+sl40+wp71" />
<package id="PropertyChanged.Fody" version="1.41.0.0" targetFramework="portable-win+net45+sl40+wp71" />
</packages> </packages>