run a primitive mycouch query - c#

I'm new to couchdb and mycouch. I'm trying to implement a very simple query, I just want to get the results of a view and save it into my DTO class.
My couchdb query works, when I query it manually via HTTP:
http://localhost:5984/mydb/_design/tshirts/_view/getAllTshirts
However, when I try running it from my app using mycouch, I can't get to run it. My current query:
using MyCouch.Requests;
using MyCouch.Responses;
// (...)
using (var client = new Client("http://localhost:5984/samples")) {
var query = new QueryViewRequest("getAllTshirts");
ViewQueryResponse<TShirt[]> result = await client.Views.QueryAsync<TShirt[]>(query);
Console.WriteLine (result);
}
For some reason, it won't find the Client class. I found an example where Client is used on github, as you can see, I'm using all the MyCouch related namespaces as in the example.
I also tried using MyCouchStore instead:
using (var store = new MyCouchStore("http://localhost:5984/", "samples")) {
var query = new QueryViewRequest("getAllTshirts");
ViewQueryResponse<TShirt[]> result = await store.Views.QueryAsync<TShirt[]>(query);
Console.WriteLine (result);
}
However, the store doesn't contain any property named Views.
Any ideas how to query my view using MyCouch?

This is what I do, with the MyCouchStore
using (var store = new MyCouchStore("http://user:password#localhost:5984", "samples")) {
var query = new Query("tshirts", "getAllTshirts");
var rows = store.QueryAsync<TShirt>(query).Result;
}

Apparantely, the documentation was not up to date. The constructor requires now 2 arguments, the second being an optional bootstrapper. This worked for me:
var client = new Client("http://localhost:5984/samples", null)

Related

How to create new AutoML DataSet for simple classification (C#)

As part of ML automation process I want to dynamically create new AutoML model. I'm using C# (.net framework) and Google.Cloud.AutoML.V1.
After trying to run CreateDataSet code:
var autoMlClient = AutoMlClient.Create();
var parent = LocationName.FromProjectLocation(_projectId, _locationId);
var dataset = new Google.Cloud.AutoML.V1.Dataset();
dataset.DisplayName = "NewDataSet";
var response = autoMlClient.CreateDataset(parent, dataset);
I get the following error:
Field: dataset.dataset_metadata; Message: Required field not set
According to this user manual I should set Dataset Metadata Type, but the list contains only specific types of classifications (Translation/ImageClassifications etc.), I can't find a simple classification type.
How do I create a simple classification data set with the API ? in the AutoML UI its just with a simple button click ("NEW DATASET") - and have to provide only name & region - no classification type.
I also tried to set:
dataset.TextClassificationDatasetMetadata =
new TextClassificationDatasetMetadata() { ClassificationType = ClassificationType.Multiclass };
But I was unable to import data to it (got too many errors of invalid inputs from the input CSV file), I guess its related to the reason that the input format is not suitable for Text Classification.
UPDATE
I've just notice that the Nuget works with AutoML v1 but v1 beta does contains TablesDatasetMetadata Dataset Metadata Type for normal classifications. I'm speechless.
I also experienced this scenario today while creating a dataset using the NodeJS client. Since the Google AutoML table service is in the beta level you need to use the beta version of the AutoML client. In the Google cloud documentation they have used the beta client to create a dataset.
In NodeJS importing the beta version require('#google-cloud/automl').v1beta1.AutoMlClient instead of importing the normal version (v1) require('#google-cloud/automl').v1 worked for me to successfully execute the create dataset functionality.
In C# you can achieve the same through a POST request. Hope this helps :)
After #RajithaWarusavitarana comment, and my last question update , below is the code that did the trick. The token is being generated by GoogleClientAPI nuget and AutoML is handled by REST.
string GcpGlobalEndPointUrl = "https://automl.googleapis.com";
string GcpGlobalLocation = "us-central1"; // api "parent" parameter
public string GetToken(string jsonFilePath)
{
var serviceAccountCredentialFileContents = System.IO.File.ReadAllText(jsonFilePath);
var credentialParameters = NewtonsoftJsonSerializer.Instance.Deserialize<JsonCredentialParameters>(serviceAccountCredentialFileContents);
var initializer = new ServiceAccountCredential.Initializer(credentialParameters.ClientEmail)
{
Scopes = new List<string> { "https://www.googleapis.com/auth/cloud-platform" }
};
var cred = new ServiceAccountCredential(initializer.FromPrivateKey(credentialParameters.PrivateKey));
string accessToken = cred.GetAccessTokenForRequestAsync("https://oauth2.googleapis.com/token").Result;
return accessToken;
}
public void GetDataSetList(string projectId, string token)
{
var restClient = new RestClient(GcpGlobalEndPointUrl);
var createDataSetReqUrl = $"v1beta1/projects/{projectId}/locations/{GcpGlobalLocation}/datasets";
var createDataSetReq = new RestRequest(createDataSetReqUrl, Method.GET);
createDataSetReq.AddHeader("Authorization", $"Bearer {token}");
var createDatasetResponse = restClient.Execute(createDataSetReq);
createDatasetResponse.Dump();
}
I took the token generation code from google-api-dotnet-client Test File

Get element by key with Firebase in c#

I am coming to a problem where I have a guid style schema in my firebase database, which I want to display a text that is DisplayText, but for some reason my code is not working. I am using a FirebaseDatabase.Net Wrapper. How can I map it in order to read from the database properly using a guid way schema? thanks for the help.
Code:
private async Task ShowQuestion()
{
var firebase = new
FirebaseClient("https://PROJECT_URL.firebaseio.com/");
var dinos = await firebase
.Child("Questions")
.OrderByKey()
.StartAt("DisplayText")
.LimitToFirst(1)
.OnceAsync<GameController>();
foreach (var dino in dinos)
{
Console.WriteLine(dinos);
}
I tried doing:
string page = "https://PROJECT_URL.firebaseio.com/Questions/DisplayText.json?orderBy"DisplayText"&limitToFirst=1";
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(page))
using (HttpContent content = response.Content)
{
// Reading the string.
string result = await content.ReadAsStringAsync();
Console.WriteLine(result);
// Getting a reference to the text component.
questionDisplayText = GetComponent<Text>();
questionDisplayText.text = result.ToString();
questionDisplayText.text = result.Trim(new char[] {'"'});
}
Firebase queries take a two-step approach:
You order the child nodes on their key, their value, or the value of a property.
You then filter on values of the thing you ordered on.
Since you order by key, the filtering operations like StartAt() compare the key to the value you passed. And since there is no key DisplayText, there are no results.
If you want to read the first question, you shouldn't use a startAt().
FirebaseClient("https://PROJECT_URL.firebaseio.com/");
var dinos = await firebase
.Child("Questions")
.OrderByKey()
.LimitToFirst(1)
If you want to return the results ordered by the value of their DisplayText property, it'd be something like this:
FirebaseClient("https://PROJECT_URL.firebaseio.com/");
var dinos = await firebase
.Child("Questions")
.OrderByChild("DisplayText")
.LimitToFirst(1)
Since you indicated that you want to use the REST API, here's an example of how to do that:
https://stackoverflow.firebaseio.com/59384124.json?orderBy="DisplayText"&startAt="How"
If you want to embed this string in your code, you have a few options. The main ones:
string page = "https://PROJECT_URL.firebaseio.com/Questions/DisplayText.json?orderBy=\"DisplayText\"&startAt=\"How\"&limitToFirst=1";
Or
string page = #"https://PROJECT_URL.firebaseio.com/Questions/DisplayText.json?orderBy=""DisplayText""&startAt=""How""&limitToFirst=1";
And don't forget: in order to be able to filter on the server, you'll need to define an index in your security rules. In my case I did so with:
"59384124": { ".indexOn": "DisplayText" },
Also see:
The documentation for the Firebase REST API
This blog post on embedding quotes in C# strings

Connect to OrientDB using Gremlin.Net

Hi I'm trying to connect to Orient.DB (Community 3.0.18) with gremlin support from a easy console application and Gremlin.net.
I'm using the standard demodb. I can't get any gremlin query run, I get:
ResponseException: ServerSerializationError: Error during
serialization: Infinite recursion (StackOverflowError)
This is my code:
var gremlinServer = new GremlinServer("localhost", 8182, enableSsl:false, username: "root", password: "xxxx");
using (var gremlinClient = new GremlinClient(gremlinServer, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType))
{
var query = "g.V(\"33:5\")";
// Create async task to execute the Gremlin query.
var resultSet = gremlinClient.SubmitAsync<dynamic>(query).Result;
Console.WriteLine();
}
I also tried GraphSON3Reader and GraphSON3Writer having the same result.
I have two big doubt:
1) How to let this work
2) How can I specify the database? for example on CosmosDB you have to specify it in the user parameter, I tried also this solutino but again no luck.

How does one connect to the RootDSE and/or retrieve highestCommittedUSN with System.DirectoryServices.Protocols?

