MongoDB c# create role? - c#

I'm trying to create a role with the c# driver.
Can anyone please tell me how to do this?
I tried several things like this:
var command = new CommandDocument(
new BsonDocument
{
{ "createRole", "Testentity_read" },
{ "privileges", new BsonArray(new BsonDocument
{
{
"resource", new BsonDocument
{
{"db", "MyDb"},
{"collection", "Testentity"}
}
},
{
"actions", new BsonArray {"read"}
}
})},
{ "roles", new BsonArray()}
}
);
var result = _database.RunCommand(command);
but always getting this exception:
".NET type MongoDB.Bson.BsonElement cannot be mapped to a BsonValue."

I found out how to create a role from C#-driver.
var command = new CommandDocument
{
{
"createRole", "Testentity_find"
},
{
"privileges", new BsonArray
{
new BsonDocument
{
{
"resource", new BsonDocument
{
{"db", "MyDb"},
{"collection", "Testentity"}
}
},
{
"actions", new BsonArray {"find"}
}
}
}
},
{ "roles", new BsonArray()}
};

Related

Avoid the root element while serializing Dictionary with DataContractJsonSerializer

I have a Dictionary like this which I want to serialize in Json:
xrmParentPluginContextProperties = new Dictionary<string, string> {
{ "source", className },
{ "correlationId", executionContext.ParentContext.CorrelationId.ToString() },
{ "depth", executionContext.ParentContext.Depth.ToString() },
{ "initiatingUserId", executionContext.ParentContext.InitiatingUserId.ToString() },
{ "isInTransaction", executionContext.ParentContext.IsInTransaction.ToString() },
{ "isolationMode", executionContext.ParentContext.IsolationMode.ToString() },
{ "message", executionContext.ParentContext.MessageName },
{ "mode", getModeName(executionContext.ParentContext.Mode) },
{ "operationId", executionContext.ParentContext.OperationId.ToString() },
{ "orgId", executionContext.ParentContext.OrganizationId.ToString() },
{ "orgName", executionContext.ParentContext.OrganizationName },
{ "requestId", executionContext.ParentContext.RequestId.ToString() },
{ "userId", executionContext.ParentContext.UserId.ToString() },
{ "entityId", executionContext.ParentContext.PrimaryEntityId.ToString() },
{ "entityName", executionContext.ParentContext.PrimaryEntityName },
{ "type", "Plugin" },
{ "stage", getStageName(executionContext.Stage) }
};
Then I have a helper class holding the dictionary for serialization:
public class DictionarySerializationHelperClass
{
public Dictionary<string, string> dictionary;
public DictionarySerializationHelperClass()
{
}
public DictionarySerializationHelperClass(Dictionary<string, string> dict)
{
this.dictionary = dict;
}
}
I call the serialization like this:
DictionarySerializationHelperClass dictionaryClass = new DictionarySerializationHelperClass(XrmProperties.currentPluginContext);
return SerializationHelper.JsonSerialize(dictionaryClass);
And the serialization itself:
public static string JsonSerialize<T>(T objectToSerialize) where T : class, new()
{
string serialisedJson = null;
DataContractJsonSerializer serializer;
try
{
using (MemoryStream serializationStream = new MemoryStream())
{
if (typeof(T) == typeof(Dictionary<string, string>))
{
serializer = new DataContractJsonSerializer(typeof(T), new DataContractJsonSerializerSettings()
{
UseSimpleDictionaryFormat = true,
RootName = string.Empty
});
}
else
{
serializer = new DataContractJsonSerializer(typeof(T));
}
serializer.WriteObject(serializationStream, objectToSerialize);
serializationStream.Position = 0;
var reader = new StreamReader(serializationStream);
serialisedJson = reader.ReadToEnd();
}
}
catch (Exception ex)
{
string error = $"Error on Serializing JSON: \r\n\r\n{objectToSerialize}";
throw new JsonException(error, ex);
}
return serialisedJson;
}
The problem with the result is that I always get the following json which includes the root element "dictionary":
{
"dictionary":{
"source":"asdasdasd",
"correlationId":"asdasdasd",
"depth":"1",
"initiatingUserId":"asdasdasd",
"isInTransaction":"False",
"isolationMode":"2",
"message":"Retrieve",
"mode":"Synchronus",
"operationId":"asdasd",
"orgId":"esdfsdf",
"orgName":"asdasdasd",
"requestId":"asdasdasd",
"userId":"asdasdasd",
"entityId":"asdasdasd",
"entityName":"incident",
"type":"Plugin",
"stage":"Pre-operation"
}
}
How can I remove this root element to have finally the json looking like this?
{
"source":"asdasdasd",
"correlationId":"asdasdasd",
"depth":"1",
"initiatingUserId":"asdasdasd",
"isInTransaction":"False",
"isolationMode":"2",
"message":"Retrieve",
"mode":"Synchronus",
"operationId":"asdasd",
"orgId":"esdfsdf",
"orgName":"asdasdasd",
"requestId":"asdasdasd",
"userId":"asdasdasd",
"entityId":"asdasdasd",
"entityName":"incident",
"type":"Plugin",
"stage":"Pre-operation"
}
I've tried to set
Root = string.Empty
in the DataContractJsonSerializerSettings but it seems not to help.
Any hint is highly appreciated.

