Trying to get the name of each user in my MongoDB Database - c#

i have a MongoDB Database for my discord but i'm making a simple c# app that will access the database and show each users name and level this is my current code
using MongoDB.Bson;
using MongoDB.Driver;
namespace ExampleApp
{
class Program
{
static async Task Main()
{
MongoClient dbClient = new MongoClient("Connection String");
var database = dbClient.GetDatabase("test");
var collection = database.GetCollection<BsonDocument>("users");
var firstDocument = collection.Find(new BsonDocument()).ForEachAsync(user =>
{
Console.WriteLine(user);
});
Console.Read();
}
}
}
i can't figure out how to print each users name and level like user.name or user.level isn't a thing

You can access the properties of the BsonDocument like this:
Console.WriteLine($"{user["name"].AsString} - {user["level"].AsInt32}");
The indexer is used to retrieve the value. Based on this, you can use the As*-properties to convert the value to the desired data type. Above sample assumes that name is a string and level is an Int32 (int).

Related

CosmosDb - returns null properties .NET

I have a problem with downloading CosmosDb data, even when doing it like in the tutorial.
So in the beginning, my CosmosDb looks like this:
I tried to simply add a new class:
public class CaseModel
{
[JsonProperty("_id")]
public string Id { get; set; }
[JsonProperty("vin")]
public string Vin { get; set; }
}
and then just do like it is mentioned in the documentation
using (FeedIterator<Case> iterator = collection.GetItemLinqQueryable<Case>(true).ToFeedIterator())
{
while (iterator.HasMoreResults)
{
foreach (var item in await iterator.ReadNextAsync())
{
var x = item;
}
}
}
This way, the code iterates over many elements (like it is working),
but the properties are always null - as if the mapping would not work:
Then I tried something like this
using (FeedIterator<Case> feedIterator = collection.GetItemQueryIterator<Case>(
"select * from cases",
null,
new QueryRequestOptions() { PartitionKey = new PartitionKey("shardedKey") }))
{
while (feedIterator.HasMoreResults)
{
foreach (var item in await feedIterator.ReadNextAsync())
{
var x = item;
}
}
}
But this query returns no results.
I have no idea what is wrong.
Lately I was working with CosmosDb on Azure some year ago, and was doing some similar things.
The only thing that I think is strange, that the elements are marked as 'documents'
In the end, my code which should work looks like this
var dbClient = new CosmosClient(info.ConnectionString);
var db = dbClient.GetDatabase(info.DatabaseName);
var collection = db.GetContainer(info.Collection);
using (FeedIterator<CaseModel> iterator = collection.GetItemLinqQueryable<CaseModel>(true)
.ToFeedIterator())
{
while (iterator.HasMoreResults)
{
foreach (var item in await iterator.ReadNextAsync())
{
var x = item;
}
}
}
In the debug windows, I see that 3 steps at the beginning (like connect with connection string, then get database then get-container) work.
You are mixing APIs. The SDK you are referencing to (Microsoft.Azure.Cosmos) is the SQL API SDK: https://learn.microsoft.com/azure/cosmos-db/sql/sql-api-sdk-dotnet-standard
The screenshot in your question is from a Mongo API account.
Either you use a SQL API account with that SDK or you use the C# Mongo driver to interact with your Mongo API account.
SQL API accounts use id as the property for Ids/document identifier, not _id.

Why is my Firebase query giving inconsistent results?

First question here so forgive me if it's not formatted well.
I'm developing an application using Unity and Firebase. When I try to retrieve data from the database, it seems that randomly there will be no data retrieved when there is data present in the DB. Sometimes (hard to say how often) the exact same code will produce correct results by retrieving the data.
It seems like there's some problem with initialization, because if I call that method once and it doesn't retrieve any data, it will consistently do that until I start a new session. So whatever it does (work or not work) will be consistent during each session.
By the way, when I say "not work" I mean that the "stories" variable has no children. I'm expecting it to have 5 children in this case.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Firebase;
using Firebase.Database;
using Firebase.Extensions;
using Firebase.Auth;
public class firebasetest : MonoBehaviour
{
FirebaseDatabase db;
DatabaseReference dbReference;
FirebaseAuth user;
// Start is called before the first frame update
void Start()
{
FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task =>
{
user = Firebase.Auth.FirebaseAuth.DefaultInstance;
dbReference = FirebaseDatabase.DefaultInstance.RootReference;
db = FirebaseDatabase.DefaultInstance;
GetStories();
});
}
public void GetStories()
{
db.GetReference("stories").OrderByChild("postDate").LimitToFirst(100).GetValueAsync().ContinueWithOnMainThread(task =>
{
DataSnapshot stories = task.Result;
// Create new StoryPanel object for each story retrieved
foreach (var child in stories.Children)
{
Debug.Log(child.Child("title").Value);
}
});
}
}
Here's what the data looks like
Hey I had this issue before and it seems like Firebase saves an old version of the DB in the cache . You need to use KeepSynced(true)
Try this and let me know if this works-
public void GetStories()
{
DatabaseReference dtr = FirebaseDatabase.DefaultInstance.GetReference("stories");
dtr.KeepSynced(true); dtr.OrderByChild("postDate").LimitToFirst(100).GetValueAsync().ContinueWithOnMainThread(task =>
{
DataSnapshot stories = task.Result;
// Create new StoryPanel object for each story retrieved
foreach (var child in stories.Children)
{
Debug.Log(child.Child("title").Value);
}
});
}

