コード例 #1
0
        public async Task <bool> Upload(FileStream stream, Conductor obj, string filenanme)
        {
            conexion = new Conexion();
            var auth = new FirebaseAuthProvider(new FirebaseConfig(conexion.Firekey()));
            var a    = await auth.SignInWithEmailAndPasswordAsync(conexion.AthEmail(), conexion.AthPassword());

            var cancellation = new CancellationTokenSource();
            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("FotosConductores")
                               .Child(filenanme)
                               .PutAsync(stream, cancellation.Token);

            try
            {
                string link = await task;
                obj.rutafoto_conductor = link;
                Task tarea2 = Task.Run(() => SignUp(obj));
            }

            catch (Exception ex)
            {
                Console.WriteLine("Exception was thrown: {0}", ex);
            }
            return(true);
        }
コード例 #2
0
        public async Task <ActionResult> Edit(ShopItem shopItem, HttpPostedFileBase ImageFile)
        {
            if (ImageFile == null)
            {
                List <FirebaseObject <ShopItem> > items = await shopItemService.GetAllShopItems();

                foreach (FirebaseObject <ShopItem> firebaseObject in items)
                {
                    if (firebaseObject.Object.Id == shopItem.Id)
                    {
                        shopItem.ImgSource = firebaseObject.Object.ImgSource;
                    }
                }

                shopItemService.UpdateShopItem(shopItem);
            }
            else
            {
                FirebaseStorage firebaseStorage = new FirebaseStorage("runformoneydb.appspot.com");
                Guid            imageName       = Guid.NewGuid();
                var             stroageImage    = await firebaseStorage.Child("Images").Child(imageName.ToString()).PutAsync(ImageFile.InputStream);

                string c = await firebaseStorage.Child("Images").Child(imageName.ToString()).GetDownloadUrlAsync();

                shopItem.ImgSource = c;
                shopItemService.UpdateShopItem(shopItem);
            }
            await Task.Delay(500);

            return(RedirectToAction("Index"));
        }
コード例 #3
0
    // Start is called before the first frame update
    void Start()
    {
        // When the app starts, check to make sure that we have
        // the required dependencies to use Firebase, and if not,
        // add them if possible.
        FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task => {
            dependencyStatus = task.Result;
            if (dependencyStatus == DependencyStatus.Available)
            {
                InitializeFirebase();
            }
            else
            {
                Debug.LogError(
                    "Could not resolve all Firebase dependencies: " + dependencyStatus);
            }
        });
        //LogEvent("testEvent",Time.time, 0);

        csvPath = Application.persistentDataPath + "/Analytics/" + PlayerPrefs.GetString("PlayerID", "unknown") + "/Loom.csv";
        CreateNewHeader();
        PlayerPrefs.SetInt("LoomSC", PlayerPrefs.GetInt("LoomSC") + 1);

        storage = FirebaseStorage.GetInstance("gs://loomunity-c1269.appspot.com");
    }
コード例 #4
0
        public async Task ShouldBeSetWhenDownloadingAsync(string secretsFilePath, string fileToUpload, string mimeType)
        {
            File.Exists(secretsFilePath).Should().BeTrue("You need to create your own secrets.json (check out the example file for details)");

            var secrets = JsonConvert.DeserializeObject <Secrets>(File.ReadAllText(secretsFilePath));
            var options = secrets.Authentication.CreateAuthProvider().GetStorageAuthOptions(secrets.Authentication);
            var storage = new FirebaseStorage(secrets.BucketName, options);

            long   actualStreamSize;
            string downloadUrl;

            using (var contentStream = new MemoryStream(File.ReadAllBytes(fileToUpload)))
            {
                actualStreamSize = contentStream.Length;
                downloadUrl      = await storage.Child("test.jpg").PutAsync(
                    contentStream,
                    CancellationToken.None,
                    mimeType);
            }

            // now download the file and check the mime-type
            var http = await storage.Options.CreateHttpClientAsync();

            using (var response = await http.GetAsync(downloadUrl))
            {
                response.Content.Headers.ContentType.MediaType.Should().Be(mimeType);
                response.Content.Headers.ContentLength.HasValue.Should().BeTrue();
                // ReSharper disable once PossibleInvalidOperationException
                response.Content.Headers.ContentLength.Value.Should().Be(actualStreamSize);
                (await response.Content.ReadAsByteArrayAsync()).LongLength.Should().Be(actualStreamSize);
            }
        }