Using System.DirectoryServices, one can get the highestCommittedUSN this way:
using(DirectoryEntry entry = new DirectoryEntry("LDAP://servername:636/RootDSE"))
{
var usn = entry.Properties["highestCommittedUSN"].Value;
}
However, I need to get this information from a remote ADLDS using System.DirectoryServices.Protocols, which does not leverage ADSI. Following is a simplified code sample of what I'm attempting to do:
using(LdapConnection connection = GetWin32LdapConnection())
{
var filter = "(&(highestCommittedUSN=*))";
var searchRequest = new SearchRequest("RootDSE", filter, SearchScope.Subtree, "highestCommittedUSN");
var response = connection.SendRequest(searchRequest) as SearchResponse;
var usn = response.Entries[0].Attributes["highestCommittedUSN"][0];
}
Unfortunately this kicks back a "DirectoryOperationException: The distinguished name contains invalid syntax." At first I thought there might be something wrong in GetWin32LdapConnection() but that code is called in numerous other places to connect to the directory and never errors out.
Any ideas?
Thanks for the idea, Zilog. Apparently to connect to the RootDSE, you have to specify null for the root container. I also switched the filter to objectClass=* and the search scope to "base." Now it works!
using(LdapConnection connection = GetWin32LdapConnection())
{
var filter = "(&(objectClass=*))";
var searchRequest = new SearchRequest(null, filter, SearchScope.Base, "highestCommittedUSN");
var response = connection.SendRequest(searchRequest) as SearchResponse;
var usn = response.Entries[0].Attributes["highestcommittedusn"][0];
}
I hope this saves someone else some time in the future.

How to create indexes in MongoDB via .NET

I've programmatically created a new document collection using the MongoDB C# driver.
At this point I want to create and build indexes programmatically. How can I do that?
Starting from v2.0 of the driver there's a new async-only API. The old API should no longer be used as it's a blocking facade over the new API and is deprecated.
The currently recommended way to create an index is by calling and awaiting CreateOneAsync with an IndexKeysDefinition you get by using Builders.IndexKeys:
static async Task CreateIndexAsync()
{
var client = new MongoClient();
var database = client.GetDatabase("HamsterSchool");
var collection = database.GetCollection<Hamster>("Hamsters");
var indexKeysDefinition = Builders<Hamster>.IndexKeys.Ascending(hamster => hamster.Name);
await collection.Indexes.CreateOneAsync(new CreateIndexModel<Hamster>(indexKeysDefinition));
}
you should use CreateIndex as EnsureIndex is marked obsolete for future compatibility with the next versions of MongoDB:
var client = new MongoClient("mongodb://localhost");
var db = client.GetServer().GetDatabase("db");
var collection = db.GetCollection<Hamster>("Hamsters");
collection.CreateIndex(IndexKeys<Hamster>.Ascending(_ => _.Name));
The overload of CreateOneAsync in the currently accepted answer is now marked as obsolete with the message "Use CreateOneAsync with a CreateIndexModel instead." Here's how you do it:
static async Task CreateIndex(string connectionString)
{
var client = new MongoClient(connectionString);
var database = client.GetDatabase("HamsterSchool");
var collection = database.GetCollection<Hamster>("Hamsters");
var indexOptions = new CreateIndexOptions();
var indexKeys = Builders<Hamster>.IndexKeys.Ascending(hamster => hamster.Name);
var indexModel = new CreateIndexModel<Hamster>(indexKeys, indexOptions);
await collection.Indexes.CreateOneAsync(indexModel);
}
Something like this should do:
var server = MongoServer.Create("mongodb://localhost");
var db = server.GetDatabase("myapp");
var users = db.GetCollection<User>("users");
users.EnsureIndex(new IndexKeysBuilder().Ascending("EmailAddress"));
Please see the following bits in the documentation:
http://api.mongodb.org/csharp/current/html/06bcd201-8844-3df5-d170-15f2b423675c.htm
There is an entire area on Indexing under the Definitions and Builders documentation page:
http://mongodb.github.io/mongo-csharp-driver/2.4/reference/driver/definitions/#index-keys
Example:
IndexKeysDefinition<MyModel> keys = "{ Reference: 1 }";
var indexModel = new CreateIndexModel<MyModel>(keys);
await _context.Indexes.CreateOneAsync(indexModel);
the easiest way to create indexes in c# is by using the driver wrapper library MongoDB.Entities. here's an example of creating a text index:
DB.Index<Author>()
.Key(a => a.Name, Type.Text)
.Key(a => a.Surname, Type.Text)
.Create();
and to do a full-text search, you simply do:
DB.SearchText<Author>("search term");
haven't seen anything else that makes it simpler than that.

Categories