GithubHelp home page GithubHelp logo

step-up-labs / firebase-storage-dotnet Goto Github PK

View Code? Open in Web Editor NEW
138.0 8.0 35.0 264 KB

C# library for Firebase Storage

License: MIT License

C# 100.00%
firebase-storage firebase firebase-database firebase-auth gcloud

firebase-storage-dotnet's Introduction

FirebaseStorage.net

AppVeyor Build status

Easily upload files and other content to Firebase Storage. More info in a blog post

For Authenticating with Firebase checkout the Firebase Authentication library and related blog post

Installation

// Install release version
Install-Package FirebaseStorage.net -pre

Supported frameworks

.NET Standard 1.1 - see https://github.com/dotnet/standard/blob/master/docs/versions.md for compatibility matrix

Usage

// Get any Stream - it can be FileStream, MemoryStream or any other type of Stream
var stream = File.Open(@"C:\Users\you\file.png", FileMode.Open);

//authentication
var auth = new FirebaseAuthProvider(new FirebaseConfig("api_key"));
var a = await auth.SignInWithEmailAndPasswordAsync("email", "password");

// Constructr FirebaseStorage, path to where you want to upload the file and Put it there
var task = new FirebaseStorage(
    "your-bucket.appspot.com"
     new FirebaseStorageOptions
     {
         AuthTokenAsyncFactory = () => Task.FromResult(a.FirebaseToken),
         ThrowOnCancel = true,
     })
    .Child("data")
    .Child("random")
    .Child("file.png")
    .PutAsync(stream);

// Track progress of the upload
task.Progress.ProgressChanged += (s, e) => Console.WriteLine($"Progress: {e.Percentage} %");

// await the task to wait until upload completes and get the download url
var downloadUrl = await task;

firebase-storage-dotnet's People

Contributors

bezysoftware avatar macleysousa avatar tommed 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

firebase-storage-dotnet's Issues

Firebase Storage Issue

Hi,

I am using FirebaseStorage.net for uploading image in my c# project
Below is the piece of code i am using for upload purpose
var task = new FirebaseStorage("path")
.Child("data").Child("random").Child("file.png").PutAsync(xmlStream);

However i am getting below listed error

The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'

I have added reference to required assembly.

Please do the needful.

Storage Firebase, bad request 400 for GetDownloadUrlAsync

I'm trying to get a download URL for a file but I have an exception, i use FirebaseAuthentication.net and FirebaseStorage.net in a VSTO Powerpoint project.

var url = await firebaseStorage.Child("parent").Child("filename").GetDownloadUrlAsync();

GetDownloadUrlAsync() throws an exception
Exception occured while processing the request. Url: https://firebasestorage.googleapis.com/v0/b/Your-bucket.appspot.com/o/parent/filename bad request Response: { "error": { "code": 400, "message": "Invalid HTTP method/URL pair." } }

In a WPF or winform project the function works very well and I can make HTTP calls even with WebClient or RestClient but in a VSTO project always I have the same error Bad request: 400

Problem after uploading pdf.

When I upload a pdf file my app crashes but the file has uploaded properly and I can see it in my firebase console.

This is the code:
public static async Task UploadPDF(Stream file, string PersonID, string fileName)
{
try
{
var storage = await firebaseStorage.Child(PersonID).Child(fileName + ".pdf").PutAsync(file);
return storage;
}catch(Exception e)
{
Message.ShowToast(e.ToString());
return null;
}
}

And this is the error:
FATAL UNHANDLED EXCEPTION: System.NotSupportedException: Specified method is not supported.
at Android.Runtime.InputStreamInvoker.get_Position () [0x00000] in <87aaae1e4e224b88a1398ac27fed7129>:0
at Firebase.Storage.FirebaseStorageTask+d14.MoveNext () [0x00075] in <05490158a17440cdbb77cdfa1390ba02>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.b6_1 (System.Object state) [0x00000] in :0
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context (System.Object state) [0x00007] in :0
at System.Threading.ExecutionContext.RunInternal (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state, System.Boolean preserveSyncCtx) [0x00071] in :0
at System.Threading.ExecutionContext.Run (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state, System.Boolean preserveSyncCtx) [0x00000] in :0
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem () [0x00021] in :0
at System.Threading.ThreadPoolWorkQueue.Dispatch () [0x00074] in :0
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback () [0x00000] in :0