コード例 #5
0
 public static void PreWarmDependencies(object key, FirebaseStorage fbStorage, Action completed)
 {
     PreWarmDependencies(new List <object>()
     {
         key
     }, fbStorage, completed);
 }
コード例 #6
0
        public async Task <ServiceResult <LoadedImage, LoadImageError> > LoadImageAsync(string externalId)
        {
            var imagesRepository = _unitOfWork.GetRepository <UploadedImage>();
            var imageDetails     = await imagesRepository.SingleOrDefaultAsync(i => i.ExternalId == externalId);

            if (imageDetails == null)
            {
                return(ServiceResult <LoadedImage, LoadImageError> .CreateFailed(LoadImageError.IncorrectExternalId));
            }

            var imageExtension = Path.GetExtension(imageDetails.FilePath);
            var imageName      = $"{externalId}{imageExtension}";

            var firebaseStorage = new FirebaseStorage(_firebaseImageStorageConfiguration.StorageBucket)
                                  .Child(_firebaseImageStorageConfiguration.ImagesDirectory)
                                  .Child(imageName);

            try
            {
                var fileBytes = await firebaseStorage.GetAsync(imageDetails.FilePath);

                return(ServiceResult <LoadedImage, LoadImageError> .CreateSuccess(new LoadedImage(fileBytes, imageDetails.MediaType)));
            }
            catch (FirebaseStorageException)
            {
                return(ServiceResult <LoadedImage, LoadImageError> .CreateFailed(LoadImageError.ImageNotExists));
            }
        }
コード例 #7
0
        private async void ribPicProfile_Click(object sender, EventArgs e)
        {
            string imageFile      = "";
            var    openFileDialog = new OpenFileDialog();

            try
            {
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    imageFile = openFileDialog.FileName;
                    // Get any Stream - it can be FileStream, MemoryStream or any other type of Stream
                    var stream = File.Open(imageFile, FileMode.Open);

                    // Constructr FirebaseStorage, path to where you want to upload the file and Put it there
                    var task = new FirebaseStorage("mchat-ca3c9.appspot.com")
                               .Child("DemoApp/PictureProfile/" + userEmail)
                               .PutAsync(stream);

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

                    // await the task to wait until upload completes and get the download url
                    var downloadUrl = await task;
                    await client.SetAsync("DemoApp/MessageInfo/ID/" + userEmail + "/picProfile", downloadUrl);

                    ribPicProfile.Load(downloadUrl);
                }
            }
            catch
            {
                MessageBox.Show("Something went wrong.");
            }
        }
コード例 #8
0
        internal FirebaseDBStorageReference(FirebaseStorage storage, string childRoot)
        {
            this.children = new List <string>();

            this.storage = storage;
            this.children.Add(childRoot);
        }
コード例 #9
0
        private async void Init(string storage)
        {
            if (_inited || _initing)
            {
                return;
            }

            _initing = true;
            var status = await FirebaseDependencies.CheckAndFixDependencies();

            switch (status)
            {
            case DependencyStatus.Available:
            {
                _storage = storage.IsNullOrEmpty()? FirebaseStorage.DefaultInstance : FirebaseStorage.GetInstance(storage);
                _initing = false;
                _inited  = true;
                break;
            }

            default:
            {
                _initing = false;
                _inited  = false;
                break;
            }
            }
        }
コード例 #10
0
ファイル: VRMUploader.cs プロジェクト: yuzuka4573/VRPN2
 /// <summary>
 /// Init the ModelUploader
 /// </summary>
 /// <param name="targetURL">storage URL</param>
 /// <param name="targetDBURL">DB URL</param>
 public VRMUploader(string targetURL, string targetDBURL)
 {
     FirebaseApp.DefaultInstance.SetEditorDatabaseUrl(targetDBURL);
     DB_ref      = FirebaseDatabase.DefaultInstance.RootReference;
     Storage     = FirebaseStorage.GetInstance(targetURL);
     Storage_ref = Storage.GetReferenceFromUrl(targetURL);
 }
