MongoDB db.runCommand() from C# - c#

Hi I'm using C# with MongoDB Official driver v2.2.4 and I want to run db.runCommand() on the admin database.
So far i have this and i am able to connect to the admin database but db.runCommand is giving me this error "An unhandled exception of type 'System.FormatException' occurred in MongoDB.Bson.dll Additional information: JSON reader was expecting a value but found 'db'."
MongoClient client = new MongoClient();
database = client.GetDatabase("admin");
var collection = database.GetCollection<BsonDocument>("test");
var commandResult = database.RunCommand<string>(#"db.createCollection(test1)");
After I resolve this test I want to run this command from C# but I am stuck.
db.runCommand( { addshard : “localhost:10001”, name : “shard10001” } );
Any one can resolve this problem and provide me with a good explanation and example. After some search I have tried this code does seems to make more sense but still getting an error.
"Additional information: Command addshard failed: no such command: 'addshard', bad cmd: '{ addshard: "192.168.1.4:27017", name: "shard1" }'."
Any ideas please of what I'm doing wrong! Thanks.
var addShardCommand = new BsonDocument {
{ "addshard", "192.168.1.4:27017"},
{ "name", "shard1" }
};
var addShardResult = database.RunCommand<BsonDocument>(addShardCommand);

You need to check what is the correct command in mongodb. like sometime name need Document object instead of just string.
I am using something like this. check if this help
var name = new BsonDocument { { "name", "regions" } };
var command = new BsonDocument { { "listCollections", 1 }, { "filter", name } };
var result = Database.RunCommand<BsonDocument>(command);
var k = result.ToJson();
Here name is again object which I found from this documentation https://docs.mongodb.com/manual/reference/command/listCollections/
Some more help you can take from here
https://zetcode.com/csharp/mongodb/

Related

RFC error "Element BAPIRETURN1 of container metadata ... is unknown"

In my C# program which uses the SAP .NET connector, I want to call the RFC function "BAPI_GET_PAYROLL_RESULT_LIST" and read the result.
I looked at the function with SE37. There I found out that the export parameter should be BAPIRETURN1, which is a structure.
So I searched for an example code of an RFC call and modified it for my case.
I have already tried to read the table BAPI7004_RL, because it was in the information in SE37 and I don't know if I have to use the export parameter or the table.
This is my code:
string appServerHost = ConfigurationManager.AppSettings["AppServerHost"];
string name = ConfigurationManager.AppSettings["Name"];
string systemnumber = ConfigurationManager.AppSettings["SystemNumber"];
string user = ConfigurationManager.AppSettings["User"];
string pw = ConfigurationManager.AppSettings["Password"];
string client = ConfigurationManager.AppSettings["Client"];
string language = ConfigurationManager.AppSettings["Language"];
RfcConfigParameters parms = new RfcConfigParameters
{
{ RfcConfigParameters.AppServerHost, appServerHost },
{ RfcConfigParameters.Name, name },
{ RfcConfigParameters.SystemNumber, systemnumber },
{ RfcConfigParameters.User, user },
{ RfcConfigParameters.Password, pw },
{ RfcConfigParameters.Client, client },
{ RfcConfigParameters.Language, language }
};
RfcDestination dest = RfcDestinationManager.GetDestination(parms);
RfcRepository repo = dest.Repository;
IRfcFunction fnc = dest.Repository.CreateFunction("BAPI_GET_PAYROLL_RESULT_LIST");
fnc.SetValue("employeenumber", "0001");
fnc.Invoke(dest);
RfcStructureMetadata TableMetaData = dest.Repository.GetStructureMetadata("BAPIRETURN1");
IRfcStructure stru = fnc.GetStructure("BAPIRETURN1"); //BAPI7004_RL
//IRfcTable tabDetail = fnc.GetTable("BAPI7004_RL"); //BAPIRETURN1
After the line IRfcStructure stru = fnc.GetStructure("BAPIRETURN1") an exception is thrown at runtime, which says:
Element BAPIRETURN1 of container BAPI_GET_PAYROLL_RESULT_LIST unknown
When I try it with the table, I get the same result.
Where is the error in my code? Or is it maybe a permission problem?
The name of the parameter is "RETURN" and not "BAPIRETURN1" as specified by you.
"BAPIRETURN1" is the type name, i.e. the name for the associated meta data.

How to get list of all collections in RavenDB 4

There was this approach in previous versions -
var terms = new GetTermsOperation("Raven/DocumentsByEntityName", "Tag", "", 1024);
But now it doesn't work. I tried to use another command:
var op = new GetCollectionStatisticsOperation();
var collectionStats = store.Maintenance.Send(op);
But it throws an error - System.ArgumentNullException: 'Value cannot be null.
Parameter name: key'
Then i found out how to get the all collections from the browser admin panel:
from #all_docs select distinct #metadata.#collection
How to translate that snippet to c# code?
If you don't have a database assigned at the document store level, you need to specify it explicitly, like so:
var collectionStats = store.Maintenance.ForDatabase("db-name").Send(op);
I found a clue - my DocumentStore variable didn't had an assigned Database ( it was assigned in OpenSession constructor):
//Wrong variant
IDocumentStore store = new DocumentStore()
{
Urls = new string[] { Host }, /*Database = "testdb"*/
}
using (IDocumentSession session = store.OpenSession(dbName))
{
//some code
}
//Good variant
IDocumentStore store = new DocumentStore()
{
Urls = new string[] { Host }, Database = "testdb"
}
using (IDocumentSession session = store.OpenSession())
{
//some code
}

Upload data to Google Sheets using C# .NET API v4 from ADO DataReader

Using the Google Sheets API Version v4 for .NET in C# how do the values get assigned to the ValueRange from an ADO DataReader.
The online documentation from Google typically has code that looks like this:
// TODO: Assign values to desired properties of `requestBody`. All existing
// properties will be replaced:
Data.ValueRange requestBody = new Data.ValueRange();
Clearly this is where the data values should be set. In testing, it is possible to do the following successfully:
string range = "MySheet!A2:B";
var MyDataList = new List<object>() { "My Cell Text", "More text" };
RequestBody.Values = new List<IList<object>> { MyDataList };
Previous attempts to solve this issue involved creating a class to match the data from the reader and making a List of the objects. Then a line of code like the following was used:
RequestBody.Values = new List<IList<object>> { new List<object>(MyDataAsList) } ;
This returns the following error:
Google.GoogleApiException was unhandled
HResult=-2146233088
Message=Google.Apis.Requests.RequestError
Invalid values[1][0]:
I'm open to suggestions on other solutions to get the content of a SQL query to output to a Google Sheet.
TIA,
Joshua

mongoDB C# Driver is not returning any data

I am having a problem where C# Driver is not returning any data with either using async-await or synchronous method.
When trying to run in the command line, it works perfectly, here's the snippet:
db.Collection_StudentResults.aggregate([ { $unwind: "$modules" }, { $match: { "studentNumber": "", "modules.code": "" } } ])
and here's how I have it setup in C#:
public static async Task<BsonDocument> getSingleStudentData(string studentNumber)
{
var client = new MongoClient("mongodb://localhost:27017");
var db = client.GetDatabase("dbStudents");
var collection = db.GetCollection<BsonDocument>("Collection_StudentResults");
var aggregate = collection.Aggregate()
.Unwind("modules")
.Match(new BsonDocument { { "studentNumber", studentNumber } });
var result = await aggregate.ToListAsync();
return result.FirstOrDefault();
}
Drivers Used: v2.4.0
MongoDB Version: v3.2.10
In Collection_StudentResults, the first document contains the studentNumber and modules array, in the modules array each document has code field.
Please help!
Thanks
Sorry - my bad, bad bad bad...
I missed the db = db.getSiblingDB in my builder script - which caused the data to go into the root database.
All the best.

Create dll file in runtime doesn't work in c#

I am trying to create a DLL file in runtime ,as a matter of fact i need to save an encoded data to DLL .My code is like this :
class DllFile
{
public static void CreateDllFile(string source)
{
var provider = new CSharpCodeProvider();
var options = new CompilerParameters
{
OutputAssembly = "test.dll"
};
var results = provider.CompileAssemblyFromSource(options, new[] { source });
}
}
I expect from this code to create a dll file but it doesn't create
The error is :The pointer for this method was null
Best regards.Any ideas will be appreciated.
Compilation errors are reported via the returned value:
var results = provider.CompileAssemblyFromSource(options, new[] { source });
Now check results, and in particular results.Errors.
You can also check results.NativeCompilerReturnValue - that should be 0 for success, and non-zero for failure.
Any errors would be in the Errors property of the CompilerResults returned from the CompileAssemblyFromSource method. Have you tried printing them out to see if there are errors ?
CompilerResults results = provider.CompileAssemblyFromSource(options, new[] { source });
foreach(CompilerError error in results.Errors)
{
Console.WriteLine(error.ToString());
}

Categories

Resources