Any help or suggestion is appreciated. Thank you

An unhandled exception of type 'System.ObjectDisposedException' occurred in mscorlib.dll

Hello!

Firstly, thank you for your library.

When I run the sample code putting a Console.ReadKey() on last line of the Main method (just after Run().Wait(); call) I get a exception:

An unhandled exception of type 'System.ObjectDisposedException' occurred in mscorlib.dll
System.ObjectDisposedException
Additional information: cannot access closed file

When the exception is thrown the file already was upload correctly.

Same problem occurs when I try to run the code on a Winforms application.

Could you help me figure out why this happens?

Thank you.

Unable to add this NuGet package

I am new to Xamarin.Forms I have to use Firebase Storeage for my project but while adding this Nuget package. I am stuck with this--
Could not install package 'FirebaseStorage.net 1.0.0-alpha6'. You are trying to install this package into a project that targets '.NETPortable,Version=v4.5,Profile=Profile78', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

Getting this error while adding. Also tried to change Profile to 259,344 doesn't work. Also uninstalled Windows 8.1 suggested by some threads also not helped.

Any help will be appreciated

GetDownloadUrlAsync() just hanging

I am trying to get a download url for a file already in Firebase storage - I am using the code below and have tried with and without authentication but none of the asynchronous functions are returning they just hang forever. I get no error and no timeout.

public static async Task<string> GetURL()
        {
            var authProvider = new FirebaseAuthProvider(new FirebaseConfig(LocalTools.APIKey));

            string email = LocalTools.Email;
            string password = LocalTools.Password;
            var auth = await authProvider.SignInWithEmailAndPasswordAsync(email, password);            

            var task = new FirebaseStorage(LocalTools.Bucket,
                new FirebaseStorageOptions { AuthTokenAsyncFactory = () => Task.FromResult(auth.FirebaseToken) })
                .Child(LocalTools.ProjectFileName)
                .GetDownloadUrlAsync();


            return await task;
        }

Could not install package

Could not install package 'FirebaseStorage.net 1.0.0'. You are trying to install this package into a project that targets '.NETPortable,Version=v4.5,Profile=Profile259', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

How to set mime-type?

The API clearly shows the ability to set MIME TYPE and other meta-data when uploading a file, which is exposed in the other libraries, but the C# version doesn't seem to support this..? Why you no love C#?

Getting Json Parsing Error when resultContent is having metadata

Code
var result = await http.GetAsync(url); resultContent = await result.Content.ReadAsStringAsync().ConfigureAwait(false); var data = JsonConvert.DeserializeObject<Dictionary<string,string>>(resultContent);

Sample Result Content
{ "name": "*****/*******.nessus", "bucket": "****.appspot.com", "generation": "1519292246046168", "metageneration": "1", "contentType": "application/octet-stream", "timeCreated": "2018-02-22T09:37:26.043Z", "updated": "2018-02-22T09:37:26.043Z", "storageClass": "STANDARD", "size": "2756082", "md5Hash": "", "contentEncoding": "identity", "contentDisposition": "inline; filename*=utf-8''*******%20%282%29.nessus", "crc32c": "CY6yWQ==", "etag": "CNjritWcudkCEAE=", "downloadTokens": "", "metadata": { "app": "" } }