コード例 #11
0
ファイル: ModelDownloader.cs プロジェクト: raykibul/AR_MIXER
    string  DownloadFile(String url)
    {
        FirebaseStorage  storage     = FirebaseStorage.DefaultInstance;
        StorageReference storage_ref = storage.GetReferenceFromUrl(url);



        // Start downloading a file
        Task task = storage_ref.GetFileAsync(local_url,
                                             new Firebase.Storage.StorageProgress <DownloadState>((DownloadState state) => {
            DownloadingText.text = String.Format(
                "Progress: {0} of {1} bytes transferred.",
                state.BytesTransferred,
                state.TotalByteCount
                );
        }), CancellationToken.None);

        task.ContinueWith(resultTask => {
            if (!resultTask.IsFaulted && !resultTask.IsCanceled)
            {
                Debug.Log("Download finished.");
                DownloadingText.text = "DOWnload Finished";
            }
        });
        return(local_url);
    }
コード例 #12
0
        public async Task PushFirebaseAsync(Config conf)
        {
            Console.WriteLine("Start upload ...");
            // Get any Stream - it can be FileStream, MemoryStream or any other type of Stream
            var stream = File.Open(@"pdfcreated.pdf", FileMode.Open);

            var authProvider =
                new FirebaseAuthProvider(new Firebase.Auth.FirebaseConfig(conf.ApiKey));
            var auth = await authProvider.SignInWithEmailAndPasswordAsync(conf.Email, conf.Pw);

            var authOption = new FirebaseStorageOptions
            {
                AuthTokenAsyncFactory = () => Task.FromResult(auth.FirebaseToken),
                ThrowOnCancel         = true
            };

            // Construct FirebaseStorage, path to where you want to upload the file and Put it there
            var task = new FirebaseStorage(@"htlgkr-testet.appspot.com", authOption)
                       .Child("pdf")
                       .Child("pdfcreated.pdf")
                       .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;

            Console.WriteLine("URL: " + downloadUrl);
        }
コード例 #13
0
    private void SetCloudItinerary()
    {
        if (itinerary.Contains(SystemInfo.deviceUniqueIdentifier) == false)
        {
            //write to file
            string path = Directory.GetCurrentDirectory() + "\\" + folderName + "\\" + "Itinerary.txt";

            ValidateDirectory();
            ValidateFile("Itinerary.txt");

            itinerary.Add(SystemInfo.deviceUniqueIdentifier);

            File.WriteAllText(path, JsonConvert.SerializeObject(itinerary, Formatting.Indented));

            //upload to cloud
            FirebaseStorage  storage     = FirebaseStorage.DefaultInstance;
            StorageReference storage_ref = storage.GetReferenceFromUrl(networkURL);
            StorageReference fileRef     = storage_ref.Child($"TanabataData/Itinerary.txt");

            fileRef.PutFileAsync(path).ContinueWith((Task <StorageMetadata> task) =>
            {
                if (task.IsFaulted || task.IsCanceled)
                {
                    Debug.Log(task.Exception.ToString());
                }
                else
                {
                    Debug.Log("Itinerary finished uploading...");
                }
            });
        }
    }
コード例 #14
0
    private void GetOwnCloudData()
    {
        FirebaseStorage storage = FirebaseStorage.DefaultInstance;

        StorageReference storage_ref = storage.GetReferenceFromUrl(networkURL);

        string path = Directory.GetCurrentDirectory() + "\\" + folderName + "\\" + fileName;

        ValidateDirectory();
        ValidateFile(fileName);

        StorageReference fileRef = storage_ref.Child($"TanabataData/{SystemInfo.deviceUniqueIdentifier}/{fileName}");

        // Download to the local file system
        fileRef.GetFileAsync(path).ContinueWith(task =>
        {
            if (!task.IsFaulted && !task.IsCanceled)
            {
                Debug.Log("User data File downloaded.");
            }
            else
            {
                Debug.Log("No user data found in cloud: " + task.Exception.ToString());
            }

            userDataDownloaded = true;
        });
    }
コード例 #15
0
 public async Task <Android.Net.Uri> GetFile(string fileName, FirebaseStorage storage)
 {
     return(await storage.Reference
            .Child("animalProfilePics")
            .Child(fileName)
            .GetDownloadUrlAsync());
 }
