PageRenderTime 41ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/C#/MongoDBAPI/MongoDBHandler.ashx.cs

https://github.com/rogerlonatural/GitHub
C# | 94 lines | 72 code | 19 blank | 3 comment | 2 complexity | 918de364f9f9629d5f624b5aa86d1878 MD5 | raw file
  1. using System;
  2. using System.Collections;
  3. using System.Data;
  4. using System.Linq;
  5. using System.Web;
  6. using System.Web.Services;
  7. using System.Web.Services.Protocols;
  8. using System.Xml.Linq;
  9. using MongoDB.Bson;
  10. using MongoDB.Driver;
  11. using MongoDB.Driver.Builders;
  12. using MongoDB.Driver.Linq;
  13. using System.Text.RegularExpressions;
  14. using System.IO;
  15. namespace MongoDBAPI
  16. {
  17. /// <summary>
  18. /// Summary description for $codebehindclassname$
  19. /// </summary>
  20. [WebService(Namespace = "http://tempuri.org/")]
  21. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  22. public class MongoDBHandler : IHttpHandler
  23. {
  24. public void ProcessRequest(HttpContext context)
  25. {
  26. context.Response.ContentType = "application/json";
  27. string mongoDBConn = System.Configuration.ConfigurationManager.AppSettings["MongoDBConn"];
  28. string dbName = mongoDBConn.Substring(mongoDBConn.LastIndexOf('/') + 1);
  29. if (dbName.Contains('?'))
  30. {
  31. dbName = dbName.Substring(0, dbName.LastIndexOf('?'));
  32. }
  33. string collectionName = System.Configuration.ConfigurationManager.AppSettings["MongoDBCollection"];
  34. if ("POST".Equals(context.Request.HttpMethod))
  35. {
  36. try
  37. {
  38. var client = new MongoClient(mongoDBConn);
  39. var server = client.GetServer();
  40. var dbSettings = server.CreateDatabaseSettings(dbName);
  41. dbSettings.SlaveOk = true;
  42. var db = server.GetDatabase(dbSettings);
  43. var collection = db.GetCollection(collectionName);
  44. Stream instream = context.Request.InputStream;
  45. BinaryReader br = new BinaryReader(instream, System.Text.Encoding.UTF8);
  46. byte[] bytes = br.ReadBytes((int)instream.Length);
  47. string jSONInput = System.Text.Encoding.UTF8.GetString(bytes);
  48. var doc = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(jSONInput);
  49. var query = new QueryDocument(doc);
  50. var result = collection.Find(query);
  51. var settings = new MongoDB.Bson.IO.JsonWriterSettings();
  52. settings.OutputMode = MongoDB.Bson.IO.JsonOutputMode.Strict;
  53. string json = result.ToJson(settings);
  54. json = "{\"result\":" + json + "}";
  55. context.Response.Write(json);
  56. }
  57. catch (ExecutionTimeoutException ete)
  58. {
  59. context.Response.Write(ete.Message);
  60. }
  61. catch (Exception ex)
  62. {
  63. context.Response.Write(ex.Message);
  64. }
  65. }
  66. }
  67. public bool IsReusable
  68. {
  69. get
  70. {
  71. return false;
  72. }
  73. }
  74. }
  75. }