How do I create a document with subdocument in MongoDB with C#

I want to create a nested document with c# in mongodb.
My Code Looks like this
var documnt = new BsonDocument
{
{ "name","test1"},
{ "nachname","test5"},
{ "age","test2"},
{ "wohnort","test3"},
{"test","test4" }
};
collection.InsertOneAsync(documnt);
Console.Read();`
how can i add a subdocument to Wohnort?
Ive found the answer by myself
var documnt = new BsonDocument
{
{ "name","test1"},
{ "nachname","test5"},
{ "age","test2"},
{ "wohnort", new BsonArray
{
new BsonDocument {{"test1","test1"}}}
}
};
collection.InsertMany(documnt);
Console.Read();

Method inside an array in C#

I just got in contact with C# and I was wondering if it's possible to call a method inside an array. I have to say that I'm working with NoSQL database (mongodb).
This is mi code, and I want to call data() method inside that JSON.
static void Main(string[] args)
{
MongoClient client = new MongoClient();
var db = client.GetDatabase("test");
var collection = db.GetCollection<BsonDocument>("collection");
var document = new BsonDocument
{
{ "date", 10/04/2018 },
{ "data", data() }
};
collection.InsertOneAsync(document);
Console.Read();
}
static void data()
{
for (int i = 1; i <= 50; i++)
{
var data = new BsonDocument
{
{ "magnitude"+i, new BsonDocument{
{ "value", 5 }
} }
};
}
}
EDIT: Basically, what I'm trying to create with C# is this json below. I already did it with PHP and now, I'm trying to do it with C#.
{
"_id" : ObjectId("5abb735eb57dce214009035a"),
"date" : 1262300400,
"data" : {
"magnitude1" : {
"value" : 60
},
"magnitude2" : {
"value" : 38
},
"magnitude3" : {
"value" : 200
},
"magnitude4" : {
"value" : 62
},
"magnitude5" : {
"value" : 153
},
"magnitude6" : {
"value" : 176
},
"magnitude7" : {
"value" : 185
},
"magnitude8" : {
"value" : 168
},
.
.
.
You can use methods to gather data but I'm not sure exactly how you're asking it. Related to the code example I'll just give a simple run down, which is basic programming in general, not just C#.
You can write methods that return void or that return a variable of some type (at a minimum).
//Returns void
public void DoSomething()
{
//Do some work
return;
}
//Returns int
public int GetSomething()
{
int result = 100;
return result;
}
When you have methods that return data you can use them as you would a variable; just remember the method will execute every time it's called so it's often best to save the data to a variable. But for your example you can do something like this.
//other code ommitted
var document = new BsonDocument
{
{ "date", 10/04/2018 },
{ "data", getDocuments() }
};
//remaining code omitted
static List<BsonDocument> getDocuments()
{
var documents = new List<BsonDocument>();
for (int i = 1; i <= 50; i++)
{
var document = new BsonDocument
{
{ "magnitude" + i, new BsonDocument { { "value", 5 } } }
};
documents.Add(document);
}
return documents;
}
Now I modified the data() method to return a list of documents and changed the naming to match it but I'm not sure what you wanted to do with the method. That was my best assumption of what you were trying to accomplish by looking at your code so feel free to ignore all of it if it's wrong.
I've could solve it thanks to #Michael .Code below in case helps to anyone.
static void Main(string[] args)
{
MongoClient client = new MongoClient();
var db = client.GetDatabase("test");
var collection = db.GetCollection<BsonDocument>("Collection");
var document = new BsonDocument
{
{ "date", 10/04/2018 },
{ "data", new BsonDocument{ getDocuments() } }
};
collection.InsertOneAsync(document);
Console.Read();
}
static BsonDocument getDocuments()
{
var documents = new BsonDocument();
for (int i = 1; i <= 5; i++)
{
var document = new BsonDocument
{
{ "magnitude" + i, new BsonDocument { { "value", 5 } } }
};
documents.AddRange(document);
}
return documents;
}

How to get a Sitecore item from a fake site

In a unittest I am using Sitecore.FakeDb.
I have extended the sample to add the fakeSite with a rootPath, which gets set.
If I try to retrieve the rootItem with Context.Site.GetItem(rootPath) it returns null.
[Test]
public void FakeSite()
{
// create a fake site context
var fakeSite = new Sitecore.FakeDb.Sites.FakeSiteContext(
new Sitecore.Collections.StringDictionary
{
{ "name", "website" }, { "database", "web" }, { "rootPath", "/sitecore/content/NL" }
});
// switch the context site
using (new Sitecore.Sites.SiteContextSwitcher(fakeSite))
{
var rootItem = Context.Site.Database.GetItem(Context.Site.RootPath); // returns null
Assert.IsNotNull(rootItem);
Assert.AreEqual("website", Sitecore.Context.Site.Name);
Assert.AreEqual("master", Sitecore.Context.Site.Database.Name);
}
}
What am I missing?
You need to add fake item to your fake db first.
See sample code from github here:
public void HowToCreateSimpleItem()
{
using (Sitecore.FakeDb.Db db = new Sitecore.FakeDb.Db
{
new Sitecore.FakeDb.DbItem("Home") { { "Title", "Welcome!" } }
})
{
Sitecore.Data.Items.Item home = db.GetItem("/sitecore/content/home");
Xunit.Assert.Equal("Welcome!", home["Title"]);
}
}
public void HowToCreateHierarchyOfItems()
{
using (Sitecore.FakeDb.Db db = new Sitecore.FakeDb.Db
{
new Sitecore.FakeDb.DbItem("Articles")
{
new Sitecore.FakeDb.DbItem("Getting Started"),
new Sitecore.FakeDb.DbItem("Troubleshooting")
}
})
{
Sitecore.Data.Items.Item articles =
db.GetItem("/sitecore/content/Articles");
Xunit.Assert.NotNull(articles.Children["Getting Started"]);
Xunit.Assert.NotNull(articles.Children["Troubleshooting"]);
}
}
https://github.com/sergeyshushlyapin/Sitecore.FakeDb/wiki/Creating-a-Simple-Item
https://github.com/sergeyshushlyapin/Sitecore.FakeDb/wiki/Creating-a-Hierarchy-of-Items
As #Marek said, I didn't create an item, just set the rootPath to which item it should point.
This is the working test.
[Test]
public void FakeSite()
{
using (Db db = new Db("web")
{
new DbItem("NL") { { "Title", "NL Site" } }
})
{
Item siteItem = db.GetItem("/sitecore/content/NL");
// create a fake site context
var fakeSite = new Sitecore.FakeDb.Sites.FakeSiteContext(
new Sitecore.Collections.StringDictionary
{
{ "name", "website" }, { "database", "web" }, { "rootPath", "/sitecore/content/NL" }
});
// switch the context site
using (new Sitecore.Sites.SiteContextSwitcher(fakeSite))
{
Assert.AreEqual("website", Sitecore.Context.Site.Name);
Assert.AreEqual("web", Sitecore.Context.Site.Database.Name);
var rootItem = Context.Site.Database.GetItem(Context.Site.RootPath);
Assert.IsNotNull(rootItem);
}
}
}
Although I realize that Site means the CM/CD site. Not the MultiSite I was looking for.

MongoDB c# using new driver

I know I may sound to you guys like a total nob but I am.
I am trying to use the mongodb driver in c#. Try to do something like add a record.
I learned today all basic mongodb queries and even tried it with robomongo.
But i don't understand how to use it in c#?
how to call it from the main function??
this is the code I wrote (trying to use mongodb website tutorial):
what is await? what is Task? what does it mean and how to make it work?
Thank you a lot for helping me.
class Program
{
protected static IMongoClient _client;
protected static IMongoDatabase _database;
public static void Main()
{
_client = new MongoClient();
_database = _client.GetDatabase("test");
Task simpleTask = Tasky();
}
public async Task Tasky()
{
var document = new BsonDocument
{
{ "address" , new BsonDocument
{
{ "street", "2 Avenue" },
{ "zipcode", "10075" },
{ "building", "1480" },
{ "coord", new BsonArray { 73.9557413, 40.7720266 } }
}
},
{ "borough", "Manhattan" },
{ "cuisine", "Italian" },
{ "grades", new BsonArray
{
new BsonDocument
{
{ "date", new DateTime(2014, 10, 1, 0, 0, 0, DateTimeKind.Utc) },
{ "grade", "A" },
{ "score", 11 }
},
new BsonDocument
{
{ "date", new DateTime(2014, 1, 6, 0, 0, 0, DateTimeKind.Utc) },
{ "grade", "B" },
{ "score", 17 }
}
}
},
{ "name", "Vella" },
{ "restaurant_id", "41704620" }
};
var collection = _database.GetCollection<BsonDocument>("restaurants");
await collection.InsertOneAsync(document);
}
}
Try to understand simpler version, then read about async/await. Add some documents to your collection using mongo shell and try this:
var collection = new MongoClient("mongodb://localhost").GetServer()
.GetDatabase("your_db").GetCollection<BsonDocument>("your_collection");
var cursor = collection.FindAll();
foreach(var doc in cursor) {
Console.WriteLine(doc);
}
cursor is used to get documents one by one.

Categories

Resources