コード例 #16
0
    /*
     * Method for publishing a recipe to firebase,
     * Takes in the recipe object that has all the inputted info from the recipe publishing page and a photo of the food
     * then sends the photo to storage and the recipe to our DB
     */
    public void PublishNewRecipe(Recipe recipe, string local_file)
    {
        FirebaseStorage storage = FirebaseStorage.DefaultInstance;
        string          key     = databaseReference.Child("recipes").Push().Key;

        // File located on disk
        Firebase.Storage.StorageReference storage_ref = storage.GetReferenceFromUrl("gs://regen-66cf8.appspot.com/Recipes/" + key);
        // Create a reference to the file you want to upload
        storage_ref.PutFileAsync("file://" + local_file)
        .ContinueWith((Task <StorageMetadata> task) => {
            if (task.IsFaulted || task.IsCanceled)
            {
                Debug.Log(task.Exception.ToString());
            }
            else
            {
                Debug.Log("Finished uploading...");
            }
        });
        recipe.ImageReferencePath = $"gs://regen-66cf8.appspot.com/Recipes/" + key;

        string json = JsonUtility.ToJson(recipe);

        databaseReference.Child("recipes").Child(key).SetRawJsonValueAsync(json);

        NotificationManager.Instance.ShowNotification("Publish Successful");
    }
コード例 #17
0
 public FetchedJob(FirebaseStorage storage, string queue, string jobId, string reference)
 {
     connection = (FirebaseConnection)storage.GetConnection();
     JobId      = jobId;
     Queue      = queue;
     Reference  = reference;
 }
コード例 #18
0
    // Use this for initialization
    void Start()
    {
        storage     = FirebaseStorage.DefaultInstance;
        storage_ref = storage.GetReferenceFromUrl("gs://nyangress-220707.appspot.com");
        // Set up the Editor before calling into the realtime database.
        FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://nyangress-220707.firebaseio.com/");

        // Get the root reference location of the database.
        reference = FirebaseDatabase.DefaultInstance.RootReference;
        if (Application.platform == RuntimePlatform.Android)
        {
            // Android
            // GetComponent<RectTransform>().Rotate(new Vector3(0, 0, -90));
            width  = (int)gameObject.GetComponent <RectTransform>().sizeDelta.y;
            height = (int)gameObject.GetComponent <RectTransform>().sizeDelta.x;
        }
        else
        {
            width  = (int)gameObject.GetComponent <RectTransform>().sizeDelta.x;
            height = (int)gameObject.GetComponent <RectTransform>().sizeDelta.y;
        }

        WebCamDevice[] devices = WebCamTexture.devices;
        webcamTexture       = new WebCamTexture(devices[0].name, this.width, this.height, this.fps);
        m_displayUI.texture = webcamTexture;

        webcamTexture.Play();

        StartCoroutine(Init());
    }
コード例 #19
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            OverridePendingTransition(Android.Resource.Animation.FadeIn, Android.Resource.Animation.FadeOut);
            SetContentView(Resource.Layout.DatabaseActivity);

            toolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbarMain);
            if (null != toolbar)
            {
                SetSupportActionBar(toolbar);
                SupportActionBar.SetDisplayHomeAsUpEnabled(true);
                toolbar.SetTitleTextColor(Color.White);
            }

            database = FirebaseDatabase.Instance;

            databaseSchemaReference = database.GetReferenceFromUrl(Intent.GetStringExtra("databaseSchema"));
            databaseDataReference   = database.GetReferenceFromUrl(Intent.GetStringExtra("databasePath"));
            sorage = FirebaseStorage.Instance;

            mainLayout = FindViewById <FrameLayout>(Resource.Id.tableFrame);

            model = new DatabaseModel(databaseDataReference, databaseSchemaReference);
            view  = model.GetView(this);

            mainLayout.AddView(view.GetView());
            databaseSchemaReference.AddChildEventListener(schemaListener);
        }
コード例 #20
0
        private StorageReference getByPath(string path)
        {
            FirebaseStorage storage = FirebaseStorage.DefaultInstance;

            Firebase.Storage.StorageReference storage_ref = storage.GetReferenceFromUrl(bucketUrl);
            return(storage_ref.Child(path));
        }
コード例 #21
0
        private void UploadTask(string fileUrl)
        {
            User user = new User();

            // Get any Stream - it can be FileStream, MemoryStream or any other type of Stream
            var stream = File.Open(fileUrl, FileMode.Open);

            fileName = ShortenPathName(stream);

            filenameLabel.Text = fileName + " is being uploaded.\n It might take a while...";

            // Construct FirebaseStorage, path to where you want to upload the file and Put it there
            var task = new FirebaseStorage("jamcloud-db-2aea9.appspot.com")
                       .Child("jamcloud_audio")
                       .Child(user.GetCurrentUser().Username)
                       .Child(fileName)
                       .PutAsync(stream);

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


                if (per.Percentage >= 0 && per.Percentage < 100)
                {
                    progressBar.Value  = per.Percentage;
                    progressLabel.Text = per.Percentage + "%";
                }
                else
                {
                    Close();
                }
            };
        }
