Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
MongoDb diagnostic page
<!-- directives -->
<% @Page Language="C#" %>
<%@ Import namespace="MongoDB.Bson.Serialization" %>
<%@ Import namespace="MongoDB.Bson.Serialization.Conventions" %>
<%@ Import namespace="MongoDB.Driver" %>
<%@ Import namespace="MongoDB.Bson" %>
<!-- call example:
https://server/_diagnostics/mongo.aspx?connectionString=mongodb%3A%2F%2Fserver%3A27017%2Ftest&collectionName=logs
-->
<script runat="server">
private IMongoDatabase GetDatabase(string connectionString)
{
var url = new MongoUrl(connectionString);
var client = new MongoClient(url);
var database = client.GetDatabase(url.DatabaseName ?? "test");
return database;
}
private void GetCount(string connectionString, string collectionName, int executionCount)
{
outputText.InnerHtml = "Get count of " + collectionName + " <br/>";
for (int i = 0; i < executionCount; i++)
{
try
{
var db = GetDatabase(connectionString);
var collection = db.GetCollection<BsonDocument>(collectionName);
var count = collection.CountAsync(new BsonDocument {})
.Result;
outputText.InnerHtml += "SUCCESSFUL " + count.ToString() + " <br/>";
}
catch (Exception ex)
{
outputText.InnerHtml += "FAILED " + ex.ToString() + " <br/>";
}
}
}
private void GetCountClick(object sender, EventArgs e)
{
var executionCountInt = int.Parse(executionCount.Value);
GetCount(connectionString.Value, collectionName.Value, executionCountInt);
}
private void Page_Load()
{
var cn = Request.QueryString["connectionString"];
if (string.IsNullOrWhiteSpace(cn)) return;
var collection = Request.QueryString["collectionName"];
if (string.IsNullOrWhiteSpace(collection)) return;
var executionCount = Request.QueryString["executionCount"] ?? "1";
var executionCountInt = int.Parse(executionCount);
GetCount(cn, collection, executionCountInt);
}
</script>
<!-- Layout -->
<html>
<head>
<title> Mongo Test </title>
</head>
<body>
<h3> Test mongo connectivity </h3>
<p>Machine name: <%= System.Environment.MachineName %></p>
<p>MongoDriver: <%= typeof(MongoClient).Assembly.GetName().Version.ToString() %>
<form runat="server">
<h4>Connection String</h4>
<input runat="server" id="connectionString" type="text" value="mongodb://server:27017/test" style="width:600px" />
<br />
<h4>Collection name</h4>
<input runat="server" id="collectionName" type="text" value="logs" />
<h4>Retry count</h4>
<input runat="server" id="executionCount" type="text" value="1" />
<br />
<input runat="server" id="button1" type="submit" value="Get Count" OnServerClick="GetCountClick" />
<hr />
<h3> Results: </h3>
<span runat="server" id="outputText" />
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment