We have one mongodb Replica Set with two instances(127.0.0.1:27017 - Primary, 127.0.0.1:27018- Secondary) and one arbiter(127.0.0.1:27019). When I step down from primary by using rs.stepDown(60) it should become secondary and secondary should become primary instance, and all write operations should happen in the secondary instance(primary after step down). But after stepping down I am getting the exception "Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host.".
App.Config has the following keys:
<appSettings>
<add key="mongoServerIP" value="127.0.0.1" />
<add key="mongoServerPort" value="27017"/>
<!--<add key="dbname" value="PSLRatingEngine"/>-->
<add key="MongoDbDatabaseName" value="PSLRatingEngine" />
<add key="testcollectionname" value="Test"/>
</appSettings>
C# code :
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ReplicaSetTest
{
class Program
{
static void Main(string[] args)
{
string mongoserverip = ConfigurationManager.AppSettings["mongoServerIP"].ToString();
int port = Convert.ToInt32(ConfigurationManager.AppSettings["mongoServerPort"].ToString());
string dbname = ConfigurationManager.AppSettings["MongoDbDatabaseName"].ToString();
string customercollectionname = ConfigurationManager.AppSettings["testcollectionname"].ToString();
try
{
MongoServerSettings settings = new MongoServerSettings();
settings.Server = new MongoServerAddress(mongoserverip, port);
// Create server object to communicate with our server
MongoServer server = new MongoServer(settings);
// Get our database instance to reach collections and data
var db = server.GetDatabase(dbname);
// Get user collection reference
var collection = db.GetCollection(customercollectionname);
int i = 0;
while(true)
{
Employee emp = new Employee();
emp.EmpId = i + 1000;
Random r = new Random();
emp.Age = r.Next(20, 70);
emp.Salary = r.NextDouble() * 100000;
emp.Name = "emp" + i;
emp.Dept = "Engineering";
collection.Insert<Employee>(emp);
i++;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Please let me know how I can automatically switch from primary to secondary by C# code if anything happens to primary instance of the replica set.