Code Monkey home page Code Monkey logo

sdk-for-dotnet's Introduction

Appwrite .NET SDK

License Version Build Status Twitter Account Discord

This SDK is compatible with Appwrite server version 1.4.x. For older versions, please check previous releases.

Appwrite is an open-source backend as a service server that abstract and simplify complex and repetitive development tasks behind a very simple to use REST API. Appwrite aims to help you develop your apps faster and in a more secure way. Use the .NET SDK to integrate your app with the Appwrite server to easily start interacting with all of Appwrite backend APIs and tools. For full API documentation and tutorials go to https://appwrite.io/docs

Installation

.NET

Add this reference to your project's .csproj file:

<PackageReference Include="Appwrite" Version="0.7.1" />

You can install packages from the command line:

# Package Manager
Install-Package Appwrite -Version 0.7.1

# or .NET CLI
dotnet add package Appwrite --version 0.7.1

Getting Started

Initialize & Make API Request

Once you have installed the package, it is extremely easy to get started with the SDK; all you need to do is import the package in your code, set your Appwrite credentials, and start making API calls. Below is a simple example:

using Appwrite;
using Appwrite.Services;
using Appwrite.Models;

var client = new Client()
  .SetEndpoint("http://cloud.appwrite.io/v1")  
  .SetProject("5ff3379a01d25")                 // Your project ID
  .SetKey("cd868db89");                         // Your secret API key

var users = new Users(client);

var user = await users.Create(
    userId: ID.Unique(),
    email: "[email protected]",
    password: "password",
    name: "name");

Console.WriteLine(user.ToMap());

Error Handling

The Appwrite .NET SDK raises an AppwriteException object with message, code, and response properties. You can handle any errors by catching AppwriteException and presenting the message to the user or handling it yourself based on the provided error information. Below is an example.

var users = new Users(client);

try
{
    var user = await users.Create(
        userId: ID.Unique(),
        email: "[email protected]",
        password: "password",
        name: "name");
} 
catch (AppwriteException e)
{
    Console.WriteLine(e.Message);
}

Learn more

You can use the following resources to learn more and get help

Preparing Models for Databases API

For the .NET SDK, we use the Newtonsoft.Json library for serialization/deserialization support. The default behavior converts property names from PascalCase to camelCase on serializing to JSON. In case the names of attributes in your Appwrite collection are not created in camelCase, this serializer behavior can cause errors due to mismatches in the names in the serialized JSON and the actual attribute names in your collection.

The way to fix this is to add the JsonProperty attribute to the properties in the POCO class you create for your model.

For e.g., if you have two attributes, name (string type) and release_date (DateTime type), your POCO class would be created as follows:

public class TestModel
{
  [JsonProperty("name")]
  public string Name { get; set; }

  [JsonProperty("release_date")]
  public DateTime ReleaseDate { get; set; }
}

The JsonProperty attribute will ensure that your data object for the Appwrite database is serialized with the correct names.

Contribution

This library is auto-generated by Appwrite custom SDK Generator. To learn more about how you can help us improve this SDK, please check the contribution guide before sending a pull-request.

License

Please see the BSD-3-Clause license file for more information.

sdk-for-dotnet's People

Contributors

abnegate avatar adityaoberai avatar christyjacob4 avatar eldadfux avatar lohanidamodar avatar sangwan5688 avatar torstendittmann avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sdk-for-dotnet's Issues

๐Ÿš€ Feature: Proposal for Building a separate API SDK - "Appwrite.Core" for Modern .NET Version (6+ onwards) Using Refit, System.Text, and HttpClientFactory

๐Ÿ”– Feature description

The proposed feature involves building a separate API SDK - "Appwrite.Core" based on the existing API SDK to make it compatible with modern .NET versions (specifically .NET 6 and beyond). The new approach will utilize the Refit library, System.Text, and HttpClientFactory to optimize the SDK's performance, simplify the development process, and provide a seamless integration experience for developers.

๐ŸŽค Pitch

Why Implement this Feature:

Upgrading the API SDK for modern .NET versions is essential to keep up with the latest advancements and ensure that our SDK remains relevant and efficient. By rebuilding the SDK using Refit, System.Text, and HttpClientFactory, we can leverage their capabilities to enhance the overall development experience and the quality of our SDK.

Advantages of the Proposed Approach:

