I want to be able to run any MongoDB command from C#. I know that this can be done. I start with a simple example, instead of using the dropDatabase method from the C# driver I am trying to drop a database using the db.runCommand method as follows.
I have tried in two ways, passing the command as a string and also passing the command as a BsonDocument but nothing is working and I don't have any clues where I'm wrong even after researching on the internet I cannot find a suitable example.
I'm having a really hard time to identify why this piece of code is not working.
Command passed as a string:
database.RunCommand<string>("{dropdatabase : 1}");
Command passed as a BSON document:
var command = new BsonDocument { {"dropdatabase", "1" } };
var execute = database.RunCommand<BsonDocument>(command);
You can use a JsonCommand like this:
var command = new JsonCommand<BsonDocument>("{ dropDatabase: 1 }");
db.RunCommand(command);
or use a CommandDocument like this:
var command = new CommandDocument("dropDatabase", 1);
db.RunCommand<BsonDocument>(command);
Related
Let's say I have a string. " db.getCollection("somecollection").find({})". Can I execute this string as a query in C#? i.e. I get a string. And I just execute it as a query but in c#
I just want like this
string query = "db.getCollection("somename")";
Mongo.execute(query);
no, the best you can do in this context is to use db.RunCommand<BsonDocument>("{ ping : 1 }") (c#) which is close to the shell db.runCommand({ ping : 1 })
UPDATE:
you may look at this as well How to execute mongo commands through shell scripts?, I'm not familiar with this and it doesn't work for me on windows and 5.0 server in most of the cases mentioned there other than simple one: mongo --eval "printjson(db.serverStatus())", but if you will be able to make this suggested script mongo < script.js (or similar) work in, for example, the shell, you will be able to put your random query in this file(script.js) and then, add this file as argument into Process creating similar to:
using (var process = new Process())
{
// arguments below may require the whole path to the files
process.StartInfo.Arguments = "script.js";
process.StartInfo.FileName = "mongo";
process.Start();
}
to read results, you will need analyzing process.StandardOutput/process.StandardError stream.
"it is showing error like :- JSON reader was expecting a value but
found 'mongodump'.'"
//i tried this code but itr=s not working
"var cmd = new JsonCommand<BsonDocument>(" mongodump--db XEAP --out
F:\\");
database.RunCommand(cmd);"
I want to take backup of database using c# code.
"var cmd = new JsonCommand<BsonDocument>(" mongodump--db XEAP --out
F:\\");
database.RunCommand(cmd);"
database.RunCommand executes MongoDB command.
mongodump is an OS-level executable. This thread explains how to run this kind of command from C#.
Run Command Prompt Commands
I am new to JINT, and trying to just do some basic tests to kind of learn the ropes. My first attempt was to just store some javascript in my database, load it, and execute it in a unit test. So that looks essentially like this....
[Fact]
public void can_use_jint_engine() {
using (var database = DocumentStore()) {
using (var session = database.OpenSession()) {
var source = session.Load<Statistic>("statistics/1");
// join the list of strings into a single script
var script = String.Join("\n", source.Scripting);
// this will create the script
// console.log("this is a test from jint.");
//
var engine = new Jint.Engine();
// attempt to execute the script
engine.Execute(script);
}
}
}
And it doesn't work, I get this error, which makes absolutely no sense to me, and I cannot find any documentation on.
Jint.Runtime.JavaScriptExceptionconsole is not defined at
Jint.Engine.Execute(Program program) at
Jint.Engine.Execute(String source) at
SampleProject.Installers.Instanced.__testing_installer.can_use_jint_engine()
in _testing_installer.cs: line 318
Can anyone assist in shedding some light on this? I'm pretty confused at this point.
With JavaScript there are three entities - we care about. The host (browser, your application etc), the engine (JINT in this case) and the script ("console.log(...)") in this case.
JavaScript defines a bunch of functions and object as part of the language, but console is not one of them. By convention, browsers define a console object that can be used in the manner you describe. However, since your app is not a browser (and JINT does not do this by itself), there's no console object defined in your namespace (globals).
What you need to do is add a console object that will be accessible in JINT. You can find how to do this in the docs, but here's a simple example of how to add a log function to the engine so it can be used from the JS code (example taken from github).
var engine = new Engine()
.SetValue("log", new Action<object>(Console.WriteLine))
;
engine.Execute(#"
function hello() {
log('Hello World');
};
hello();
");
I am looking at creating a small interpreter for C# that I could load in some applications. Something that could be able to run things like this:
> var arr = new[] { 1.5,2.0 };
arr = { 1.5, 2.0 }
> var sum = arr.Sum();
sum = 3.5
And so I was thinking this could be achieved by creating a dictionary of all the variables and their types and then compile each of the row as they come, and then execute the function, get the result and stick it in the dictionary of variables.
However, it seems to me that this may be actually quite difficult to build and possibly very inefficient.
Then I thought that Powershell was doing what I needed. But how is it done? Can anyone enlighten me as to how Powershell works or what a good way would be to build a .Net interpreter?
How about you host the PowerShell engine in your application and let it do the interpreting for you? For example:
private static void Main(string[] args)
{
// Call the PowerShell.Create() method to create an
// empty pipeline.
PowerShell ps = PowerShell.Create();
// Call the PowerShell.AddScript(string) method to add
// some PowerShell script to execute.
ps.AddScript("$arr = 1.5,2.0"); # Execute each line read from prompt
// Call the PowerShell.Invoke() method to run the
// commands of the pipeline.
foreach (PSObject result in ps.Invoke())
{
Console.WriteLine(result.ToString());
}
}
If your goal is to learn how to build an interpreter, have a look at the interpreter pattern.
Look at either Roslyn http://msdn.microsoft.com/en-US/roslyn or Mono Compiler http://www.mono-project.com/CSharp_Compiler . Both should be able to do what you are looking for
Somthing like this? Or perhaps Roslyn(http://msdn.microsoft.com/en-gb/roslyn)
Added comment as answer, as it seems more useful than I first thought
I want to be able to call VB scripts from C#, which is easy enough, but I need to be able to get back the results from these scripts at times. Should I use the method referenced with something to read back, or should I use a different method? I've found a method to getting data back from powershell scripts using Runspaces and Pipelines, but I don't know enough about this technology to know if it will work with VB scripts as well. Ideally, I'd like to do something similar to the powershell method where I can just pass in the contents of the script without needing to reference an external file and get back the results. Can anyone tell me how to do this? Thanks.
Here's a pretty simple way to do it by listening to an event:
Process vbsProcess = new Process();
vbsProcess.StartInfo.FileName = "yourscript.vbs";
vbsProcess.StartInfo.UseShellExecute = false;
vbsProcess.StartInfo.RedirectStandardOutput = true;
vbsProcess.OutputDataReceived += new DataReceivedEventHandler(YourOutputHandler);
vbsProcess.Start();
vbsProcess.WaitForExit();