Error
Unexpected character encountered while parsing value: {. Path 'metadata', line 17, position 15.

at Newtonsoft.Json.JsonTextReader.ReadStringValue(ReadType readType)
at Newtonsoft.Json.JsonTextReader.ReadAsString()
at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateDictionary(IDictionary dictionary, JsonReader reader, JsonDictionaryContract contract, JsonProperty containerProperty, String id)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
at Firebase.Storage.FirebaseStorageReference.d__6.MoveNext() in D:\Projects\Nehemiah\rq-prototype.backendapi\Nehemiah.Prototype.API\Firebase.Storage\FirebaseStorageReference.cs:line 61

Firebase storage List function

Thank you for the excellent plugin.

Are there plans to implement the list function to FirebaseStorage.net. Or is it already possible to get the content of a folder in Firebase storage?

Kind regards,

Ruud

Importing into Unity

Would you guys think about porting this into a Unity package? I've tried by myself but I'm running into a slew of errors that are just above my knowledge of .NET framework.
I would be your first paying customer if you could get it to work in Unity and put it up on the Unity Asset Store.

How To Delete File ??

                            var task = new FirebaseStorage(
                                       Bucket,
                                       new FirebaseStorageOptions
                                       {
                                           AuthTokenAsyncFactory = () => Task.FromResult(a.FirebaseToken),
                                           ThrowOnCancel = true // when you cancel the upload, exception is thrown. By default no exception is thrown
                                       })
                                       .Child("TypeImages")
                                       .Child($"{type.fileUpload.FileName}")
                                       .DeleteAsync();

these are my code

File getting deleted even with rule auth !=null

rules_version = '2'; service firebase.storage { match /b/{bucket}/o { match /{allPaths=**} { allow write: if request.auth == null; allow read: if request.auth != null; allow delete: if request.auth != null; } } }

My c# code

var task = new FirebaseStorage("myapp.appspot.com")
.Child("9500811661D15-1-2021T23:28:43.pdf").DeleteAsync();
task.Wait();

When I try to use GetDownloadUrlAsync() I get error as expected. I also expect the same for DeleteAsync(); But the storage file gets deleted. Why?

Response Data of N/A

Hello,

I have recently ran into an error using this package.
it is no longer allowing me to upload files to firebase and returns a response data of "N/A".

please could you advise me,

kind regards,

Isaac

the error which is logged:
{"The text associated with this error code could not be found.\r\n\r\nA connection with the server could not be established\r\n"}

task progress still contuinue even task completed

task.Progress.ProgressChanged += (s, e) => Console.WriteLine($"Progress: {e.Percentage} %");

            // cancel the upload
            // cancellation.Cancel();

            try
            {
                // error during upload will be thrown when you await the task
                Console.WriteLine("Download link:\n" + await task);
            }

I try to show a progress view in progress changed method. task progress shows progress view even task is done. task.progress still gives value even await task is completed. how to prevent this ?.

Large video does not upload

I am having problems uploading videos over 50 mb, they are not stored in firebase storage, firebasestorage returns the link empty and no error occurs and the process is 0%

send a file but creates a folder

When I run the code below, you are creating a folder instead of sending the file.

var task = await new FirebaseStorage("matlu-344e5.appspot.com")
.Child(filename)
.PutAsync(file);

        targeturl = task;

FirebaseStorage using Visual Basic 2017

Hi, Can you please share a sample code how to upload file to Firebase storage using Visual Basic 2017? I have installed FirebaseAuthentication.net and FirebaseStorage.net using NuGet command line. Thanks in Advance!
Tareq

Multiple Images Upload

I am Facing a Problem In Multiple Images Upload . I'm Using a plugin called XAM.PLUGIN.MEDIA to Get a Image File from my Phone Local Storage & Then Upload to Firebase Storage, But the Image Name Remains the Same . The First Image Automatically Deleted and New Image Uploads With the Same Name .

using Firebase.Storage;
using Plugin.Media;
using Plugin.Media.Abstractions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace App13
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(true)]
public partial class MainPage : ContentPage
{
MediaFile file;
public MainPage()
{
InitializeComponent();

        imgBanner.Source = ImageSource.FromResource("XamarinFirebase.images.banner.png");
        imgChoosed.Source = ImageSource.FromResource("XamarinFirebase.images.default.jpg");
    }

    private async void BtnPick_Clicked(object sender, EventArgs e)
    {
        await CrossMedia.Current.Initialize();
        try
        {
            file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
            {
                PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium
            });
            if (file == null)
                return;
            imgChoosed.Source = ImageSource.FromStream(() =>
            {
                var imageStram = file.GetStream();
                return imageStram;
            });
            await StoreImages(file.GetStream());
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }
    }

    private async void BtnStore_Clicked(object sender, EventArgs e)
    {
        await StoreImages(file.GetStream());
        await DisplayAlert("Hurrah!", "Your image has been successfuly Uploaded.", "OK");

    }

    public async Task<string> StoreImages(Stream imageStream)
    {
        var stroageImage = await new FirebaseStorage("")
            .Child("XamarinMonkeys")
            .Child("image.jpg")
            .PutAsync(imageStream);
        string imgurl = stroageImage;
        return imgurl;
    }
}

}

Upload to a particular folder

Using Child("foldername") is not working
Specifying folder name in the storage bucket string also didn't work.
How to upload a file stream into a particular folder with any random name ?

how can set meta data when uploading an image

i want to set meta data when uploading an image like cache-control
this is an example from firebase documentation , i want using this in .net thanks for helping

import { getStorage, ref, uploadBytes } from "firebase/storage";

const storage = getStorage();
const storageRef = ref(storage, 'images/mountains.jpg');

// Create file metadata including the content type
/** @type {any} */
const metadata = {
  cacheControl: 'public,max-age=300',
};

// Upload the file and metadata
const uploadTask = uploadBytes(storageRef, file, metadata);

.net core support

It looks like the library does not support .net core. Any plans for that?

Access storage with GCP storage account

Is it possible to access storage with a Google Cloud Platform service account,
[email protected]?

When you create the AuthenticationheaderValue("firebase", authstring)

What does firebase expect for the authString? A JWT? Can I get an auth token from your FirebaseClient?

Can't upload audio and video files

        // Get any Stream — it can be FileStream, MemoryStream or any other type of Stream
        var stream = new MemoryStream(File.ReadAllBytes(textAudio.Text));


        // Construct FirebaseStorage with path to where you want to upload the file and put it there
        var task = new FirebaseStorage("my-bucket.appspot.com")
         .Child("audio")
         .Child(Path.GetFileName(textAudio.Text))
         .PutAsync(stream);

        // Track progress of the upload
        task.Progress.ProgressChanged += (s, ex) => Console.WriteLine($"Progress: {ex.Percentage} %");

        // Await the task to wait until upload is completed and get the download url
        var downloadUrl = await task;

        MessageBox.Show("Download at: " + downloadUrl);

downloadUrl is empty. And when i check the firebase console nothing is uploaded. But the task shows progress until 100%.

GetDownloadUrlAsync fails with 400

Depending on your configuration HttpClient.GetAsync(url) in PerformFetch may unescape or not the escaped path by GetEscapedPath, leading to a 400 response from Firebase.

The following will fix the issue:

 private async Task<T> PerformFetch<T>()
        {
            var url = this.GetDownloadUrl();
            var resultContent = "N/A";

            try
            {
                var uri = new Uri(url);
                ForceCanonicalPathAndQuery(uri);

                using (var http = await this.storage.Options.CreateHttpClientAsync().ConfigureAwait(false))
                {
                    var result = await http.GetAsync(uri);
                    resultContent = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
                    var data = JsonConvert.DeserializeObject<T>(resultContent);

                    result.EnsureSuccessStatusCode();

                    return data;
                }

            }
            catch (Exception ex)
            {
                throw new FirebaseStorageException(url, resultContent, ex);
            }
        }

        void ForceCanonicalPathAndQuery(Uri uri)
        {
            string paq = uri.PathAndQuery; // need to access PathAndQuery
            FieldInfo flagsFieldInfo = typeof(Uri).GetField("m_Flags", BindingFlags.Instance | BindingFlags.NonPublic);
            ulong flags = (ulong)flagsFieldInfo.GetValue(uri);
            flags &= ~((ulong)0x30); // Flags.PathNotCanonical|Flags.QueryNotCanonical
            flagsFieldInfo.SetValue(uri, flags);
        }

