Monday, 23 April 2018

Mongo DB Connection string from web.config to c# (Collectionname,DB, Connection)

.CS

 private string connectionString = WebConfigurationManager.AppSettings["MongoDbConnectionString"];
        private string mongoDatabase = WebConfigurationManager.AppSettings["MongoDb"];
        private string mongocollection = WebConfigurationManager.AppSettings["Mongocollection"];

        public static string mongoConnKey = "MongoDbConnectionString";
        public static string mongodb = "MongoDb";
        public static string mongocollec = "Mongocollection";


 public string GetSessionData(string transactionID)
        {
            try
            {

                connectionString = ConfigurationManager.AppSettings[mongoConnKey];
                mongoDatabase = ConfigurationManager.AppSettings[mongodb];
                mongocollection = ConfigurationManager.AppSettings[mongocollec];
                var client = new MongoClient(connectionString);
                var _database = client.GetDatabase(mongoDatabase);
                var collection = _database.GetCollection<BsonDocument>(mongocollection);
                var Filter = new BsonDocument("TransactionId", transactionID);
                var result = collection.Find(Filter).ToList();              
                return result.ToString();
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }

Web.config:
   <!--Dev Mongo DB-->

    <add key="MongoDbConnectionString" value="mongodb://testuser:password123@IPaddress:27017/SteveTest" />
    <add key="MongoDb" value="SteveTest" />
    <add key="Mongocollection" value="TestCollection" />


Note : check highliged lines

No comments:

Post a Comment