public void TestErrorMessageNotString() { var document = new BsonDocument("errmsg", 3.14159); var result = new CommandResult(); result.Initialize(document); Assert.AreEqual("3.14159", result.ErrorMessage); }
public void TestErrorMessagePresent() { var document = new BsonDocument("errmsg", "An error message"); var result = new CommandResult(); result.Initialize(document); Assert.AreEqual("An error message", result.ErrorMessage); }
public MongoSafeModeException( string message, CommandResult commandResult ) : base(message, commandResult) { }
public void TestErrorMessageMissing() { var document = new BsonDocument(); var result = new CommandResult(); result.Initialize(document); Assert.AreEqual("Unknown error", result.ErrorMessage); }
public void TestOkTrue() { var document = new BsonDocument("ok", true); var result = new CommandResult(null, document); Assert.IsTrue(result.Ok); Assert.IsNull(result.ErrorMessage); }
/// <summary> /// Initializes a new instance of the MongoCommandException class. /// </summary> /// <param name="message">The error message.</param> /// <param name="commandResult">The command result.</param> public MongoCommandException( string message, CommandResult commandResult ) : this(message) { this.commandResult = commandResult; }
//Replica Set Commands //http://www.mongodb.org/display/DOCS/Replica+Set+Commands //rs.help() show help //rs.status() { replSetGetStatus : 1 } //rs.initiate() { replSetInitiate : null } initiate // with default settings //rs.initiate(cfg) { replSetInitiate : cfg } //rs.add(hostportstr) add a new member to the set //rs.add(membercfgobj) add a new member to the set //rs.addArb(hostportstr) add a new member which is arbiterOnly:true //rs.remove(hostportstr) remove a member (primary, secondary, or arbiter) from the set //rs.stepDown() { replSetStepDown : true } //rs.conf() return configuration from local.system.replset //db.isMaster() check who is primary /// <summary> /// 增加服务器 /// </summary> /// <param name="mongoSvr">副本组主服务器</param> /// <param name="HostPort">服务器信息</param> /// <param name="IsArb">是否为仲裁服务器</param> /// <returns></returns> public static CommandResult AddToReplsetServer(MongoServer mongoSvr, String HostPort, int priority, Boolean IsArb) { CommandResult mCommandResult = new CommandResult(new BsonDocument()); try { if (!IsArb) { mCommandResult = ExecuteJsShell("rs.add({_id:" + mongoSvr.Instances.Length + 1 + ",host:'" + HostPort + "',priority:" + priority.ToString() + "});", mongoSvr); } else { //其实addArb最后也只是调用了add方法 mCommandResult = ExecuteJsShell("rs.addArb('" + HostPort + "');", mongoSvr); } } catch (EndOfStreamException) { } catch (Exception ex) { throw ex; } return mCommandResult; }
public void TestCodeMissing() { var document = new BsonDocument(); var result = new CommandResult(document); Assert.False(result.Code.HasValue); }
public void TestOkFalse() { var document = new BsonDocument("ok", false); var result = new CommandResult(null, document); Assert.IsFalse(result.Ok); Assert.IsNotNull(result.ErrorMessage); }
/// <summary> /// Save Edited Javascript /// </summary> /// <param name="jsName"></param> /// <param name="jsCode"></param> /// <param name="jsCol"></param> /// <returns></returns> public static string SaveEditorJavascript(string jsName, string jsCode, MongoCollection jsCol) { //标准的JS库格式未知 if (QueryHelper.IsExistByKey(jsName)) { var result = DropDocument(jsCol, (BsonString) jsName); if (string.IsNullOrEmpty(result)) { CommandResult resultCommand; try { resultCommand = new CommandResult( jsCol.Insert(new BsonDocument().Add(ConstMgr.KeyId, jsName).Add("value", jsCode)).Response); } catch (MongoCommandException ex) { resultCommand = new CommandResult(ex.Result); } if (resultCommand.Response["err"] == BsonNull.Value) { return string.Empty; } return resultCommand.Response["err"].ToString(); } return result; } return string.Empty; }
/// <summary> /// 删除单条数据 /// </summary> /// <param name="mongoCol">表对象</param> /// <param name="objectId">ObjectId</param> /// <returns></returns> public static string DropDocument(MongoCollection mongoCol, string objectId) { CommandResult result; try { //有时候在序列化的过程中,objectId是由某个字段带上[id]特性客串的,所以无法转换为ObjectId对象 //这里先尝试转换,如果可以转换,则转换 ObjectId seekId; if (ObjectId.TryParse(objectId, out seekId)) { //如果可以转换,则转换 result = new CommandResult( mongoCol.Remove(Query.EQ(ConstMgr.KeyId, seekId), WriteConcern.Acknowledged) .Response); } else { //不能转换则保持原状 result = new CommandResult( mongoCol.Remove(Query.EQ(ConstMgr.KeyId, objectId), WriteConcern.Acknowledged) .Response); } } catch (MongoCommandException ex) { result = new CommandResult(ex.Result); } BsonElement err; return !result.Response.TryGetElement("err", out err) ? string.Empty : err.ToString(); }
public void TestOkZero() { var document = new BsonDocument("ok", 0); var result = new CommandResult(document); Assert.False(result.Ok); Assert.NotNull(result.ErrorMessage); }
public void TestCode() { var document = new BsonDocument("code", 18); var result = new CommandResult(document); Assert.True(result.Code.HasValue); Assert.Equal(18, result.Code); }
public void TestCodeMissing() { var command = new CommandDocument("invalid", 1); var document = new BsonDocument(); var result = new CommandResult(command, document); Assert.IsFalse(result.Code.HasValue); }
public void TestCode() { var command = new CommandDocument("invalid", 1); var document = new BsonDocument("code", 18); var result = new CommandResult(command, document); Assert.IsTrue(result.Code.HasValue); Assert.AreEqual(18, result.Code); }
public void TestOkMissing() { var command = new CommandDocument("invalid", true); var document = new BsonDocument(); var result = new CommandResult(command, document); try { var dummy = result.Ok; } catch (MongoCommandException ex) { Assert.IsTrue(ex.Message.StartsWith("Command 'invalid' failed: response has no ok element (response: ")); } }
/// <summary> /// Js Shell 的结果判定 /// </summary> /// <param name="Result"></param> /// <returns></returns> public static Boolean IsShellOK(CommandResult Result) { if (!Result.Response.ToBsonDocument().GetElement("retval").Value.IsBsonDocument) { return true; } return Result.Response.ToBsonDocument() .GetElement("retval") .Value.AsBsonDocument.GetElement("ok") .Value.ToString() == "1"; }
/// <summary> /// 重新启动 /// </summary> /// <param name="primarySvr">副本组主服务器</param> /// <param name="config">服务器信息</param> /// <remarks>这个命令C#无法正确执行</remarks> /// <returns></returns> public static CommandResult ReconfigReplsetServer(MongoServer primarySvr, BsonDocument config) { var cmdRtn = new CommandResult(new BsonDocument()); try { return CommandExecute.ExecuteJsShell("rs.reconfig(" + config + ",{force : true})", primarySvr); } catch (EndOfStreamException) { } return cmdRtn; }
/// <summary> /// 删除服务器 /// </summary> /// <param name="mongoSvr">副本组主服务器</param> /// <param name="hostPort">服务器信息</param> /// <remarks>这个命令C#无法正确执行</remarks> /// <returns></returns> public static CommandResult RemoveFromReplsetServer(MongoServer mongoSvr, string hostPort) { var mCommandResult = new CommandResult(new BsonDocument()); try { CommandExecute.ExecuteJsShell("rs.remove('" + hostPort + "');", mongoSvr); } catch (EndOfStreamException) { } return mCommandResult; }
public void TestOkMissing() { var command = new CommandDocument("invalid", 1); var document = new BsonDocument(); var result = new CommandResult(document) { Command = command }; try { var dummy = result.Ok; } catch (MongoCommandException ex) { Assert.IsTrue(ex.Message.StartsWith("Command 'invalid' failed. Response has no ok element (response was ", StringComparison.Ordinal)); } }
/// <summary> /// 当前对象的MONGO命令 /// </summary> /// <param name="mMongoCommand">命令对象</param> /// <param name="ShowMsgBox"></param> /// <returns></returns> public static CommandResult ExecuteMongoCommand(MongoCommand mMongoCommand, Boolean ShowMsgBox = true) { var ResultCommandList = new List<CommandResult>(); var mCommandResult = new CommandResult(new BsonDocument()); try { switch (mMongoCommand.RunLevel) { case MongoDbHelper.PathLv.CollectionLv: if (String.IsNullOrEmpty(mMongoCommand.CommandString)) { mCommandResult = ExecuteMongoColCommand(mMongoCommand.cmdDocument, SystemManager.GetCurrentCollection()); } else { mCommandResult = ExecuteMongoColCommand(mMongoCommand.CommandString, SystemManager.GetCurrentCollection()); } break; case MongoDbHelper.PathLv.DatabaseLv: mCommandResult = ExecuteMongoDBCommand(mMongoCommand.cmdDocument, SystemManager.GetCurrentDataBase()); break; case MongoDbHelper.PathLv.InstanceLv: mCommandResult = ExecuteMongoSvrCommand(mMongoCommand.cmdDocument, SystemManager.GetCurrentServer()); break; default: break; } ResultCommandList.Add(mCommandResult); if (ShowMsgBox) MyMessageBox.ShowMessage(mMongoCommand.CommandString, mMongoCommand.CommandString + " Result", MongoDbHelper.ConvertCommandResultlstToString(ResultCommandList), true); } catch (IOException ex) { SystemManager.ExceptionDeal(ex, mMongoCommand.CommandString, "IOException,Try to set Socket TimeOut more long at connection config"); } catch (Exception ex) { SystemManager.ExceptionDeal(ex, mMongoCommand.CommandString); } return mCommandResult; }
/// <summary> /// 插入JS到系统JS库 /// </summary> /// <param name="jsName"></param> /// <param name="jsCode"></param> public static string CreateNewJavascript(string jsName, string jsCode) { var jsCol = RuntimeMongoDbContext.GetCurrentCollection(); //标准的JS库格式未知 if (QueryHelper.IsExistByKey(jsName)) return string.Empty; CommandResult result; try { result = new CommandResult( jsCol.Insert(new BsonDocument().Add(ConstMgr.KeyId, jsName).Add("value", jsCode)).Response); } catch (MongoCommandException ex) { result = new CommandResult(ex.Result); } return result.Response["err"] == BsonNull.Value ? string.Empty : result.Response["err"].ToString(); }
/// <summary> /// 当前对象的MONGO命令 /// </summary> /// <param name="mMongoCommand">命令对象</param> /// <returns></returns> public static CommandResult ExecuteMongoCommand(MongoCommand mMongoCommand) { var resultCommandList = new List<CommandResult>(); var mCommandResult = new CommandResult(new BsonDocument()); try { switch (mMongoCommand.RunLevel) { case EnumMgr.PathLevel.Collection: if (string.IsNullOrEmpty(mMongoCommand.CommandString)) { mCommandResult = ExecuteMongoColCommand(mMongoCommand.CmdDocument, RuntimeMongoDbContext.GetCurrentCollection()); } else { mCommandResult = ExecuteMongoColCommand(mMongoCommand.CommandString, RuntimeMongoDbContext.GetCurrentCollection()); } break; case EnumMgr.PathLevel.Database: mCommandResult = ExecuteMongoDBCommand(mMongoCommand.CmdDocument, RuntimeMongoDbContext.GetCurrentDataBase()); break; case EnumMgr.PathLevel.Instance: mCommandResult = ExecuteMongoSvrCommand(mMongoCommand.CmdDocument, RuntimeMongoDbContext.GetCurrentServer()); break; } resultCommandList.Add(mCommandResult); } catch (IOException ex) { Utility.ExceptionDeal(ex, mMongoCommand.CommandString, "IOException,Try to set Socket TimeOut more long at connection config"); } catch (Exception ex) { Utility.ExceptionDeal(ex, mMongoCommand.CommandString); } return mCommandResult; }
/// <summary> /// 增加服务器 /// </summary> /// <param name="mongoSvr">副本组主服务器</param> /// <param name="hostPort">服务器信息</param> /// <param name="isArb">是否为仲裁服务器</param> /// <returns></returns> public static CommandResult AddToReplsetServer(MongoServer mongoSvr, string hostPort, int priority, bool isArb) { var mCommandResult = new CommandResult(new BsonDocument()); try { if (!isArb) { var code = "rs.add({_id:" + (mongoSvr.Instances.Length + 1) + ",host:'" + hostPort + "',priority:" + priority + "});"; mCommandResult = CommandExecute.ExecuteJsShell(code, mongoSvr); } else { //其实addArb最后也只是调用了add方法 mCommandResult = CommandExecute.ExecuteJsShell("rs.addArb('" + hostPort + "');", mongoSvr); } } catch (EndOfStreamException) { } return mCommandResult; }
/// <summary> /// 执行数据集命令 /// </summary> /// <param name="commandString"></param> /// <param name="mongoCol"></param> /// <returns></returns> public static CommandResult ExecuteMongoColCommand(string commandString, MongoCollection mongoCol) { CommandResult mCommandResult; var baseCommand = new BsonDocument { { commandString, mongoCol.Name } }; var mongoCmd = new CommandDocument(); mongoCmd.AddRange(baseCommand); try { mCommandResult = mongoCol.Database.RunCommand(mongoCmd); } catch (MongoCommandException ex) { mCommandResult = new CommandResult(ex.Result); } var e = new RunCommandEventArgs { CommandString = commandString, RunLevel = EnumMgr.PathLevel.CollectionAndView, Result = mCommandResult }; OnCommandRunComplete(e); return mCommandResult; }
/// <summary> /// 删除服务器 /// </summary> /// <param name="mongoSvr">副本组主服务器</param> /// <param name="HostPort">服务器信息</param> /// <remarks>这个命令C#无法正确执行</remarks> /// <returns></returns> public static CommandResult RemoveFromReplsetServer(MongoServer mongoSvr, String HostPort) { CommandResult mCommandResult = new CommandResult(new BsonDocument()); try { ExecuteJsShell("rs.remove('" + HostPort + "');", mongoSvr); } catch (EndOfStreamException) { } catch (Exception ex) { throw ex; } return mCommandResult; }
internal void VerifyState(MongoConnection connection) { CommandResult isMasterResult = null; bool ok = false; try { var isMasterCommand = new CommandDocument("ismaster", 1); isMasterResult = connection.RunCommand("admin.$cmd", QueryFlags.SlaveOk, isMasterCommand, false); if (!isMasterResult.Ok) { throw new MongoCommandException(isMasterResult); } var isPrimary = isMasterResult.Response["ismaster", false].ToBoolean(); var isSecondary = isMasterResult.Response["secondary", false].ToBoolean(); var isPassive = isMasterResult.Response["passive", false].ToBoolean(); var isArbiter = isMasterResult.Response["arbiterOnly", false].ToBoolean(); // workaround for CSHARP-273 if (isPassive && isArbiter) { isPassive = false; } var maxDocumentSize = isMasterResult.Response["maxBsonObjectSize", MongoDefaults.MaxDocumentSize].ToInt32(); var maxMessageLength = Math.Max(MongoDefaults.MaxMessageLength, maxDocumentSize + 1024); // derived from maxDocumentSize MongoServerBuildInfo buildInfo; var buildInfoCommand = new CommandDocument("buildinfo", 1); var buildInfoResult = connection.RunCommand("admin.$cmd", QueryFlags.SlaveOk, buildInfoCommand, false); if (buildInfoResult.Ok) { buildInfo = new MongoServerBuildInfo( buildInfoResult.Response["bits"].ToInt32(), // bits buildInfoResult.Response["gitVersion"].AsString, // gitVersion buildInfoResult.Response["sysInfo"].AsString, // sysInfo buildInfoResult.Response["version"].AsString // versionString ); } else { // short term fix: if buildInfo fails due to auth we don't know the server version; see CSHARP-324 if (buildInfoResult.ErrorMessage != "need to login") { throw new MongoCommandException(buildInfoResult); } buildInfo = null; } _isMasterResult = isMasterResult; _maxDocumentSize = maxDocumentSize; _maxMessageLength = maxMessageLength; _buildInfo = buildInfo; this.SetState(MongoServerState.Connected, isPrimary, isSecondary, isPassive, isArbiter); // if this is the primary of a replica set check to see if any instances have been added or removed if (isPrimary && _server.Settings.ConnectionMode == ConnectionMode.ReplicaSet) { var instanceAddresses = new List<MongoServerAddress>(); if (isMasterResult.Response.Contains("hosts")) { foreach (var hostName in isMasterResult.Response["hosts"].AsBsonArray) { var address = MongoServerAddress.Parse(hostName.AsString); instanceAddresses.Add(address); } } if (isMasterResult.Response.Contains("passives")) { foreach (var hostName in isMasterResult.Response["passives"].AsBsonArray) { var address = MongoServerAddress.Parse(hostName.AsString); instanceAddresses.Add(address); } } if (isMasterResult.Response.Contains("arbiters")) { foreach (var hostName in isMasterResult.Response["arbiters"].AsBsonArray) { var address = MongoServerAddress.Parse(hostName.AsString); instanceAddresses.Add(address); } } _server.VerifyInstances(instanceAddresses); } ok = true; } finally { if (!ok) { _isMasterResult = isMasterResult; _maxDocumentSize = MongoDefaults.MaxDocumentSize; _maxMessageLength = MongoDefaults.MaxMessageLength; _buildInfo = null; this.SetState(MongoServerState.Disconnected, false, false, false, false); } } }
// private static methods private static string FormatErrorMessage(CommandResult commandResult) { return string.Format("Command '{0}' failed: {1} (response: {2})", commandResult.CommandName, commandResult.ErrorMessage, commandResult.Response.ToJson()); }
/// <summary> /// Initializes a new instance of the MongoCommandException class. /// </summary> /// <param name="message">The error message.</param> /// <param name="commandResult">The command result.</param> public MongoCommandException(string message, CommandResult commandResult) : this(message) { this.commandResult = commandResult; }
// public static methods /// <summary> /// Creates a new instance of MongoServerBuildInfo initialized from the result of a buildinfo command. /// </summary> /// <param name="result">A CommandResult.</param> /// <returns>A MongoServerBuildInfo.</returns> public static MongoServerBuildInfo FromCommandResult(CommandResult result) { var document = result.Response; return new MongoServerBuildInfo( document["bits"].ToInt32(), document["gitVersion"].AsString, document["sysInfo"].AsString, document["version"].AsString ); }
// private static methods private static string FormatErrorMessage(CommandResult commandResult) { return(string.Format("Command '{0}' failed: {1} (response: {2})", commandResult.CommandName, commandResult.ErrorMessage, commandResult.Response.ToJson())); }
// constructors /// <summary> /// Initializes a new instance of the MongoCommandException class. /// </summary> /// <param name="commandResult">The command result (an error message will be constructed using the result).</param> public MongoCommandException(CommandResult commandResult) : this(FormatErrorMessage(commandResult), commandResult) { }