a) Refit Integration:
Refit is a powerful library that simplifies the creation of type-safe API clients. By utilizing Refit, we can eliminate the need for writing boilerplate code to handle HTTP requests and responses. Instead, developers can define API interfaces with attributes, making the SDK more concise and expressive. This will improve the readability and maintainability of the codebase.

Example of using Refit:

[Headers("User-Agent: MyApp")]
public interface IApiClient
{
    [Get("/posts/{id}")]
    Task<Post> GetPostById(int id);
}

b) System.Text for JSON Serialization:
.NET 6 includes significant improvements in System.Text.Json for JSON serialization and deserialization. By adopting System.Text.Json as the default JSON serializer for the SDK, we can benefit from its superior performance and reduced memory allocation compared to third-party libraries. This will lead to faster data processing and a more efficient SDK.

c) HttpClientFactory Integration:
The HttpClientFactory is designed to manage HttpClient instances efficiently, minimizing the overhead of creating new connections for each API request. By integrating HttpClientFactory, we can improve the SDK's performance and mitigate potential issues related to HttpClient misuse, such as socket exhaustion and connection leaks.

Example Implementation details

Get Account

image

using Refit;

namespace Appwrite.Core.Apis;

internal interface IAccount
{
    [Get("/account")]
    Task<User> Get(CancellationToken cancellationToken = default);
}

namespace Appwrite.Core.Services;

public class Account : HttpClientProvider
{
    private readonly IAccount _accountApi;

    public Account(Client client)
    {
        _accountApi = base.GetRestService<IAccount>(client);
    }

    /// <summary>
    /// Get Account
    /// </summary>
    /// <para>Get currently logged in user data as JSON object.</para>
    /// <param name="cancellationToken">Cancellation Token</param>
    /// <returns>User</returns>
    public async Task<User> Get(CancellationToken cancellationToken = default)
    {
        return await _accountApi.Get(cancellationToken);
    }
}

The SDK will automatically handle the HTTP request and response, making the integration process intuitive and efficient.

Example Client invocation:

using Appwrite.Core;
using Appwrite.Core.Services;

var endpoint = String.Empty;
var project = String.Empty;
var apikey = String.Empty;

var client = new Client()
    .SetEndpoint(endpoint)
    .SetProject(project)
    .SetKey(apikey);
try
{
    var account = new Account(client);

    // optional
    CancellationTokenSource newSource = new CancellationTokenSource();
    newSource.Cancel();

    var newTeam = await account.Get(newSource.Token);

    Console.WriteLine("Done !");
}
catch (TaskCanceledException ex)
{
    Console.WriteLine($"TaskCanceledException - {ex.Message}");
}
catch (AppwriteException ex)
{
    Console.WriteLine($"AppwriteException - {ex.Message}");
}
catch (Exception ex)
{
    Console.WriteLine($"Exception - {ex.Message}");
}

๐Ÿšง For more implementation details checkout - https://github.com/initinll-forks/sdk-for-dotnet/tree/dotnet-6

๐Ÿ‘€ Have you spent some time to check if this issue has been raised before?

  • I checked and didn't find similar issue

๐Ÿข Have you read the Code of Conduct?

๐Ÿ› Bug Report: query.limit unnoticed

๐Ÿ‘Ÿ Reproduction steps

Hi. I asked this on discord already with no success for an answer. Maybe I got wrong what I found in the documents, but when I

{
    int number = 5;
    try
    {
        List<string> queryList = new List<string>{
            {Query.Equal("validated", false)},
            {Query.Equal("language", lang)},
            {Query.Limit(number)}
    } 
[โ€ฆ]
    var quotes = await databases.ListDocuments(
            databaseId: databaseId,
            collectionId: collectionId,
            queries: queryList);
        return Results.Ok(quotes);        
}

๐Ÿ‘ Expected behavior

returns 5 Documents where validated is false and language is (whatever is set in query parameter)

๐Ÿ‘Ž Actual Behavior

returns 274 documents. Where validated is false and language is (whatever was set in query parameter)

๐ŸŽฒ Appwrite version

Different version (specify in environment)

๐Ÿ’ป Operating system

Linux

๐Ÿงฑ Your Environment

The Api (dotnet api project) runs on ubuntu 22.04.3 LTS and queries another machine running Appwrite 1.4.3 using dotnet-SDK 0.6.0

๐Ÿ‘€ Have you spent some time to check if this issue has been raised before?

  • I checked and didn't find similar issue

๐Ÿข Have you read the Code of Conduct?

๐Ÿ› Bug Report: Bug acquiring users on server side

๐Ÿ‘Ÿ Reproduction steps

this method:

public static User From(Dictionary<string, object> map) => new User(
id: map["$id"].ToString(),
createdAt: map["$createdAt"].ToString(),
updatedAt: map["$updatedAt"].ToString(),
name: map["name"].ToString(),
password: map["password"]?.ToString(),
hash: map["hash"]?.ToString(),
hashOptions: map["hashOptions"]?.ToString(),
registration: map["registration"].ToString(),
status: (bool)map["status"],
labels: ((JArray)map["labels"]).ToObject<List<object>>(),
passwordUpdate: map["passwordUpdate"].ToString(),
email: map["email"].ToString(),
phone: map["phone"].ToString(),
emailVerification: (bool)map["emailVerification"],
phoneVerification: (bool)map["phoneVerification"],
prefs: Preferences.From(map: ((JObject)map["prefs"]).ToObject<Dictionary<string, object>>()!),
accessedAt: map["accessedAt"].ToString()
);

the issue is that when you do this on the server from the JWT token:

var client = new Client()
        .SetEndpoint("https://cloud.appwrite.io/v1")    // Your API Endpoint
        .SetProject(projectid)                     // Your project ID
        .SetJWT(token);

var appWriteUser=(await (new Account(client)).Get());

The way it does this internally is that Get() makes an api call, retrieves a dictionary and then calls the User.From
since the dictionary does not retrieve the password, you get an exception with Key not found "password" and it crashes
meaning you can never retrieve a user on the server side, never
exact exception details details

"error":"System.Collections.Generic.KeyNotFoundException: The given key 'password' was not present in the dictionary.\r\n   at System.Collections.Generic.Dictionary2.get_Item(TKey key)\r\n   at Appwrite.Models.User.From(Dictionary2 map)\r\n   at Appwrite.Services.Account.<Get>g__Convert|1_0(Dictionary2 it)\r\n   at Appwrite.Client.Call[T](String method, String path, Dictionary2 headers, Dictionary2 parameters, Func2 convert)

๐Ÿ‘ Expected behavior

it should create an user instance with the missing information (no password)

๐Ÿ‘Ž Actual Behavior

exception as explained, and no user created

๐ŸŽฒ Appwrite version

Version 0.10.x

๐Ÿ’ป Operating system

Windows

๐Ÿงฑ Your Environment

No response

๐Ÿ‘€ Have you spent some time to check if this issue has been raised before?

  • I checked and didn't find similar issue

๐Ÿข Have you read the Code of Conduct?

Potential memory leak and deferred garbage collection cycle identified

There are a few potential memory leaks and deferred garbage collection cycle that I identified. I thought of bringing this to community's notice. Also, I will take this opportunity to suggest some better coding practices.

  1. The following classes implement the IDisposable interface. If we don't call the Dispose method on them ourselves, then we potentially leave it to the garbage collector to dispose of and then cleanup the memory. This typically happens in 2 cycles of garbage collection(The garbage collector has 3 cycles). However, if we call the dispose method ourselves before exiting a block scope, the garbage collector will then take just one cycle to clean up the memory and end up doing less work. We have to remind ourselves that garbage collection is a very expensive process).

HttpResponseMessage - Docs
HttpRequestMessage - Docs
HttpClient - Docs

  1. Newing up the HttpClient in the construction is typically a bad practice. It is always better to rely on Dependency Injection. The typical way to implement it is using this would be to accept IHttpClientFactory in the constructor.

IHttpClientFactory - Docs

then add dependency injection to inject a version of the IHttpClientFactory.

Microsoft.Extensions.DependencyInjection - Nuget

then create a ServiceCollectionExtensions static class and create a method like this -

// Clients of this Nuget package need to utilize this before using the classes.
public static IServiceCollection AddAppWrite(this IServiceCollection serviceCollection, IConfiguration configuration)
{
    // This should add the IHttpClientFactory that you want to register with proper retry policies using Poly.NET
   // This method should also house any other interface and class registrations with the DI system that are needed.
  // If it were me, I would also implement an IAppWriteUriProvider which has methods that returns the URI of all the areas that are needed and inject an implementation here.
}

and then use the IHttpClientFactory.CreateClient method to create the actual HttpClient. This typically is also an extension method. Not the HttpClient is a class that needs eager disposing.

IHttpClientFactory.CreateClient - Docs

Also, I would never expose the underlying HttpResponseMessage directly to the consumer, but instead return the string and let abstract away any other Http only resemblance. The reason I say this is because tomorrow you guys might implement the APIs using gRPC but to the consumer, it should not feel like anything has changed.

I apologize for all the ranting. My only intention is to really help the community with whatever knowledge I have.

๐Ÿ“š Documentation:

๐Ÿ’ญ Description

The readme states that to install the package in your projects, issue the command Install-Package Appwrite -Version 0.3.0.

This returns the error Install-Package : NU1102: Unable to find package Appwrite with version (>= 0.3.0)

It appears that the nuget repo only has up to version 0.2.0.

๐Ÿ‘€ Have you spent some time to check if this issue has been raised before?

  • I checked and didn't find similar issue

๐Ÿข Have you read the Code of Conduct?

  • I read the Code of Conduct

GetFileDownload returns a string without Project parameter.

Hello.

So Im trying to use some Storage methods in functions.

So Im trying to use GetFileDownload to finish my work on .net sample function for object detection.
From documentation it creates link like this:
/v1/storage/files/{fileId}/download

for link generated by the Storage class:
http://localhost/v1/storage/files/60f85fa05c655/download?
I get a response :
"{"message":"Missing or unknown project ID","code":400,"version":"0.9.1"}"

BUT works for
http://localhost/v1/storage/files/60f85fa05c655/download?project=60f85f2973fd8

๐Ÿ› Bug Report

Have you spent some time to check if this issue has been raised before?

Yup.

To Reproduce

Call
var url = Storage.GetFileDownload("id")

Expected behavior

I'd either:
-get downloaded bytes (the OKeiest solution :D )
-get a request with api_key/projectId in headers and parameters(such as quality) as parameters
-get a string with everything as parameter

Actual Behavior

get a string with parameters but without projectID which is necessary to actually access the file we want.

Your Environment

Appwrite 0.9.1
Appwrite sdk for .net 0.2.0

๐Ÿ“š Documentation: How to use the dotnet SDK?

๐Ÿ’ญ Description

for .NET there is missing documentation
my question is how to filter ListDocuments() function
database.ListDocuments(String collectionId, list ? filters = null, ...)

my question is how to filter any example pls , i dont know list<object> ? filters = null

but from my flutter and web experience, I was doing like this
queries: [
Query.equal("uid", uid),
],
so how can Filer data inside ListDocuments() function in .NET, thanks.

๐Ÿ‘€ Have you spent some time to check if this issue has been raised before?

  • I checked and didn't find similar issue

๐Ÿข Have you read the Code of Conduct?

  • I read the Code of Conduct

Upgrade our issue templates to use GitHub issue forms โœ๏ธ

Introduction

GitHub has recently rolled out a public beta for their issue forms feature. This would allow you to create interactive issue templates and validate them ๐Ÿคฏ.

Appwrite currently uses the older issue template format. Your task is to create GitHub issue forms for this repository. Please use Appwrite's issue templates as a reference for this PR.

Tasks summary:

  • Fork & clone this repository
  • Prepare bug report issue form in .github/ISSUE_TEMPLATE/bug.yaml
  • Prepare documentation issue form in .github/ISSUE_TEMPLATE/documentation.yaml
  • Prepare feature request issue form in .github/ISSUE_TEMPLATE/feature.yaml
  • Push changes to master and test issue forms on your fork
  • Submit pull request

If you need any help, reach out to us on our Discord server.

Are you ready to work on this issue? ๐Ÿค” Let us know, and we will assign it to you ๐Ÿ˜Š

Happy Appwriting!

๐Ÿš€ Feature: Support GA Release

๐Ÿ”– Feature description

Any plans to officially support the Appwrite server version 1.x, now that it's gone to GA?

๐ŸŽค Pitch

Would be nice to support the latest, full release. (Please). :D

๐Ÿ‘€ Have you spent some time to check if this issue has been raised before?

  • I checked and didn't find similar issue

๐Ÿข Have you read the Code of Conduct?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.