How to get Unique Display name for VSTS/TFS identity?

I am a writing a .Net application using the VSTS/TFS Rest .Net libraries and in one place I need to update workitems' System.AssignedTo field values and while I do want to adhere to the new(ish), unique displayname rules for identity work item fields, I have a hard time finding a method to get the Unique display name(s) for given identities.
The old / client object model does have an explicit helper method to get these unique names, but I have not found any rest endpoint nor client api method that would provide the same.
So I am wondering, given a list of identities, how do I get their corresponding unique display names which I can use to unambiguously set identity work item fields?
String collectionUri = "http://collectionurl/";
VssCredentials creds = new VssClientCredentials();
creds.Storage = new VssClientCredentialStorage();
VssConnection connection = new VssConnection(new Uri(collectionUri), creds);
TeamHttpClient thc = connection.GetClient<TeamHttpClient>();
List<IdentityRef> irs = thc.GetTeamMembersAsync("ProjectName","TeamName").Result;
foreach (IdentityRef ir in irs)
{
Console.WriteLine(ir.UniqueName);
Console.WriteLine(ir.DisplayName);
}
You could try the code below to get unique name:
using System;
using System.Collections.Generic;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
TfsConfigurationServer tcs = new TfsConfigurationServer(new Uri("http://tfsserver:8080/tfs"));
IIdentityManagementService ims = tcs.GetService<IIdentityManagementService>();
TeamFoundationIdentity tfi = ims.ReadIdentity(IdentitySearchFactor.AccountName, "[TEAM FOUNDATION]\\Team Foundation Valid Users", MembershipQuery.Expanded, ReadIdentityOptions.None);
TeamFoundationIdentity[] ids = ims.ReadIdentities(tfi.Members, MembershipQuery.None, ReadIdentityOptions.None);
foreach (TeamFoundationIdentity id in ids)
{
if (id.Descriptor.IdentityType == "System.Security.Principal.WindowsIdentity")
{
Console.WriteLine(id.DisplayName);
Console.WriteLine(id.UniqueName);
}
}
Console.ReadLine();
}
}
}
foreach (var workItem in workItems)
{
if (workItem.Fields.ContainsKey("System.AssignedTo"))
{
var person = (IdentityRef)workItem.Fields["System.AssignedTo"];
string codereview_reviewer = person.DisplayName;
Console.WriteLine(codereview_reviewer);
}
}

Using Json to Create FormDialog

I am trying to build user and conversation specific dialogs using json schema and I have the LINQ queries generating the json perfectly. If I save a sample of the json to disk and use it like the annotatedsandwich example where it is read from a file on disk, it works great. The json is unique per user and conversation and instead of writing to disk I want to use it in memory. I do not see how to pass the json string to the BuildJsonForm method or alternately how to get the userID information in the BuildJsonForm method in order to generate the json based on the user and conversation. I know I am missing something that will let me do this but I am not finding it. Any assistance with how this should be done would be appreciated. Thank you.
Instead of doing (using the AnnotatedSandwich code)
FormDialog.FromForm(SandwichOrder.BuildJsonForm)
You could just build the BuildFormDelegate and pass your parameters:
string schema = "your jsonform schema";
BuildFormDelegate<JObject> formDelegate = () => SandwichOrder.BuildJsonForm(schema);
FormDialog.FromForm(formDelegate)
Create a custom form builder to which you pass your custom form json schema
[Serializable]
public class CustomFormBuilder
{
public string FormJson { get; set; }
public CustomFormBuilder(string formJson)
{
FormJson = formJson;
}
public IForm<JObject> BuildJsonForm()
{
var schema = JObject.Parse(FormJson);
var form = new FormBuilderJson(schema)
.AddRemainingFields()
.Build();
return form;
}
}
Use as follows (where formJson is your user specific form)
var formBuilder = new CustomFormBuilder(formJson);
var jsonFormDialog = FormDialog.FromForm(
formBuilder.BuildJsonForm,
FormOptions.PromptInStart);
This will avoid the ClosureCaptureExcept‌​ion.

C# NameSpace Error With Producing Output [duplicate]

This question already has answers here:
A namespace cannot directly contain members such as fields or methods?
(4 answers)
Closed 8 years ago.
I am running this code in C# in VS2013 which I got from here: http://tda.codeplex.com/. The code is supposed to gather data from my TD Ameritrade 401k account. The code is running fine but when I look in the output folder no file is saved. I keep getting this two errors that I am unable to fix. What am I doing wrong?
namespace TDAmeritrade.Samples
{
using System;
using TDAmeritrade;
class Program
{
static void Main()
{
// Initialize TD Ameritrade client, provide additional config info if needed
var client = new TDAClient();
// Log in to the TD Ameritrade website with your user ID and password
client.LogIn("jessicasusername", "jessicaspassword");
// Now 'client.User' property contains all the information about currently logged in user
var accountName = client.User.Account.DisplayName;
// Get stock quotes snapshot.
var quotes = client.GetQuotes("GOOG, AAPL, $SPX.X, DUMMY");
// 'quotes.Error' contains a list of symbols which have not been found
var errors = quotes.Errors;
// Find symbols matching the search string
var symbols = client.FindSymbols("GOO");
// Get historical prices
var prices = client.GetHistoricalPrices("GOOG, AAPL", StartDate: DateTime.Today.AddDays(-7), EndDate: DateTime.Today.AddDays(-1));
}
}
}
const string SaveFileToLocation = #"C:\Users\jessica\Desktop\json_data";
string json = JsonConvert.SerializeObject(prices, Formatting.Indented);
using (StreamWriter writer = new StreamWriter(SaveFileToLocation))
{
writer.Write(json);
}
Error 1 A namespace cannot directly contain members such as fields or
methods
Error 2 Expected class, delegate, enum, interface, or struct
this is because you declare some variable outside of a class. just put theme in class Program.
namespace TDAmeritrade.Samples
{
using System;
using TDAmeritrade;
class Program
{
const string SaveFileToLocation = #"C:\Users\jessica\Desktop\json_data";
static void Main()
{
// find best place for these codes.
string json = JsonConvert.SerializeObject(prices, Formatting.Indented);
using (StreamWriter writer = new StreamWriter(SaveFileToLocation))
{
writer.Write(json);
}
// Initialize TD Ameritrade client, provide additional config info if needed
var client = new TDAClient();
// Log in to the TD Ameritrade website with your user ID and password
client.LogIn("jessicasusername", "jessicaspassword");
// Now 'client.User' property contains all the information about currently logged in user
var accountName = client.User.Account.DisplayName;
// Get stock quotes snapshot.
var quotes = client.GetQuotes("GOOG, AAPL, $SPX.X, DUMMY");
// 'quotes.Error' contains a list of symbols which have not been found
var errors = quotes.Errors;
// Find symbols matching the search string
var symbols = client.FindSymbols("GOO");
// Get historical prices
var prices = client.GetHistoricalPrices("GOOG, AAPL", StartDate: DateTime.Today.AddDays(-7), EndDate: DateTime.Today.AddDays(-1));
}
}
}
The way your code should be arranged is thus:
using System;
using TDAmeritrade;
namespace TDAmeritrade.Samples
{
class Program
{
const string SaveFileToLocation = #"C:\Users\jessica\Desktop\json_data";
static void Main()
{
// Initialize TD Ameritrade client, provide additional config info if needed
var client = new TDAClient();
// Log in to the TD Ameritrade website with your user ID and password
client.LogIn("jessicasusername", "jessicaspassword")
// Get historical prices
var prices = client.GetHistoricalPrices("GOOG, AAPL", StartDate: DateTime.Today.AddDays(-7), EndDate: DateTime.Today.AddDays(-1));
//You cannot create json until the prices variable has been declared!
string json = JsonConvert.SerializeObject(prices, Formatting.Indented);
using (StreamWriter writer = new StreamWriter(SaveFileToLocation))
{
writer.Write(json);
}
}
}
}

Categories

Resources