コード例 #22
0
        public async void UploadToFirebase(StorageFile file)
        {
            var stream = File.Open(file.Path, FileMode.Open);
            var task   = new FirebaseStorage("ohwall-e865f.appspot.com")
                         .Child("Media")
                         .Child(file.DisplayName)
                         .PutAsync(stream);

            task.Progress.ProgressChanged += (s, e) => progressBar.Value = e.Percentage;
            var downloadUrl = await task;

            MainPage.globalObject.SetDownloadURL(downloadUrl);
            var auth           = "8qkIRcNDoQ5InGjxxhb7ax79c3WfJd0n2jyOgO70";
            var firebaseClient = new FirebaseClient(
                "https://ohwall-e865f.firebaseio.com/",
                new FirebaseOptions
            {
                AuthTokenAsyncFactory = () => Task.FromResult(auth)
            });
            await firebaseClient
            .Child("media")
            .PostAsync(new Image(MainPage.globalObject.GetDownloadURL(), "IOTCameraBooth"));

            if (progressBar.Value == 100)
            {
                this.Frame.Navigate(typeof(UploadCompletePage));
                await Task.Delay(TimeSpan.FromSeconds(0.5));
            }
        }
コード例 #23
0
        public static async Task <string> WriteOnFirebaseStorage(byte[] file, DTOArchivo archivo)
        {
            var stream = new MemoryStream(file);
            var auth   = new FirebaseAuthProvider(new FirebaseConfig(ApiKey));
            var a      = await auth.SignInWithEmailAndPasswordAsync(AuthEmail, AuthPassword);

            var    cancellation = new CancellationTokenSource();
            string url          = "";
            var    task         = new FirebaseStorage(
                Bucket,
                new FirebaseStorageOptions
            {
                AuthTokenAsyncFactory = () => Task.FromResult(a.FirebaseToken),
                ThrowOnCancel         = true
            })
                                  .Child(archivo.IdUsuario)
                                  .Child(archivo.Id)
                                  .Child(archivo.Nombre)
                                  .PutAsync(stream, cancellation.Token);

            task.Progress.ProgressChanged += (s, e) => Progress = e.Percentage;
            try
            {
                url = await task;
            }
            catch (Exception ex)
            {
                IOUtilities.WriteExceptionLog(ex, Configuration.GetClassName <FirebaseController>());
            }
            return(url);
        }