token is invalid

IMG-20220106-WA0084
hi sir i try to upload image from ASP.Net MVC to Firebase but show this token error mention in the attach screenshot please help
my email:[email protected]
WhatsApp No:+923119209490

bad request 400 for Firebase Storage

Hi,
i'm getting bad request 400 error when i am verifying and uploading the file to get the download url .
i use FirebaseAuthentication.net , FirebaseStorage.net
I use the sample code like this

it get error until downloadurl and can't get the file in firebase storage

wirte rule:

rules_version = '2';
service firebase.storage
{
match /b/{bucket}/o
{
match /{allPaths=**} {
allow read, write:if request.auth!=null;
}
}

this is the code

var authProvider = new FirebaseAuthProvider(new FirebaseConfig("APIKEY"));
FirebaseAuth auth = await authProvider.SignInWithEmailAndPasswordAsync(account.Email, account.PW);
var stream = File.Open(@"C:\sample.jpg", FileMode.Open);
var cancellation = new CancellationTokenSource();
string Bucket = "gs://xxxxxxx.appspot.com/";

            var hello= new FirebaseStorage(
            Bucket,
            new FirebaseStorageOptions
            {
                AuthTokenAsyncFactory = () => Task.FromResult(auth.FirebaseToken),
                ThrowOnCancel = true 
            }).Child("test").Child("test2").Child("sample.jpg").PutAsync(stream, cancellation.Token);

            var downloadurl = await hello;

400 Bad request using Webclient and download URL

Hi !
Thanks a lot for the library this is very usefull =)
I have an issue using the download URL with WebClient. I don't know what I miss but each time I try with any headers or configuration I get a Bad Request as a response.
using (WebClient client = new WebClient()) { client.Headers[HttpRequestHeader.ContentType] = "application/json"; client.DownloadFile(downloadURL, destinationPath); }
Do you guys had the same kind of trouble ?
Thanks anyway

Multiple Users editing file Concurrently on Firebase Storage

Hi, thank you so much for this Nuget, ive been using it and its very helpful!

I do have a question.

I have a situation where multiple users are editing a file on firebase storage concurrently. How is this treating with this Nuget? I am currently editing the file and then just uploading it to firebase using the following:

public async void Upload(Stream fileStream, string folder, string filename) { await firebaseStorage .Child(folder) .Child(filename) .PutAsync(fileStream); }

Thanks.

how can i generate apikey

hi.
how can i generate apikey for

var auth = new FirebaseAuthProvider(new FirebaseConfig("api_key"));

Fails to upload files from the local folder

I am having trouble uploading files(.mp3) stored in the local folder by user to firebase. This is how a file is retrieved from local folder:

StorageFolder folder = ApplicationData.Current.LocalFolder;

var songfolder = await folder.GetFolderAsync("Songs");

StorageFile mp3file = await songfolder.GetFileAsync(mp3fileforupload); 

And this is how I create a stream file of the file and upload:

var stream = File.Open(mp3file.Path, FileMode.Open);

var task = new FirebaseStorage("-my-bucket-.appspot.com")
                       .Child("songs")
                       .Child(new_song_id)
                       .PutAsync(stream);

task.Progress.ProgressChanged += (s, f) => uploadProgress(f.Percentage);

var downloadurl = await task;
Debug.WriteLine("DOWNLOAD_URL " + downloadurl);

The file fails to upload. I understand that files should be uploaded as a stream of a file. This worked when uploading files from the Assets folder, but does not work with files from local folder. I have tried uploading from the MostRecentlyUsedList but it still fails to upload. Any idea why this is failing?

Enhancement

This is not an issue but rather an enhancement suggestion. First of thank you Step-up-labs for the API it's really helpful to a lot of C# developers.
I would like to suggest a log in or sign up enhancement using the Firebase SMS authentication. This will be really helpful as it's not currently supported unless you go native especially for Xamarin Forms developers.
Thank you.

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.