I am trying to extract only key attributes through mongocxx but using find() and find_one() function .I am not able to pull only key values.
int main(int, char**)
{
mongocxx::instance inst{};
mongocxx::client conn{mongocxx::uri{}};
auto collection = conn["test"]["restaurants"];
bsoncxx::stdx::optional<bsoncxx::document::value> maybe_result =collection.find_one(document{} << finalize);
if(maybe_result)
{
std::cout <<bsoncxx::to_json(*maybe_result)<< "\n";
}
}
Above code pull only the one document with keys and their values and I want only keys.
Can anyone help me on this?
Related
I am using gremlin with Azure Cosmos DB. I'm using this code to get a list of files from a graph database.
public async Task<List<string>> GetFilesWithMoreThanOneFilename()
{
List<string> list = new List<string>();
using (var gremlinClient = new GremlinClient(gremlinServer, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType))
{
var resultSet = await gremlinClient.SubmitAsync<dynamic>("g.V().hasLabel('file').where(out().count().is(gt(1)))");
if (resultSet.Count > 0)
{
foreach (var result in resultSet)
{
string output = JsonConvert.SerializeObject(result);
list.Add(output);
}
}
}
return list;
}
The output string looks like this:
{"id":"0a37e4896b6310b6d152f6cf89336173ffb89b819f7955494322e0f0bec017b4","label":"file","type":"vertex","properties":{"fileSize":[{"id":"456b087c-7cf3-43ea-a482-0f31219bc520","value":"41096"}],"mimeType":[{"id":"d849b065-16f8-465b-986c-f8e0fdda9ac7","value":"text/plain"}]}}
My Question is how I can get a single value from the result. For example just the ID or the mimeType or is the only possiblity to work with the output and string manipulation?
Due to your output data is in json format, so you could use Newtonsoft.Json to read the data.
I create a json file with your data, you could just parse the json data without file. And just read the id and properties.fileSize
static void Main(string[] args)
{
JObject jsonData = JObject.Parse(File.ReadAllText( "test.json"));
Console.WriteLine("id:"+jsonData["id"].ToString());
Console.WriteLine("properties:"+jsonData["properties"]["fileSize"].ToString());
Console.ReadLine();
}
And here is the result:
Hope this could help you, if yo ustill have other questions, please let me know.
Update: if you want to get the value in the array, you could use this to get the value:
Console.WriteLine("mimeType.value:" + jsonData["properties"]["mimeType"][0]["value"].ToString());
In general, you should only retrieve the values that you actually need and not vertices with all their properties and then filter locally. This is equivalent to relational databases where you wouldn't usually do SELECT * and instead do something like SELECT name.
Additionally, you should specify the return type you're expecting which allows Gremlin.NET to deserialize the result for you so you don't have to do that yourself.
These two suggestions together give you something like this:
var names = await client.SubmitAsync<string>(
"g.V().hasLabel('person').where(out().count().is(gt(1))).values('name')");
Console.WriteLine($"First name: {names.First()}");
names is then just a ResultSet<string> which implements IReadOnlyCollection<string>.
When releasing documents the scan operator should get logged to a file. I know this is a kofax system variable but how do I get it from the ReleaseData object?
Maybe this value is hold by the Values collection? What is the key then? I would try to access it by using
string scanOperator = documentData.Values["?scanOperator?"].Value;
Kofax's weird naming convention strikes again - during setup, said items are referred to as BatchVariableNames. However, during release they are KFX_REL_VARIABLEs (an enum named KfxLinkSourceType).
Here's how you can add all available items during setup:
foreach (var item in setupData.BatchVariableNames)
{
setupData.Links.Add(item, KfxLinkSourceType.KFX_REL_VARIABLE, item);
}
The following sample iterates over the DocumentData.Values collection, storing each BatchVariable in a Dictionary<string, string> named BatchVariables.
foreach (Value v in DocumentData.Values)
{
switch (v.SourceType)
{
case KfxLinkSourceType.KFX_REL_VARIABLE:
BatchVariables.Add(v.SourceName, v.Value);
break;
}
}
You can then access any of those variables by key - for example Scan Operator's User ID yields the scan user's domain and name.
Note: This code used to work as I used PostgreSQL. After switching to MySQL these functions stopped working for some reason.
I double checked: languageId and shopId are valid IDs and there is a valid entry of supported_language resembling the inserted record after fetchOne() but it returns null.
private Long addSupportedLanguage(Long languageId, Long shopId) {
Long value = this.ctx.insertInto(SHOP_LANGUAGE)
.set(SHOP_LANGUAGE.LANGUAGE_ID, languageId)
.set(SHOP_LANGUAGE.SHOP_ID, shopId)
.returning()
.fetchOne() // After this line I see the record in my db but it returns null
.getValue(SHOP_LANGUAGE.LANGUAGE_ID);
return value;
}
I also tried using
.returning(RESTAURANT_LANGUAGE.LANGUAGE_ID)
but the result is the same.
I am observing something similar when calling returnin() after a delete() statement:
public void deleteEmailVerificationToken(String token) {
ShopAdminVerificationTokenRecord shopAdminVerificationTokenRecord = this
.ctx.delete(SHOP_ADMIN_VERIFICATION_TOKEN)
.where(SHOP_ADMIN_VERIFICATION_TOKEN.VERIFICATION_TOKEN.eq(token))
.returning()
.fetchOne()
.into(SHOP_ADMIN_VERIFICATION_TOKEN);
if(shopAdminVerificationTokenRecord != null) {
LOGGER.debug("Deleted verification token for " + shopAdminVerificationTokenRecord.getUserEmail());
} else {
LOGGER.debug("The given token was not found.");
}
}
I don't understand why this is happening. The new record gets correctly inserted but still I cannot fetch that record immediately after insertion.
I created SHOP_LANGUAGE and all other objects using the jOOQ code generator. This is the SQL CREATE TABLE statement that I used to create the table for a MySQL database:
CREATE TABLE shop_language (
shop_id BIGINT NOT NULL,
CONSTRAINT fk__shop_language__shop
FOREIGN KEY (shop_id)
REFERENCES shop(id),
language_id BIGINT NOT NULL,
CONSTRAINT fk__shop_language__language
FOREIGN KEY (language_id)
REFERENCES language(id),
PRIMARY KEY (shop_id, language_id)
);
As mentioned in the comments:
DELETE .. RETURNING is not supported for MySQL as documented by the #Support annotation on the relevant returning() methods.
I'm doin a simple query linq to retrieve a label from an optionSet. Looks like the formatted value for the option set is missing. Someone knows why is not getting generated?
Best Regards
Sorry for the unclear post. I discovered the problem, and the reason of the missing key as formattedvalue.
The issue is with the way you retrieve the property. With this query:
var invoiceDetails = from d in xrmService.InvoiceSet
where d.InvoiceId.Value.Equals(invId)
select new
{
name = d.Name,
paymenttermscode = d.PaymentTermsCode
}
I was retrieving the correct int value for the option set, but what i needed was only the text. I changed the query this way:
var invoiceDetails = from d in xrmService.InvoiceSet
where d.InvoiceId.Value.Equals(invId)
select new
{
name = d.Name,
paymenttermscode = d.FormattedValues["paymenttermscode"]
}
In this case I had an error stating that the key was not present. After many attempts, i tried to pass both the key value and the option set text, and that attempt worked just fine.
var invoiceDetails = from d in xrmService.InvoiceSet
where d.InvoiceId.Value.Equals(invId)
select new
{
name = d.Name,
paymenttermscode = d.PaymentTermsCode,
paymenttermscodeValue = d.FormattedValues["paymenttermscode"]
}
My guess is that to retrieve the correct text associated to that option set, in that specific entity, you need to retrieve the int value too.
I hope this will be helpful.
Best Regards
You're question is rather confusing for a couple reasons. I'm going to assume that what you mean when you say you're trying to "retrieve a label from an OptionSet" is that you're attempting to get the Text Value of a particular OptionSetValue and you're not querying the OptionSetMetadata directly to retrieve the actual LocalizedLabels text value. I'm also assuming "formatted value for the option set is missing" is referring to the FormattedValues collection. If these assumptions are correct, I refer you to this: CRM 2011 - Retrieving FormattedValues from joined entity
The option set metadata has to be queried.
Here is an extension method that I wrote:
public static class OrganizationServiceHelper
{
public static string GetOptionSetLabel(this IOrganizationService service, string optionSetName, int optionSetValue)
{
RetrieveOptionSetRequest retrieve = new RetrieveOptionSetRequest
{
Name = optionSetName
};
try
{
RetrieveOptionSetResponse response = (RetrieveOptionSetResponse)service.Execute(retrieve);
OptionSetMetadata metaData = (OptionSetMetadata)response.OptionSetMetadata;
return metaData.Options
.Where(o => o.Value == optionSetValue)
.Select(o => o.Label.UserLocalizedLabel.Label)
.FirstOrDefault();
}
catch { }
return null;
}
}
RetrieveOptionSetRequest and RetrieveOptionSetResponse are on Microsoft.Xrm.Sdk.Messages.
Call it like this:
string label = service.GetOptionSetLabel("wim_continent", 102730000);
If you are going to be querying the same option set multiple times, I recommend that you write a method that returns the OptionSetMetadata instead of the label; then query the OptionSetMetadata locally. Calling the above extension method multiple times will result in the same query being executed over and over.
This question already has answers here:
How to get the identity of an inserted row?
(15 answers)
Closed 8 years ago.
public int retrieveID()
{
int lastEntry = 0;
try
{
queryString = "Select ID from Database";
myComm = new OleDbCommand(queryString, myConn);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return lastEntry;
}
I want to retrieve the last primary key used in access database, whereas i set my primary key as autonumber.
elaborating more..
I am working on a database application and want to utilize the primary key, eg if the last entry in the database was 10, i want to retrieve 10, i tried simple query but that didnot work.
If you are using an OLEDB connection then this should work
queryString = "SELECT ##IDENTITY";
Note that this should be called immediately after the INSERT that creates the record for which you want to save the ID value. If your code were to create other records with Identity (AutoNumber) fields then the ##IDENTITY value will be updated (replaced) by those calls.