Last active
August 29, 2015 14:08
-
-
Save darrelmiller/972f01aa64c6e5df37df to your computer and use it in GitHub Desktop.
Check status of SqlServer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Data; | |
using System.Data.SqlClient; | |
using System.Net; | |
using System.Net.Http; | |
using System.Net.Http.Formatting; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using System.Web.Http; | |
using Newtonsoft.Json.Linq; | |
namespace MicroHealthChecks | |
{ | |
public class DatabaseServerStatusController : ApiController | |
{ | |
public IHttpActionResult Get() | |
{ | |
using (var connection = new SqlConnection("ConnectionStringGoesHere")) | |
{ | |
try | |
{ | |
connection.Open(); | |
if (connection.State != ConnectionState.Open) | |
{ | |
return new FailResult(); | |
} | |
connection.Close(); | |
} | |
catch | |
{ | |
return new FailResult(); | |
} | |
} | |
return new SuccessResult(); | |
} | |
} | |
public class SuccessResult : IHttpActionResult | |
{ | |
public static JObject SuccessJson = new JObject(new JProperty("status", "Connection successful")); | |
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) | |
{ | |
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new ObjectContent(typeof(JObject), SuccessJson, new JsonMediaTypeFormatter()) }); | |
} | |
} | |
public class FailResult : IHttpActionResult | |
{ | |
public static JObject FailJson = new JObject(new JProperty("status", "Unable to connect")); | |
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) | |
{ | |
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable) { Content = new ObjectContent(typeof(JObject), FailJson, new JsonMediaTypeFormatter()) }); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment