fauna / faunadb-csharp Goto Github PK
View Code? Open in Web Editor NEWC# driver for FaunaDB v4
Home Page: https://fauna.com
License: Other
C# driver for FaunaDB v4
Home Page: https://fauna.com
License: Other
Package FaunaDB.Client 1.1.0 is not compatible with netcoreapp1.1 (.NETCoreApp,Version=v1.1). Package FaunaDB.Client 1.1.0 supports: net45 (.NETFramework,Version=v4.5)
Please add support to dotnet core. It was used in modern platform and especially Amazon Lambda
Hey folks,
Just came across FaunaDb. While checking out this driver I noticed that it seems to create a new HttpClient every time.
A lot of the serverless platforms (FaaS ones like Lambda and Azure Functions) have limits on the number of connections that can be created inside a function and inappropriate usage HttpClient is frequently the cause of many errors.
The old way to fix this was to use a static http client but that has problems as well. The newer way is to use an HttpClientFactory which does a much better job of managing connections.
Anyways. Just wanted to bring that up. The serverless tier of FaunaDb is what caught my eye and this is a frequent gotcha for those scenarios.
Hi,
Regarding JSON serializer, I see that FaunaDB.Client
is using Newtonsoft.Json
!!
Check out the System.Text.Json
package, I highly recommend using it, it is Fast plus it's owned and maintained by Microsoft.
Starting ASP.NET Core 3.1, System.Text.Json
is the default JSON Serializer, and Newtonsoft.Json
will be removed starting .NET 5.
I'm new to Fauna and having a VERY hard time understanding how to query and return a collection of objects.
In EntityFramework I would access a property on my database connection like:
dbContext.MyCollectionName
and be able to interact with the contents with LINQ syntax. I struggle to find the right combination of Query(Paginate(Match()))).To<MyObject[]>().Value to get objects read from Fauna. Can we put together a simple example document that shows Fauna 101 for each of the CRUD operations?
I have created a custom type called User, which utilises the FaunaField reflection method for specifying properties of the objects.
Please provide more information on how to decode arrays of custom types, as this id poorly described in your documentation for the C# driver.
The problem can be repreduced from the following example.
Example:
public class User
{
[FaunaField("id")]
public string Id { get; set; }
[FaunaField("name")]
public string Name { get; set; }
...
}
I then created a mutation for creating a new document in my 'user' collection, which works fine, and returns the expected result.
Example:
var result = await _fauna.client.Query(
Create(
Collection("user"),
Obj("data", Encoder.Encode(upsertUser))));
return Decoder.Decode<User>(result.At("data"));
Now my issue is retrieving the full list of user documents in my 'users' collection. I verified that i retrieve all the right data, but once i decode the data with Decoder.Decode or <<....>>.To<User[]>() i get NULL values.
Example:
public async Task<User[]> GetUser()
{
var result = await _fauna.client.Query(
Map(
Paginate(
Documents(Collection("user"))),
Lambda("X", Get(Var("X")))));
var userResult = result.At("data").To<User[]>().Value;
return userResult;
}
Raw Output:
Arr(
ObjectV(
ref: RefV(id = "286263727644213761",
collection = RefV(id = "user", collection = RefV(id = "collections"))),
ts: LongV(1609261214770000),
data: ObjectV(id: StringV(d9853632-7b8f-42d1-b217-eb314e58d417),
name: StringV(Test User),
email: StringV([email protected]),
ObjectV(
ref: RefV(id = "286263756128780801",
collection = RefV(id = "user", collection = RefV(id = "collections"))),
ts: LongV(1609261241940000),
data: ObjectV(id: StringV(56a06ea3-ef0b-4ded-a627-ceab63385fe2),
name: StringV(Test User),
email: StringV([email protected]),
)
)
Decoded Output:
{
"data": {
"user": [
{
"id": null,
"name": null,
"email": null,
"access": null
},
{
"id": null,
"name": null,
"email": null,
"access": null
}
]
}
}
Expected Output:
{
"data": {
"user": [
{
"id": "Sample ID",
"name": "Sample Name",
"email": "Sample Email",
},
{
"id": "Sample ID",
"name": "Sample Name",
"email": "Sample Email",
}
]
}
}
After learning about faunadb API for sometimes I felt unfamiliar with the style of API
Such as
client.Query(
Paginate(Match(Index("spells_by_element"), "fire")));
client.Query(
Do(
Create(
Ref(Class("magical_creatures"), 1),
Obj("data", Obj("name", "Hen Wen"))),
Get(Ref(Class("magical_creatures"), 1))));
I felt that some functions that require Expr
as parameter should be extension method. And so we could write it like this
client.Query(Index("spells_by_element").Match("fire").Paginate());
client.Query(Do(Class("magical_creatures").Ref(1).Create(Obj("data", Obj("name", "Hen Wen")))
,Class("magical_creatures").Ref(1).Get()));
/// or
client.Query(Class("magical_creatures").Ref(1).Create(Obj("data", Obj("name", "Hen Wen")))
.Then(Class("magical_creatures").Ref(1).Get()));
Could we have a sub namespace for this style api? (FaunaDB.LINQ maybe?)
StringV
is sealed class, so the only way to create a derived class is to inherit from ScalarValue<string>
. The internal Decoder
works one way only: ScalarValue<string>
Derived Class to StringV
but not the other way around.
Digging deeper into internal decoder implementation, the root cause is the usage of
typeof(StringV).IsAssignableFrom(typeof(DerivedClass))
typeof(DerivedClass).IsAssignableFrom(typeof(StringV))
which in both ways evaluates to false
and throws Invalid Cast Exception
.
This can be fixed in one of two ways:
StringV
not sealedIsAssignableFrom
check with string
or ScalarValue<string>
check.Save instance of User without filling out one of FirstName, LastName or Login makes Decoder.Decode throw exception with message: Missing required property: PropertyName
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Login Login { get; set; }
}
public class Login
{
public LoginTypeEnum LoginType { get; set; }
public string Username { get; set; }
public string PasswordHash { get; set; }
public string FacebookToken { get; set; }
}
It would be nice if Decoder handles properties with null values simply by setting these to null when calling Decode.
would be nice if you could have a Uri be encoded as a string into faunadb. this can be accomplished similar to the [FaunaDate] and [FaunaTime] attributes. You can have a [FaunaString] that encodes the object by calling the .ToString() and the decoder calls a constructor with a single parameter, string.
Same as fauna/faunadb-ruby#135
User's feedback:
C# driver: Noticing that enums are getting encoded as int's. Would it be possible to configure the Encoder to use the string value for an enum instead?
This makes it much easier when quering using the Query Console.
In addition to DateTime
. class DateTimeOffset
is more useful for working with time in C#. Please add support to it like DateTime
and please make implicit conversion for these classes
Consider the following structure
public class Person
{
public string Name { get; set; }
public Dictionary<string, object> Metadata { get; set; }
}
The encoder doesn't seem to have an issue and serializes the dictionary correctly; here's the encoded value ToString()
.
ObjectV(name: StringV(Japanfy),metadata: ObjectV(comm.status: StringV(connected),comm.satellites: LongV(8)))
However, the decoder doesn't behave well with this and doesn't decode the values of the dictionary. It just creates an empty object for each.
{"Name":"Japanfy","Metadata":{"comm.status":{},"comm.satellites":{}}}
Because C# has the limitation of 100 nanosecond precision on the DateTime object there is no way to add nanosecond time to fauna. Sometimes a user may want to store a nanosecond precision Time via a Unix epoch timestamp. Fauna has the Epoch function that can accomplish this. The encoder could take a long and run it through that function after detecting a [FaunaEpoch(EpochPrecision.Nanosecond)] attribute. Then the decoder would convert fauna time into a ts long value.
My Intellisense is complaining "No overload for method 'Create' takes two arguments" with the following snippet:
serverClient.Query(
Create(
Collection("posts"),
Obj("data", Obj("title", "What I had for breakfast .."))));
I'm following the docs exactly. I'm not sure where this function comes from. Also, if you navigate to 'Create' in the official csharp docs, 'CreateRole' is instead the example code snippet displayed':
https://docs.fauna.com/fauna/current/api/fql/functions/create?lang=csharp
...what? 😑
There is a good documentation about this process on nuget page
https://docs.nuget.org/create/creating-and-publishing-a-package
If a non 2XX error code is received, then resultRequest.ResponseContent
is deserialized by Newtonsoft.Json.
However, the ResponseContent received is sometimes not JSON. One user received the following error; it's possible that the ResponseContent is html rather than a JSON string.
Error :Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
It may be helpful to handle this error more gracefully and provide the user with a better message.
Intellisense is not available for any objects in this package, and that makes discoverability of the features and interactions with the Fauna client very difficult for new developers
I would like to know whether there would ever be a faunadb extension for EFcore since it's one of the main ways that people manipulate databases in .Net
The follow links seems to be a good starting point:
https://docs.nuget.org/create/enforced-package-conventions
http://blogs.msmvps.com/punitganshani/2015/06/21/5-steps-to-targeting-multiple-net-frameworks/
This library isn't working on Blazor WASM because of this 'x-query-timeout' header usage.
All HTTPClient calls get exceptions like:
Access to fetch at 'https://db.fauna.com/' from origin 'https://.....' has been blocked by CORS policy: Request header field x-query-timeout is not allowed by Access-Control-Allow-Headers in preflight response.
Until this issue is solved on the FaunaDB cloud side you can use the following workaround:
Remove the 'x-query-timeout' header in the request.
public class MessageHandler : DelegatingHandler
{
public MessageHandler(HttpClientHandler httpClientHandler) :
base(httpClientHandler)
{ }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// Dont use header 'X-Query-Timeout' for CORS policy
request.Headers.Remove("X-Query-Timeout");
return base.SendAsync(request, cancellationToken);
}
}
public async void ContactFaunaDb()
{
var httpClient = new HttpClient(new MessageHandler(new HttpClientHandler()));
var faunaDb = new FaunaClient(endpoint: Endpoint, secret: Secret, httpClient: httpClient);
var rawIndexValues = await faunaDb.Query(Paginate(Match(Index("some_index"))));
/// etc....
}
This is a feature request. JSON convention says field names should start lowercase, while C# Properties start with an uppercase letter. Newtonsoft.Json converts the casing when serializing/deserializing, the FaunaDB driver should do so as well. Right now I either have to lowercase my model properties, or uppercase JSON fields, due to the lack of conversion (neither of which is a satisfactory solution).
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.