コード例 #24
0
        public async Task Upload(FileStream stream, string fileName, string path)
        {
            var auth = new FirebaseAuthProvider(new FirebaseConfig(CommonConstants.ApiKey));
            var a    = await auth.SignInWithEmailAndPasswordAsync(CommonConstants.AuthEmail, CommonConstants.AuthPassword);

            var cancellation = new CancellationTokenSource();

            var task = new FirebaseStorage(
                CommonConstants.Bucket,
                new FirebaseStorageOptions
            {
                AuthTokenAsyncFactory = () => Task.FromResult(a.FirebaseToken),
                ThrowOnCancel         = true
            }
                )
                       .Child("file")
                       .Child(fileName)
                       .PutAsync(stream, cancellation.Token);

            try
            {
                string link = await task;
                CommonConstants.linkFile = link;
                System.IO.File.Delete(path);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
コード例 #25
0
        private static void GetFirebaseUrl(List <object> keys, FirebaseStorage fbStorage, Action completed)
        {
            if (runningFetchUrlOperationCount > 0)
            {
                Debug.LogError("Wait until the previous operation is completed before starting a new one");
                return;
            }
            runningFetchUrlOperationCount = 0;
            foreach (var key in keys)
            {
                foreach (IResourceLocator locator in UnityEngine.AddressableAssets.Addressables.ResourceLocators)
                {
                    if (locator.Locate(key, typeof(object), out IList <IResourceLocation> locations))
                    {
                        foreach (IResourceLocation location in locations)
                        {
                            foreach (var dependency in location.Dependencies)
                            {
                                string firebaseUrl = UnityEngine.AddressableAssets.Addressables.ResourceManager.TransformInternalId(dependency);
                                if (FirebaseAddressablesManager.IsFirebaseStorageLocation(firebaseUrl) == false)
                                {
                                    continue;
                                }

                                StorageReference reference = fbStorage.GetReferenceFromUrl(firebaseUrl);

                                StartUrlFetch(completed, reference, firebaseUrl);
                            }
                        }
                    }
                }
            }
        }
コード例 #26
0
        public async void Upload(FileStream stream, string filename)
        {
            var auth = new FirebaseAuthProvider(new FirebaseConfig(ApiKey));
            var a    = await auth.SignInWithEmailAndPasswordAsync(AuthEmail, AuthPassword);


            var cancellation = new CancellationTokenSource();
            var task         = new FirebaseStorage(
                Bucket,
                new FirebaseStorageOptions
            {
                AuthTokenAsyncFactory = () => Task.FromResult(a.FirebaseToken),
                ThrowOnCancel         = true
            })
                               .Child("images")
                               .Child(filename)
                               .PutAsync(stream, cancellation.Token);

            try
            {
                string link = await task;
            }
            catch (Exception ex) {
                Console.WriteLine("Exception was know: {0}", ex);
            }
        }
コード例 #27
0
ファイル: FirebaseLib.cs プロジェクト: Seliunen/GrawGO
        public async Task <string> AddImage(string imageFile)
        {
            var stream     = File.Open(imageFile, FileMode.Open);
            var outputName = Path.GetRandomFileName();
            var task       = new FirebaseStorage(Bucket,
                                                 new FirebaseStorageOptions
            {
                AuthTokenAsyncFactory = () => Task.FromResult(Authlink.FirebaseToken),
                ThrowOnCancel         = true     // when you cancel the upload, exception is thrown. By default no exception is thrown
            })
                             .Child("stationImages")
                             .Child(outputName)
                             .PutAsync(stream);

            task.Progress.ProgressChanged += (s, e) => OnSetProgress(this, e.Percentage);
            try
            {
                var url = await task;
                return(url);
            }
            catch (FirebaseStorageException e)
            {
                Console.WriteLine("Exception was thrown: {0}", e.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception was thrown: {0}", ex);
            }

            return(string.Empty);
        }
コード例 #28
0
        public async Task <string> Upload(byte[] fileBytes, string fileName)
        {
            var auth = new FirebaseAuthProvider(new FirebaseConfig(_settings.ApiKey));
            var a    = await auth.SignInWithEmailAndPasswordAsync(_settings.Email, _settings.Password);

            var task = new FirebaseStorage(
                _settings.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("Screenshots")
                       .Child(fileName)
                       .PutAsync(new MemoryStream(fileBytes));

            var percentage = "";

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

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

            return(await task);
        }
コード例 #29
0
        public async Task <Response> Login(Model.User user)
        {
            try
            {
                var authLink = await authProvider.SignInWithEmailAndPasswordAsync(user.EmailID, user.Password);

                firebaseUser = await authProvider.GetUserAsync(authLink.FirebaseToken);

                client = new FirebaseClient(Config.FirebaseWebApp,
                                            new FirebaseOptions
                {
                    AuthTokenAsyncFactory = () => Task.FromResult <string>(authLink.FirebaseToken)
                }
                                            );

                storageClient = new FirebaseStorage(Config.FirebaseStorageApp,
                                                    new FirebaseStorageOptions
                {
                    AuthTokenAsyncFactory = () => Task.FromResult <string>(authLink.FirebaseToken)
                }
                                                    );

                return(new Response {
                    Success = true, Code = (firebaseUser.IsEmailVerified) ? Code.Default : Code.EmailNotVerified
                });
            }
            catch (Exception ex)
            {
                return(new Response {
                    Success = false
                });
            }
        }
コード例 #30
0
ファイル: FileUploader.cs プロジェクト: shimronduan/DevFriend
        public async Task <string> Upload()
        {
            try
            {
                // Get any Stream - it can be FileStream, MemoryStream or any other type of Stream
                var stream = File.Open(@"D:\Purpose.png", FileMode.Open);

                // Constructr FirebaseStorage, path to where you want to upload the file and Put it there
                var task = new FirebaseStorage("dev-friend-ybkjvy")
                           //.Child("data")
                           //.Child("random")
                           .Child("Purpose.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;
                return(downloadUrl);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }