### Install Unity Test Framework (Preview) Source: https://github.com/supabase-community/supabase-csharp/wiki/Unity Install a specific preview version of the Unity Test Framework that supports running async tests. ```bash com.unity.test-framework ``` -------------------------------- ### Initialize Supabase Client in C# Source: https://github.com/supabase-community/supabase-csharp/wiki/Desktop-Clients This snippet demonstrates the complete initialization process for the Supabase client in a C# application, including network status monitoring and authentication setup. It's adapted from a Unity example but applicable to other UI frameworks. ```csharp using Supabase; using Supabase.Gotrue; using Supabase.Gotrue.Interfaces; using Client = Supabase.Client; private async void Initialize() { // We create an object to monitor the network status. NetworkStatus NetworkStatus = new(); // Create a Supabase objects object. SupabaseOptions options = new(); // Set the options to auto-refresh the JWT token with a background thread. options.AutoRefreshToken = true; // Create the client object. Note that the project URL and the anon key are // available in the Supabase dashboard. In addition, note that the public anon // key is not a security risk - in JavaScript projects, this key is visible // in the browser viewing source! _supabase = new Client("https://project URL", "supabase PUBLIC anon key", options); // This adds a listener for debug information, especially useful for dealing // with errors from the auto-refresh background thread. _supabase.Auth.AddDebugListener(DebugListener); // Here we are getting the auth service and passing it to the network status // object. The network status object will tell the auth service when the // network is up or down. NetworkStatus.Client = (Supabase.Gotrue.Client)_supabase.Auth; // Here we are setting up the persistence layer. This is an object that implements // the IGotrueSessionPersistence interface. This is used to store the JWT // token so the user won't have to log in every time they start the app. _supabase.Auth.SetPersistence(new UnitySession()); // Here we are setting up the listener for the auth state. This listener will // be called in response to the auth state changing. This is where you would // update your UI to reflect the current auth state. _supabase.Auth.AddStateChangedListener(UnityAuthListener); // We now instruct the auth service to load the session from disk using the persistence // object we created earlier _supabase.Auth.LoadSession(); // In this case, we are setting up the auth service to allow unconfirmed user sessions. // Depending on your use case, you may want to set this to false and require the user // to validate their email address before they can log in. _supabase.Auth.Options.AllowUnconfirmedUserSessions = true; // This is a well-known URL that is used to test network connectivity. // We use this to determine if the network is up or down. string url = $"{SupabaseSettings.SupabaseURL}/auth/v1/settings?apikey={SupabaseSettings.SupabaseAnonKey}"; try { // We start the network status object. This will attempt to connect to the // well-known URL and determine if the network is up or down. _supabase!.Auth.Online = await NetworkStatus.StartAsync(url); } catch (NotSupportedException) { // On certain platforms, the NetworkStatus object may not be able to determine // the network status. In this case, we just assume the network is up. _supabase!.Auth.Online = true; } catch (Exception e) { // If there are other kinds of error, we assume the network is down, // and in this case we send the error to a UI element to display to the user. // This PostMessage method is specific to this application - you will // need to adapt this to your own application. PostMessage(NotificationType.Debug, "Network Error {e.GetType()}", e); _supabase!.Auth.Online = false; } if (_supabase.Auth.Online) { // If the network is up, we initialize the Supabase client. await _supabase.InitializeAsync(); // Here we are fetching the current settings for the auth service as exposed // by the server. For example, we might want to know which providers have been // configured, or change the behavior if auto-confirm email is turned off or on. Settings = await _supabase.Auth.Settings(); } } ``` -------------------------------- ### Install UniTask via Git URL Source: https://github.com/supabase-community/supabase-csharp/wiki/Unity Install the UniTask library for async/await support in Unity using its Git URL in the Package Manager. ```bash https://github.com/Cysharp/UniTask.git?path=src/UniTask/Assets/Plugins/UniTask ``` -------------------------------- ### Install NuGet CLI on macOS Source: https://github.com/supabase-community/supabase-csharp/wiki/Unity Use Homebrew to install the NuGet command-line interface on macOS. ```bash brew install nuget ``` -------------------------------- ### Install NuGet CLI on Windows Source: https://github.com/supabase-community/supabase-csharp/wiki/Unity Use Chocolatey to install the NuGet command-line interface on Windows. ```powershell choco install nuget.commandline ``` -------------------------------- ### Initialize and Use GoTrue Stateless Client Source: https://github.com/supabase-community/supabase-csharp/wiki/Server-Side-Applications This example demonstrates how to initialize a GoTrue stateless client and invite a user using a service role key. Ensure the service role key is kept secure as it grants administrative privileges. ```csharp using static Supabase.Gotrue.StatelessClient; IGotrueStatelessClient client = new StatelessClient(); var user = $"{RandomString(12)}@supabase.io"; var serviceRoleKey = GenerateServiceRoleToken(); var result = await _client.InviteUserByEmail(user, serviceRoleKey, Options); ``` -------------------------------- ### Install supabase-csharp NuGet Package Source: https://github.com/supabase-community/supabase-csharp/wiki/Server-Side-Applications Use this command to add the supabase-csharp library to your .NET project via the NuGet package manager. ```bash dotnet add package supabase-csharp ``` -------------------------------- ### Install Supabase C# Library on macOS Source: https://github.com/supabase-community/supabase-csharp/wiki/Unity Install the supabase-csharp NuGet package into your Unity project's Assets directory using the NuGet CLI. ```bash nuget install supabase-csharp -OutputDirectory ./Assets/Supabase -Framework netstandard2.0 ``` -------------------------------- ### Accessing Supabase C# Client Services Source: https://github.com/supabase-community/supabase-csharp/wiki/Home Demonstrates how to get instances of various clients (Auth, Postgrest, Storage, Realtime) and invoke Supabase functions. This snippet covers common entry points for interacting with the Supabase backend. ```csharp // Get the Auth Client var auth = supabase.Auth; // Get the Postgrest Client for a Model var table = supabase.From(); // Invoke an RPC Call await supabase.Rpc("hello_world", null); // Invoke a Supabase Function await supabase.Functions.Invoke("custom_function"); // Get the Storage Client var storageBucket = supabase.Storage.From("bucket_name"); // Use syntax for broadcast, presence, and postgres_changes var realtime = supabase.Realtime.Channel("room_1"); // Alternatively, shortcut syntax for postgres_changes await supabase.From().On(ListenType.All, (sender, response) => { switch (response.Event) { case Constants.EventType.Insert: break; case Constants.EventType.Update: break; case Constants.EventType.Delete: break; } Debug.WriteLine($"[{response.Event}]:{response.Topic}:{response.Payload.Data}"); }); ``` -------------------------------- ### Install NewtonsoftJson Support for Blazor WASM Source: https://github.com/supabase-community/supabase-csharp/wiki/Desktop-Clients For projects defaulting to System.Text.Json, such as Blazor WASM, install the NewtonsoftJson integration package. This is required for JSON serialization compatibility. ```bash dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson --version 7.0.5 ``` -------------------------------- ### Add Newtonsoft Json Package Source: https://github.com/supabase-community/supabase-csharp/wiki/Unity Install the Unity-specific version of the Newtonsoft JSON package via the Unity Package Manager by name. ```bash com.unity.nuget.newtonsoft-json ``` -------------------------------- ### Configure NewtonsoftJson in Initialization Code Source: https://github.com/supabase-community/supabase-csharp/wiki/Desktop-Clients After installing the NewtonsoftJson package, include this line in your application's initialization code to enable its use for JSON handling. ```csharp builder.Services.AddControllers().AddNewtonsoftJson(); ``` -------------------------------- ### Save Session Data to Cache Source: https://github.com/supabase-community/supabase-csharp/wiki/Authorization-with-Gotrue This C# method provides an example of saving session data to the user's cache directory using `Xamarin.Essentials`. It serializes the session object and writes it to a file. Ensure you implement corresponding load and destroy methods. ```csharp // Add callback methods for above // Here's a quick example of using this to save session data to the user's cache folder // You'll want to add methods for loading the file and deleting when the user logs out internal bool SaveSession(Session session) { var cacheFileName = ".gotrue.cache"; try { var cacheDir = FileSystem.CacheDirectory; var path = Path.Join(cacheDir, cacheFileName); var str = JsonConvert.SerializeObject(session); using (StreamWriter file = new StreamWriter(path)) { file.Write(str); file.Dispose(); return Task.FromResult(true); }; } catch (Exception err) { Debug.WriteLine("Unable to write cache file."); throw err; } } ``` -------------------------------- ### JWT Expiration Error in Blazor Source: https://github.com/supabase-community/supabase-csharp/blob/master/Examples/BlazorWebAssemblySupabaseTemplate/README.MD An example of a critical error message indicating an invalid and expired JWT when attempting to sign out or fetch data from the database in a Blazor WebAssembly application using Supabase. ```csharp blazor.webassembly.js:1 crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] Unhandled exception rendering component: {"code":401,"msg":"invalid JWT: unable to parse or verify signature, token is expired by 22m22s"} Supabase.Gotrue.RequestException: {"code":401,"msg":"invalid JWT: unable to parse or verify signature, token is expired by 22m22s"} at Supabase.Gotrue.Helpers.MakeRequest(HttpMethod method, String url, Object data, Dictionary`2 headers) at Supabase.Gotrue.Client.SignOut() at BlazorWebAssemblySupabaseTemplate.Services.AuthService.Logout() at BlazorWebAssemblySupabaseTemplate.Shared.MainLayout.OnClickLogout() at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task) at MudBlazor.MudChip.OnClickHandler(MouseEventArgs ev) at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task) at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task , ComponentState ) ``` -------------------------------- ### Initialize Supabase Client with Local Instance Options Source: https://github.com/supabase-community/supabase-csharp/wiki/Home This snippet shows how to initialize the Supabase client for a local instance. It also demonstrates signing up a new user. ```csharp var options = new ClientOptions { Url = "https://example.com/api" }; var client = new Client(options); var user = await client.SignUp("new-user@example.com"); ``` -------------------------------- ### Initialize Supabase Stateless Client for Local Instance Source: https://github.com/supabase-community/supabase-csharp/wiki/Home This snippet demonstrates initializing and using a Supabase StatelessClient for local API interactions, including user sign-up. ```csharp var options = new StatelessClientOptions { Url = "https://example.com/api" } await new StatelessClient().SignUp("new-user@example.com", options); ``` -------------------------------- ### Native Sign in with Apple Flow in Unity Source: https://github.com/supabase-community/supabase-csharp/wiki/Authorization-with-Gotrue This C# code demonstrates the complete flow for native Sign in with Apple in Unity. It includes generating nonces, presenting the native dialog, handling callbacks, and signing into Supabase. ```csharp // These are values that we will use to handle the flow. // This is a one-time use code. It's used to verify the JWT from Apple. private string? _nonce; // This is a hash of the one-time use code. private string? _nonceVerify; // This is the identity token from Apple. private string? _identityToken; // This is the authorization code from Apple. private string? _authorizationCode; // This method brings up the native dialog. public void SignInWithApple() { // This generates a random nonce (a one-time code) used to verify the JWT from // Apple. _nonce = Supabase.Gotrue.Helpers.GenerateNonce(); // This is a SHA256 hash of the nonce. _nonceVerify = Supabase.Gotrue.Helpers.GenerateSHA256NonceFromRawNonce(_nonce); // Here we set the options for the native dialog, including the nonce. AppleAuthLoginArgs loginArgs = new(LoginOptions.IncludeEmail | LoginOptions.IncludeFullName, _nonceVerify); // Here we are asking the native dialog wrapper library to present the native // dialog. We are passing in the nonce and a callback to handle the results. _appleAuthManager!.LoginWithAppleId(loginArgs, SuccessCallback, ErrorCallback); } // This method handles the callback from the native dialog and sets the data // to be used later. private void SuccessCallback(ICredential credential) { // Obtained credential, cast it to IAppleIDCredential if (credential is IAppleIDCredential appleIdCredential) { // Apple User ID string? userId = appleIdCredential.User; // Email and first name are received ONLY in the first login // You may want to add logic to save these fields locally // Identity token _identityToken = Encoding.UTF8.GetString(appleIdCredential.IdentityToken, 0, appleIdCredential.IdentityToken.Length); // Authorization code _authorizationCode = Encoding.UTF8.GetString(appleIdCredential.AuthorizationCode, 0, appleIdCredential.AuthorizationCode.Length); // And now you have all the information to create/login a user in your system _doAppleSignIn = true; } else { // Error handling - you don't want to use Sign in with Apple on non Apple devices } } // Now we use an Update() declared async. private async void Update() { // Updates the AppleAuthManager instance to execute // pending callbacks inside Unity's execution loop _appleAuthManager?.Update(); if (_doAppleSignIn) { _doAppleSignIn = false; // ReSharper disable once Unity.PerformanceCriticalCodeInvocation bool status = await SignInToSupabaseWithApple(); if (!status) Debug.Log("Sign in failed", gameObject); _doAppleSignIn = false; } } // This method takes the data from the callback and sends it to Supabase to // validate the JWT and create a Supabase session. Note that because this method // goes over the network, it's declared async. In Unity this means you might want // to call this method from an Update method marked async. private async Task SignInToSupabaseWithApple() { try { Session? session = await SupabaseManager.Client()?.Auth.SignInWithIdToken(Constants.Provider.Apple, _identityToken!, _nonce)!; if (session?.User?.Id != null) { // You logged in successfully! Depending on your application you may want to load another scene, etc. } else { // Something went wrong - you may want to display an error message to the user. } } catch (GotrueException e) { // Something went wrong - you may want to display an error message to the user. GotrueExceptions // generally mean the server sent back an error message. } catch (Exception e) { // Catch-all for anything else that might have gone wrong. } return true; } ``` -------------------------------- ### Initialize Supabase Auth Client with Public Key Source: https://github.com/supabase-community/supabase-csharp/wiki/Home Use this snippet to initialize the Supabase Auth client when using the Supabase Hosted service from an untrusted client. Ensure you replace 'PROJECT_ID' and 'SUPABASE_PUBLIC_KEY' with your actual project details. ```csharp var auth = new Supabase.Gotrue.Client(new ClientOptions { Url = "https://PROJECT_ID.supabase.co/auth/v1", Headers = new Dictionary { { "apikey", SUPABASE_PUBLIC_KEY } } }) ``` -------------------------------- ### Deployment Commands Source: https://github.com/supabase-community/supabase-csharp/blob/master/Examples/BlazorWebAssemblySupabaseTemplate/README.MD Commands for publishing the Blazor WebAssembly application and deploying it with Firebase. ```bash dotnet publish -c Release -o release firebase deploy ``` -------------------------------- ### Initialize Supabase Auth Client with Offline Support Source: https://github.com/supabase-community/supabase-csharp/wiki/Authorization-with-Gotrue This snippet shows how to create a Supabase Auth client with offline capabilities enabled and integrate it with the NetworkStatus monitor. Ensure the client is configured with `AllowUnconfirmedUserSessions` if needed. ```csharp // Create the client var client = new Client(new ClientOptions { AllowUnconfirmedUserSessions = true }); // Create the network status monitor var status = new NetworkStatus(); // Tell the network status monitor to update the client's online status status.Client = client; // Start the network status monitor await status.StartAsync(); // rest of the usual client configuration ``` -------------------------------- ### Initiate PKCE OAuth Flow with GitHub Source: https://github.com/supabase-community/supabase-csharp/wiki/Authorization-with-Gotrue Initiates the OAuth flow for GitHub using the PKCE type. Ensure the RedirectTo URL is configured in your Supabase project settings. ```csharp var state = await client.SignIn(Constants.Provider.Github, new SignInOptions { FlowType = Constants.OAuthFlowType.PKCE, RedirectTo = "http://localhost:3000/oauth/callback" }); ``` -------------------------------- ### Prepare Identity Token for Google Sign-In Source: https://github.com/supabase-community/supabase-csharp/wiki/Authorization-with-Gotrue Prepares the identity token received from a Google Sign-In implementation for use with Supabase. Ensure User Signups are enabled in Supabase project settings. ```csharp var identityToken = Encoding.UTF8.GetString(System.Text.Encoding.UTF8.GetBytes(GoogleIdToken), 0, GoogleIdToken.Length); ``` -------------------------------- ### Accessing Raw Assets Source: https://github.com/supabase-community/supabase-csharp/blob/master/Examples/Xamarin.Forms/SupabaseExampleXA.Android/Assets/AboutAssets.txt Demonstrates how to open a raw asset file using the Assets.Open() method within an Android Activity. Ensure the file is placed in the Assets directory and has a Build Action of 'AndroidAsset'. ```csharp public class ReadAsset : Activity { protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); InputStream input = Assets.Open ("my_asset.txt"); } } ``` -------------------------------- ### Login or Create User with Google Identity Token Source: https://github.com/supabase-community/supabase-csharp/wiki/Authorization-with-Gotrue Logs in an existing user or creates a new one using a Google identity token. This method is used after preparing the identity token. ```csharp var user = await Supabase.Auth.SignInWithIdToken(Supabase.Gotrue.Constants.Provider.Google, identityToken); ``` -------------------------------- ### Initialize Gotrue Client with Session Persistence Source: https://github.com/supabase-community/supabase-csharp/wiki/Authorization-with-Gotrue This C# code demonstrates how to initialize the Gotrue client with custom session persistence callbacks for MAUI/Xamarin applications. It sets up listeners for debug and state changes, and loads the session. ```csharp async void Initialize() { // Specify the methods you'd like to use as persistence callbacks var persistence = new GotrueSessionPersistence(SaveSession, LoadSession, DestroySession); var client = new Client( Url = GOTRUE_URL, new ClientOptions { AllowUnconfirmedUserSessions = true, SessionPersistence = persistence }); // Specify a debug callback to listen to problems with the background token refresh thread client.AddDebugListener(LogDebug); // Specify a call back to listen to changes in the user state (logged in, out, etc) client.AddStateChangedListener(AuthStateListener); // Load the session from persistence client.LoadSession(); // Loads the session using SessionRetriever and sets state internally. await client.RetrieveSessionAsync(); } ``` -------------------------------- ### Loading Custom Fonts from Assets Source: https://github.com/supabase-community/supabase-csharp/blob/master/Examples/Xamarin.Forms/SupabaseExampleXA.Android/Assets/AboutAssets.txt Shows how to load a custom font file from the Android Assets directory using Typeface.CreateFromAsset(). The font file should be located in a subdirectory like 'fonts/'. ```csharp Typeface tf = Typeface.CreateFromAsset (Context.Assets, "fonts/samplefont.ttf"); ``` -------------------------------- ### Download File from Array Buffer Source: https://github.com/supabase-community/supabase-csharp/blob/master/Examples/BlazorWebAssemblySupabaseTemplate/wwwroot/index.html A JavaScript function to download a file from an ArrayBuffer. It creates a Blob, generates a URL, and simulates a click on an anchor element to initiate the download. This function is intended to be called from C# code in Blazor. ```javascript window.downloadFileFromStream = async (fileName, arrayBuffer) => { const blob = new Blob([arrayBuffer]); const url = URL.createObjectURL(blob); const anchorElement = document.createElement('a'); anchorElement.href = url; anchorElement.download = fileName ?? ''; anchorElement.click(); anchorElement.remove(); URL.revokeObjectURL(url); } ``` -------------------------------- ### Proguard Rules for Unity Source: https://github.com/supabase-community/supabase-csharp/wiki/Unity These ProGuard rules are recommended to prevent issues with code stripping and reflection in Unity projects when using JSON-related operations. ```proguard -keepattributes Signature -keepattributes Annotation -keepattributes EnclosingMethod -keepattributes InnerClasses ``` -------------------------------- ### Generated Resource Class in Android Source: https://github.com/supabase-community/supabase-csharp/blob/master/Examples/Xamarin.Forms/SupabaseExampleXA.Android/Resources/AboutResources.txt This C# class is automatically generated by the build system to provide access tokens for various resource types like drawables, layouts, and strings. ```csharp public class Resource { public class drawable { public const int icon = 0x123; } public class layout { public const int main = 0x456; } public class strings { public const int first_string = 0xabc; public const int second_string = 0xbcd; } } ``` -------------------------------- ### Exchange OAuth Code for Session Source: https://github.com/supabase-community/supabase-csharp/wiki/Authorization-with-Gotrue Exchanges the received OAuth code for a Supabase session using the stored PKCE verifier. This is typically called within your application's callback handler. ```csharp var session = await client.ExchangeCodeForSession(state.PKCEVerifier, RETRIEVE_CODE_FROM_GET_PARAMS); ``` -------------------------------- ### Register Service Worker Source: https://github.com/supabase-community/supabase-csharp/blob/master/Examples/BlazorWebAssemblySupabaseTemplate/wwwroot/index.html Registers the service worker for the Blazor WebAssembly application. This is a standard practice for Progressive Web Apps. ```javascript navigator.serviceWorker.register('service-worker.js'); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.