public virtual BsonValue Eval(BsonJavaScript code, params object[] args)
        {
            var mappedArgs = args.Select(a => BsonTypeMapper.MapToBsonValue(a));
            var evalArgs   = new EvalArgs {
                Code = code, Args = mappedArgs
            };

            return(Eval(evalArgs));
        }
        public virtual BsonValue Eval(EvalFlags flags, BsonJavaScript code, params object[] args)
        {
            var mappedArgs = args.Select(a => BsonTypeMapper.MapToBsonValue(a));
            var @lock      = ((flags & EvalFlags.NoLock) != 0) ? (bool?)false : null;
            var evalArgs   = new EvalArgs {
                Code = code, Args = mappedArgs, Lock = @lock
            };

            return(Eval(evalArgs));
        }
Ejemplo n.º 3
0
 /// <summary>
 ///     eval Javascript
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void cmdEval_Click(object sender, EventArgs e)
 {
     var mongoDb = RuntimeMongoDbContext.GetCurrentDataBase();
     var js = new BsonJavaScript(ctlEval.Context);
     var Params = new List<BsonValue>();
     if (txtParm.Text != string.Empty)
     {
         foreach (var parm in txtParm.Text.Split(",".ToCharArray()))
         {
             if (parm.StartsWith("'") & parm.EndsWith("'"))
             {
                 Params.Add(parm.Trim("'".ToCharArray()));
             }
             else
             {
                 try
                 {
                     var isNuberic = true;
                     for (var i = 0; i < parm.Length; i++)
                     {
                         if (!char.IsNumber(parm, i))
                         {
                             isNuberic = false;
                         }
                     }
                     if (isNuberic)
                     {
                         Params.Add(Convert.ToInt16(parm));
                     }
                 }
                 catch (Exception ex)
                 {
                     Utility.ExceptionDeal(ex, "Exception", "Parameter Exception");
                 }
             }
         }
     }
     try
     {
         var args = new EvalArgs {Args = Params.ToArray(), Code = js};
         var result = mongoDb.Eval(args);
         MyMessageBox.ShowMessage("Result", "Result",
             result.ToJson(MongoHelper.JsonWriterSettings), true);
     }
     catch (Exception ex)
     {
         Utility.ExceptionDeal(ex, "Exception", "Result");
     }
 }
Ejemplo n.º 4
0
 /// <summary>
 ///     添加一个用户自定义角色
 /// </summary>
 public static BsonValue AddRole(MongoDatabase mongoDb, Role role)
 {
     var roleCommand = string.Empty;
     var doc = new EvalArgs();
     roleCommand = "db.createRole(" + Environment.NewLine;
     roleCommand += "{" + Environment.NewLine;
     roleCommand += "    role: '" + role.Rolename + "'," + Environment.NewLine;
     //Roles
     roleCommand += "    roles:" + Environment.NewLine;
     roleCommand += "    [";
     for (var i = 0; i < role.Roles.Length; i++)
     {
         var singleroles = role.Roles[i];
         roleCommand += "{ role: '" + singleroles.MRole + "', db: '" + singleroles.Db + "' }" +
                        (i == role.Roles.Length - 1 ? "" : ",") + Environment.NewLine;
     }
     roleCommand += "     ],";
     //privileges
     roleCommand += "    privileges:" + Environment.NewLine;
     roleCommand += "    [";
     for (var i = 0; i < role.Privileges.Length; i++)
     {
         var singleprivileges = role.Privileges[i];
         roleCommand += "{" + singleprivileges.Resource.GetJsCode() + "," +
                        MongoDbAction.GetActionListJs(singleprivileges.Actions) + "}" +
                        (i == role.Privileges.Length - 1 ? "" : ",") + Environment.NewLine;
     }
     roleCommand += "     ],";
     //
     roleCommand += "}" + Environment.NewLine;
     roleCommand += ")";
     doc.Code = roleCommand;
     BsonValue result;
     try
     {
         result = mongoDb.Eval(doc);
     }
     catch (MongoCommandException ex)
     {
         result = ex.Result;
     }
     return result;
 }
Ejemplo n.º 5
0
 /// <summary>
 /// 添加一个用户自定义角色
 /// </summary>
 public static BsonValue AddRole(MongoDatabase mongoDb, Role role)
 {
     String RoleCommand = String.Empty;
     EvalArgs doc = new EvalArgs();
     RoleCommand = "db.createRole(" + System.Environment.NewLine;
     RoleCommand += "{" + System.Environment.NewLine;
     RoleCommand += "    role: '" + role.rolename + "'," + System.Environment.NewLine;
     //Roles
     RoleCommand += "    roles:" + System.Environment.NewLine;
     RoleCommand += "    [";
     for (int i = 0; i < role.roles.Length; i++)
     {
         var singleroles = role.roles[i];
         RoleCommand += "{ role: '" + singleroles.mRole + "', db: '" + singleroles.db + "' }" +
                        ((i == role.roles.Length - 1) ? "" : ",") + System.Environment.NewLine;
     }
     RoleCommand += "     ],";
     //privileges
     RoleCommand += "    privileges:" + System.Environment.NewLine;
     RoleCommand += "    [";
     for (int i = 0; i < role.privileges.Length; i++)
     {
         var singleprivileges = role.privileges[i];
         RoleCommand += "{" + singleprivileges.resource.GetJsCode() + "," + Action.GetActionListJs(singleprivileges.actions) + "}" +
                        ((i == role.privileges.Length - 1) ? "" : ",") + System.Environment.NewLine;
     }
     RoleCommand += "     ],";
     //
     RoleCommand += "}" + System.Environment.NewLine;
     RoleCommand += ")";
     doc.Code = RoleCommand;
     BsonValue result;
     try
     {
         result = mongoDb.Eval(doc);
     }
     catch (MongoCommandException ex)
     {
         result = ex.CommandResult.Response;
     }
     return result;
 }
        private BsonValue Eval(IClientSessionHandle session, EvalArgs args)
        {
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }
            if (args.Code == null)
            {
                throw new ArgumentException("Code is null.", "args");
            }

            var operation = new EvalOperation(_namespace, args.Code, GetMessageEncoderSettings())
            {
                Args    = args.Args,
                MaxTime = args.MaxTime,
                NoLock  = args.Lock.HasValue ? !args.Lock : null
            };

            return(ExecuteWriteOperation(session, operation));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Evaluates JavaScript code at the server.
        /// </summary>
        /// <param name="args">The args.</param>
        /// <returns>The result of evaluating the code.</returns>
        public virtual BsonValue Eval(EvalArgs args)
        {
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }
            if (args.Code == null)
            {
                throw new ArgumentException("Code is null.", "args");
            }

            var command = new CommandDocument
            {
                { "$eval", args.Code },
                { "args", () => new BsonArray(args.Args), args.Args != null }, // optional
                { "nolock", () => !args.Lock.Value, args.Lock.HasValue },      // optional
                { "maxTimeMS", () => args.MaxTime.Value.TotalMilliseconds, args.MaxTime.HasValue } // optional
            };
            var result = RunCommandAs <CommandResult>(command);

            return(result.Response["retval"]);
        }
        /// <summary>
        /// Evaluates JavaScript code at the server.
        /// </summary>
        /// <param name="args">The args.</param>
        /// <returns>The result of evaluating the code.</returns>
        public virtual BsonValue Eval(EvalArgs args)
        {
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }
            if (args.Code == null)
            {
                throw new ArgumentException("Code is null.", "args");
            }

            var operation = new EvalOperation(_namespace, args.Code, GetMessageEncoderSettings())
            {
                Args    = args.Args,
                MaxTime = args.MaxTime,
                NoLock  = args.Lock.HasValue ? !args.Lock : null
            };

            using (var binding = _server.GetWriteBinding())
            {
                return(operation.Execute(binding));
            }
        }
 public void TestEvalWithMaxTime()
 {
     if (_primary.Supports(FeatureId.MaxTime) && _primary.InstanceType != MongoServerInstanceType.ShardRouter)
     {
         using (var failpoint = new FailPoint(FailPointName.MaxTimeAlwaysTimeout, _server, _primary))
         {
             if (failpoint.IsSupported())
             {
                 failpoint.SetAlwaysOn();
                 var args = new EvalArgs
                 {
                     Code = "return 0;",
                     MaxTime = TimeSpan.FromMilliseconds(1)
                 };
                 Assert.Throws<ExecutionTimeoutException>(() => _database.Eval(args));
             }
         }
     }
 }
Ejemplo n.º 10
0
 /// <summary>
 ///     初始化副本(Mongo Shell)
 /// </summary>
 /// <returns></returns>
 public static CommandResult InitReplicaSet()
 {
     //使用local数据库发送 rs.initiate() 指令
     MongoDatabase mongoDb = RuntimeMongoDbContext.GetCurrentClient().GetServer().GetDatabase("local");
     var args = new EvalArgs { Code = "rs.initiate()" };
     var result = mongoDb.Eval(args);
     return new CommandResult(result.AsBsonDocument);
 }
Ejemplo n.º 11
0
 /// <summary>
 /// Evaluates JavaScript code at the server.
 /// </summary>
 /// <param name="args">The args.</param>
 /// <returns>The result of evaluating the code.</returns>
 public virtual BsonValue Eval(EvalArgs args)
 {
     return(UsingImplicitSession(session => Eval(session, args)));
 }
Ejemplo n.º 12
0
 /// <summary>
 ///     GetRole
 /// </summary>
 /// <param name="mongoDb"></param>
 /// <param name="roleName"></param>
 /// <returns></returns>
 public static BsonDocument GetRole(MongoDatabase mongoDb, string roleName)
 {
     var doc = new EvalArgs();
     doc.Code = "db.getRole('" + roleName + "',{showPrivileges:true})";
     return mongoDb.Eval(doc).AsBsonDocument;
 }
 public void TestEvalWithMaxTime()
 {
     if (!DriverTestConfiguration.Client.Settings.Credentials.Any())
     {
         if (_primary.Supports(FeatureId.MaxTime))
         {
             using (var failpoint = new FailPoint(FailPointName.MaxTimeAlwaysTimeout, _server, _primary))
             {
                 if (failpoint.IsSupported())
                 {
                     failpoint.SetAlwaysOn();
                     var args = new EvalArgs
                     {
                         Code = "return 0;",
                         MaxTime = TimeSpan.FromMilliseconds(1)
                     };
                     Assert.Throws<MongoExecutionTimeoutException>(() => _adminDatabase.Eval(args));
                 }
             }
         }
     }
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Executes the contents of the <paramref name="file"/>.
        /// </summary>
        /// <param name="file">The patch file to execute.</param>
        private void ExecutePatch(string file)
        {
            string friendlyFileName = Regex.Match(file, "[0-9.]+" + Regex.Escape(@"\") + ".*" + Regex.Escape(".") + "js$").Value;
            this.installLogger.Log(string.Format(Messages.DB_ExecuteScript, friendlyFileName));
            string contents = File.ReadAllText(file);
            EvalArgs args = new EvalArgs
                                {
                                    Code = new BsonJavaScript(contents),
                                    MaxTime = TimeSpan.FromDays(7)
                                };

            this.Database.Eval(args);

            this.installLogger.LogSuccess(Messages.MAIN_StepComplete);
        }