public string GetReference(string pathAppend)
    {
        // Points to itemPath
        StorageReference space_ref = storageFolderReference.Child(pathAppend);

        return(space_ref.ToString());
    }
Ejemplo n.º 2
0
    /*
     * public void OnTokenReceived(object Sender, Firebase.Messaging.TokenReceivedEventArgs EventArgs)
     * {
     *  Debug.Log("Firebase Messaging - Token de Registro Recebido: " + EventArgs.Token);
     * }
     *
     * public void OnMessageReceived(object Sender, Firebase.Messaging.MessageReceivedEventArgs EventArgs)
     * {
     *  Debug.Log("Firebase Messaging - Recebida uma nova mensagem de: " + EventArgs.Message.From);
     * }
     */

    public static void UploadByte(byte[] File, string Path, string Type, string Database)
    {
        StorageReference FileReference = StorageReference.Child(Path);

        var Metadata = new MetadataChange();

        Metadata.ContentType = "image/" + Type.Replace(".", "");

        FileReference.PutBytesAsync(File, Metadata).ContinueWith(Task =>
        {
            if (Task.IsFaulted || Task.IsCanceled)
            {
                Debug.Log(Task.Exception.ToString());
                TecWolf.System.SystemInterface.Alert("Arquivo não enviada com sucesso, tente novamente.");
            }
            else
            {
                TecWolf.System.SystemInterface.Alert("Arquivo enviado com sucesso.");

                FileReference.GetDownloadUrlAsync().ContinueWith(TaskDownload =>
                {
                    if (TaskDownload.IsCompleted)
                    {
                        Debug.Log("Download URL: " + TaskDownload.Result);
                        DownloadUrl = TaskDownload.Result.ToString();

                        FirebaseController.WriteDataString(Database, "link", FirebaseController.DownloadUrl);
                    }
                });
            }
        });
    }
Ejemplo n.º 3
0
        private void UploadVideo()
        {
            progressDialog = new ProgressDialog(this);
            progressDialog.SetTitle("Uploading Video........");
            progressDialog.Window.SetType(Android.Views.WindowManagerTypes.SystemAlert);
            progressDialog.Show();

            var video = Storageref.Child("Video/" + Vidname);

            video.PutFile(filePath).AddOnProgressListener(this).AddOnFailureListener(this).AddOnSuccessListener(this);
        }
Ejemplo n.º 4
0
    public void UploadFile()
    {
        // Get a reference to the storage service, using the default Firebase App
        FirebaseStorage storage = FirebaseStorage.DefaultInstance;
        // FirebaseStorage storage = FirebaseStorage.GetInstance("gs://basicfileupload.appspot.com") ;



        // Create a storage reference from our storage service
        StorageReference storage_ref =
            storage.GetReferenceFromUrl("gs://basicfileupload.appspot.com");

        // Create a child reference
        // images_ref now points to "images"
        StorageReference testFileRef = storage_ref.Child($"Testing/{fileName.text}");
        string           download_url;

        // Upload the file to the path "images/rivers.jpg"
        testFileRef.PutFileAsync(fileName.text)

        .ContinueWith((Task <StorageMetadata> task) => {
            if (task.IsFaulted || task.IsCanceled)
            {
                Debug.Log(task.Exception.ToString());
            }
            else
            {
                Task <Uri> dloadTask = testFileRef.GetDownloadUrlAsync();
                download_url         = dloadTask.Result.ToString();
                Debug.Log("Finished uploading...");
                Debug.Log("download url = " + download_url);
            }
        });
    }
Ejemplo n.º 5
0
    // Update is called once per frame
    public void Poster(Vector2d location, byte[] pic)
    {
        //init datapackage
        DataPackage package = new DataPackage();

        //write some datas
        package.latitude  = location.x;
        package.longitude = location.y;
        package.timeStamp = DateTime.Now.ToString("yyyyMMddhhmmss");

        //upload picture and get urls
        Firebase.Storage.StorageReference pngRef = storage_ref.Child("images").Child(package.timeStamp + ".png");

        // Upload the file to the path "images/rivers.jpg"
        pngRef.PutBytesAsync(pic)
        .ContinueWith((Task <StorageMetadata> task) => {
            if (task.IsFaulted || task.IsCanceled)
            {
                Debug.Log(task.Exception.ToString());
                // Uh-oh, an error occurred!
            }
            else
            {
                // Metadata contains file metadata such as size, content-type, and download URL.
                StorageMetadata metadata = task.Result;
                pngRef.GetDownloadUrlAsync().ContinueWith((Task <Uri> task2) => {
                    if (!task2.IsFaulted && !task2.IsCanceled)
                    {
                        Debug.Log("Download URL: " + task2.Result);
                        // ... now download the file via WWW or UnityWebRequest.
                    }
                });
            }
        });
    }
Ejemplo n.º 6
0
    public void DownloadPhotoToDevice()
    {
        DateTime startTime = DateTime.Now;
        var      filePath  = Path.Combine(Application.persistentDataPath, newFilename);

        Debug.Log("downloading from " + filePath);
        Debug.Log("getting file " + newFilename);
        // Start downloading a file
        Task task = storage_ref.Child(newFilename).GetFileAsync(filePath,
                                                                new Firebase.Storage.StorageProgress <DownloadState>((DownloadState state) => {
            // called periodically during the download
            //Debug.Log(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.");
                DateTime endTime = DateTime.Now;
                TimeSpan ts      = endTime - startTime;
                print("Download duration (ms): " + ts.Milliseconds);
            }
        });
    }
Ejemplo n.º 7
0
    public void UploadProfilePic()
    {
        FirebaseStorage  storage     = FirebaseStorage.DefaultInstance;
        StorageReference storage_ref = GetStorageReference();
        var profilePicReference      = storage_ref.Child("images/" + auth.CurrentUser.Email);

        Byte[] profile = FacebookManager.Instance.ProfileTexture.EncodeToPNG();

        profilePicReference.PutBytesAsync(profile)
        .ContinueWith((Task <StorageMetadata> task) => {
            if (task.IsFaulted || task.IsCanceled)
            {
                Debug.Log(task.Exception.ToString());
                // Uh-oh, an error occurred!
            }
            else
            {
                // Metadata contains file metadata such as size, content-type, and download URL.
                Firebase.Storage.StorageMetadata metadata = task.Result;
                string download_url = storage_ref.GetDownloadUrlAsync().ToString();
                Debug.Log("Finished uploading...");
                Debug.Log("download url = " + download_url);
            }
        });
    }
Ejemplo n.º 8
0
    /* The function call to be allowed only if network is available
     * Get yipli pc app url from backend */
    public static async Task <string> UploadLogsFileToDB(string userID, List <string> fileNames, List <string> filePaths)
    {
        StorageReference storageRef = yipliStorage.RootReference;

        string storageChildRef = "customer-tickets/" + userID + "/" + DateTime.Now.Day + DateTime.Now.Month + DateTime.Now.Year + "/" + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + "/";

        for (int i = 0; i < fileNames.Count; i++)
        {
            StorageReference fmResponseLogRef = storageRef.Child(storageChildRef + fileNames[i]);

            await fmResponseLogRef.PutFileAsync(filePaths[i]).ContinueWith((Task <StorageMetadata> task) => {
                if (task.IsFaulted || task.IsCanceled)
                {
                    Debug.Log(task.Exception.ToString());
                    // Uh-oh, an error occurred!
                }
                else
                {
                    // Metadata contains file metadata such as size, content-type, and download URL.
                    StorageMetadata metadata = task.Result;
                    string md5Hash           = metadata.Md5Hash;
                    Debug.Log("Finished uploading...");
                    Debug.Log("md5 hash = " + md5Hash);
                }
            });
        }

        return(storageChildRef);
    }
Ejemplo n.º 9
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;
        });
    }
Ejemplo n.º 10
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...");
                }
            });
        }
    }
Ejemplo n.º 11
0
    public void UploadFile(string childpathString, byte[] _data)
    {
        FirebaseStorage storage = FirebaseStorage.DefaultInstance;

        StorageReference storageRef = storage.RootReference;

        // Create a reference to the file you want to upload
        StorageReference childRef = storageRef.Child(childpathString);// ("profileImages/"+auth.CurrentUser.UserId+".jpg");

        // Upload the file to the path "images/rivers.jpg"
        childRef.PutBytesAsync(_data)
        .ContinueWith((Task <StorageMetadata> task) => {
            if (task.IsFaulted || task.IsCanceled)
            {
                Debug.Log(task.Exception.ToString());
                // Uh-oh, an error occurred!
            }
            else
            {
                // Metadata contains file metadata such as size, content-type, and download URL.
                StorageMetadata metadata = task.Result;
                string md5Hash           = metadata.Md5Hash;
                Debug.Log("Finished uploading...");
                Debug.Log("md5 hash = " + md5Hash);
                //Debug.Log("md5 hash = " + "gs://konnekt4march.appspot.com"+profileImagesRef.Path);
                _uploadcomplete?.Invoke(childRef.Path);
            }
        });
    }
Ejemplo n.º 12
0
        /// <summary>
        /// upload the Live2D model to server
        /// </summary>
        /// <param name="filepath">Current live2D model.json file</param>
        public async Task UploadLive2D(string filepath)
        {
            var fileType = new MetadataChange();
            //setup compressor
            ModelCompressor comp = new ModelCompressor();
            string          data = null;
            await Task.Run(() =>
            {
                data = comp.CompressAsync(filepath).Result;
            });

            StorageReference moc3Path = Storage_ref.Child("VRP/" + CurrentUser.UserId + "/Live2D/" + Path.GetFileNameWithoutExtension(filepath) + "_model.json");

            isUploading          = true;
            fileType.ContentType = "application/json";

            await moc3Path.PutBytesAsync(System.Text.Encoding.UTF8.GetBytes(data), fileType).ContinueWith((Task <StorageMetadata> task) =>
            {
                Debug.Log("start uploading");
                if (task.IsFaulted || task.IsCanceled)
                {
                    Debug.Log(task.Exception.ToString());
                    // Uh-oh, an error occurred!
                    isUploading = false;
                }
                else
                {
                    metadata = task.Result;
                    Debug.Log("Finished uploading...");
                }
                isUploading = false;
            });
        }
Ejemplo n.º 13
0
    public void SubmitData()
    {
        DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference;

        reference.Child(emailText).Child(LCGoogleLoginBridge.GSIEmail())
        .SetRawJsonValueAsync(JsonConvert.SerializeObject(_AppRequest));
        reference.Child(messageText.text).Child(_AppRequest.message)
        .SetRawJsonValueAsync(JsonConvert.SerializeObject(_AppRequest));
        reference.Child(locationText.text).Child(_AppRequest.location)
        .SetRawJsonValueAsync(JsonConvert.SerializeObject(_AppRequest));


        StorageReference storage = FirebaseStorage.DefaultInstance.RootReference;

        Firebase.Storage.StorageReference img_ref = storage.Child("UserImages/user.jpg");

        ImageGet.instance.imgTex.GetRawTextureData();

        img_ref.PutBytesAsync(ImageGet.instance.imgTex.GetRawTextureData())
        .ContinueWith((System.Threading.Tasks.Task <StorageMetadata> task) => {
            if (task.IsFaulted || task.IsCanceled)
            {
                Debug.Log(task.Exception.ToString());
            }
            else
            {
                Firebase.Storage.StorageMetadata metadata = task.Result;
                string download_url = metadata.DownloadUrl.ToString();
                Debug.Log("Finished uploading...");
                Debug.Log("download url = " + download_url);
            }
        });
    }
Ejemplo n.º 14
0
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Create your application here
        SetContentView(Resource.Layout.layout2);

        FirebaseAuth mAuth = FirebaseAuth.Instance;
        FirebaseUser user  = mAuth.CurrentUser;

        if (user == null)
        {
            var result = mAuth.SignInAnonymously();
        }

        FirebaseDatabase database = FirebaseDatabase.Instance;

        dbRef = database.GetReference("mygallery");

        FirebaseStorage storage = FirebaseStorage.Instance;
        //create child reference
        StorageReference storageRef = storage.Reference;

        imagesRef = storageRef.Child("images");

        Button btn = FindViewById <Button>(Resource.Id.createdb);

        btn.Click += Btn_Click;
    }
Ejemplo n.º 15
0
        private void OnUploadClicked(object sender, EventArgs e)
        {
            if (filePath != null)
            {
                progressDialog = new ProgressDialog(Activity);
                progressDialog.SetTitle("Uploading...");
                // progressDialog.Window.SetType(Android.Views.WindowManagerTypes.SystemAlert);
                progressDialog.Show();
                string testName = etTestName.Text;
                var    images   = reference.Child(User).Child(testName);

                images.PutFile(filePath)
                .AddOnProgressListener(this)
                .AddOnSuccessListener(this)
                .AddOnFailureListener(this);
            }
        }
Ejemplo n.º 16
0
        private void DonloadImage()
        {
            TASK           = DOWNLOAD;
            progressDialog = new ProgressDialog(this);
            progressDialog.SetTitle("Downloading");
            progressDialog.Window.SetType(Android.Views.WindowManagerTypes.SystemAlert);
            progressDialog.Show();

            var images = storageRef.Child("images/" + guid);

            Java.IO.File file = new Java.IO.File(GetExternalFilesDir(null), guid + ".jpg");

            images.GetFile(file)
            .AddOnProgressListener(this)
            .AddOnSuccessListener(this)
            .AddOnFailureListener(this);
        }
Ejemplo n.º 17
0
    public void takeAPic(Button button)
    {
        //disable button function
        button.interactable = false;
        try
        {
            webcamTexture.GetPixels32(colors);
            texture.SetPixels32(colors);
            texture.Apply();
            png = texture.EncodeToPNG();

            //init datapackage
            DataPackage package = new DataPackage();

            //write some datas
            package.latitude  = users.LocationProvider.CurrentLocation.LatitudeLongitude.x;
            package.longitude = users.LocationProvider.CurrentLocation.LatitudeLongitude.y;
            package.timeStamp = DateTime.Now.ToString("yyyyMMddhhmmss");

            //upload picture and get urls
            Firebase.Storage.StorageReference pngRef = storage_ref.Child("images").Child(package.timeStamp + ".png");

            // Upload the file to the path "images/rivers.jpg"
            pngRef.PutBytesAsync(png).ContinueWith((Task <StorageMetadata> task) =>
            {
                if (task.IsFaulted || task.IsCanceled)
                {
                    Debug.Log(task.Exception.ToString());
                    // Uh-oh, an error occurred!
                }
                else
                {
                    // Metadata contains file metadata such as size, content-type, and download URL.
                    StorageMetadata metadata = task.Result;
                    pngRef.GetDownloadUrlAsync().ContinueWith((Task <Uri> task2) =>
                    {
                        if (!task2.IsFaulted && !task2.IsCanceled)
                        {
                            Debug.Log("Download URL: " + task2.Result);
                            package.picURL = task2.Result.ToString();
                            string json    = JsonUtility.ToJson(package);
                            //make location of containing data
                            string key = reference.Child("Cat").Push().Key;
                            reference.Child("Cat").Child(key).SetRawJsonValueAsync(json);
                        }
                    });
                }
            });
        }
        catch (Exception e)
        {
            throw;
        }
        finally {
            //eable button function
            button.interactable = true;
        }
    }
Ejemplo n.º 18
0
        /// <summary>
        /// Get Url to external(firebase storage) file
        /// </summary>
        /// <param name="filename">name file</param>
        /// <returns>Url to external file</returns>
        public async Task <string> GetFileUrl(string filename)
        {
            try
            {
                var storage = FirebaseStorage.Instance;

                var spaceRef = storageRef.Child($"userimages/{filename}");

                var url = await spaceRef.DownloadUrl;

                filename = url.ToString();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("---> Error UploadFiles " + ex.Message);
            }

            return(filename);
        }
Ejemplo n.º 19
0
    void Start()
    {
        FirebaseStorage  storage     = FirebaseStorage.DefaultInstance;
        StorageReference storage_ref = storage.GetReferenceFromUrl(baseUrl);

        user_ref = storage_ref.Child(userName);
        Debug.Log(user_ref.ToString());
        fileName = Application.persistentDataPath + "/ImagesUrls.txt";
        File.WriteAllText(fileName, "The quick brown fox jumps over the lazy dogs");
    }
    public void GetAudioAndPosition(string key, string imageName)
    {
        FirebaseDatabase.DefaultInstance
        .GetReference(imageName)
        .GetValueAsync().ContinueWith(task => {
            if (task.IsFaulted)
            {
                error = "Error!";
            }
            else if (task.IsCompleted)
            {
                DataSnapshot snapshot = task.Result;
                DataSnapshot c        = snapshot.Child(key);
                double value0         = (double)c.Child("0").Value;
                double value1         = (double)c.Child("1").Value;
                double value2         = (double)c.Child("2").Value;
                position         = new float[] { (float)value0, (float)value1, (float)value2 };
                updatingPosition = true;
            }
        });

        byte[]     fileContents   = { };
        const long maxAllowedSize = 34008512;

        audio_ref = storage_ref.Child(key);
        audio_ref.GetBytesAsync(maxAllowedSize).ContinueWith((Task <byte[]> task) => {
            if (task.IsFaulted || task.IsCanceled)
            {
                Debug.Log("Downloading Failed");
                Debug.Log(task.Exception.ToString());
                // Uh-oh, an error occurred!
            }
            else
            {
                fileContents = task.Result;
                audioData    = new float[fileContents.Length / 4];
                System.Buffer.BlockCopy(fileContents, 0, audioData, 0, fileContents.Length);
                updatingAudio = true;
            }
        });
    }
Ejemplo n.º 21
0
    public static void UserUploadToFirebase(LevelManager.Level level)
    {
        DatabaseReference data = FirebaseDatabase.DefaultInstance.GetReferenceFromUrl("https://blockquest-a1e16.firebaseio.com/");

        StorageReference levelFolder = root.Child(saveLoc);
        StorageReference userName    = levelFolder.Child(FormattedUserName);
        StorageReference userLevel   = userName.Child(level.LevelName);
        StorageReference levelFile   = userLevel.Child(level.LevelName + ".xml");
        StorageReference levelPic    = userLevel.Child(level.LevelName + ".png");

        levelFile.PutFileAsync(level.LevelPath);
        levelPic.PutBytesAsync(level.LevelPic.EncodeToPNG());

        Level newLevel = new Level(level.LevelName, levelFile.Path, levelPic.Path);

        Debug.Log(levelFile.Path);
        Debug.Log(levelPic.Path);

        data.Child(saveLoc).Child(FirebaseManager.FormattedUserName).Child(level.LevelName).Child("File_Path").SetValueAsync(newLevel.filePath);
        data.Child(saveLoc).Child(FirebaseManager.FormattedUserName).Child(level.LevelName).Child("Picture_Path").SetValueAsync(newLevel.picturePath);
    }
Ejemplo n.º 22
0
    public static void UploadFileToFirebase(LevelManager.Level level)
    {
        DatabaseReference data = FirebaseDatabase.DefaultInstance.GetReferenceFromUrl("https://blockquest-a1e16.firebaseio.com/");

        StorageReference levelFolder = root.Child(saveLoc);
        StorageReference userLevel   = levelFolder.Child(level.LevelName);
        StorageReference levelFile   = userLevel.Child(level.LevelName + ".xml");
        StorageReference levelPic    = userLevel.Child(level.LevelName + ".png");

        levelFile.PutFileAsync(level.LevelPath);
        levelPic.PutBytesAsync(level.LevelPic.EncodeToPNG());

        Level newLevel = new Level(level.LevelName, levelFile.Path, levelPic.Path);

        data.Child(saveLoc).Child(level.LevelName).Child("File_Path").SetValueAsync(newLevel.filePath);
        data.Child(saveLoc).Child(level.LevelName).Child("Picture_Path").SetValueAsync(newLevel.picturePath);
        if (saveLoc == "Default_Levels")
        {
            data.Child("Base_Level_Last_Changed").SetValueAsync(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
        }
    }
Ejemplo n.º 23
0
    private void StoreCSVToFirebase(string path)
    {
        // Create a root reference
        StorageReference storage_ref = storage.RootReference;

        // Create a reference to the file you want to upload
        string           childString = path.Substring(path.IndexOf("/Analytics/"));
        StorageReference csv_ref     = storage_ref.Child(childString);

        // Upload the file to the path
        csv_ref.PutFileAsync(path);
    }
Ejemplo n.º 24
0
    public void UploadImagesToFirebase(List <string> Paths)
    {
        FilePath = Paths;
        //Creating a different session everytime the user wants create a scene
        Debug.Log("Module Started");
        string sessionReference = CreateUserSession();

        Firebase.Storage.StorageReference session_ref = user_ref.Child(sessionReference);
        MetadataChange type = new MetadataChange {
            ContentType = "image/jpeg"
        };
        int Counter = 0;

        foreach (string ImagePath in Paths)
        {
            string imageName = "Image_" + Counter.ToString() + ".JPG";
            Counter++;
            StorageReference folder_ref = session_ref.Child(imageName);
            folder_ref.PutFileAsync(ImagePath, type)
            .ContinueWith((Task <StorageMetadata> task) =>
            {
                if (task.IsFaulted || task.IsCanceled)
                {
                    Debug.Log(task.Exception.ToString());
                }
                else
                {
                    StorageMetadata metadata = task.Result;
                    string download_url      = metadata.DownloadUrl.ToString() + "\n";
                    UTF8Encoding uniEncoding = new UTF8Encoding(true);
                    File.WriteAllText(fileName, download_url);
                    images.Add(download_url);
                    Debug.Log(download_url);
                    uploadCount++;
                    CheckIfComplete();
                }
            }
                          );
        }
    }
Ejemplo n.º 25
0
        private async void UploadImage()
        {
            var docs = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

            UserImage img = new UserImage();

            try
            {
                var destination = System.IO.Path.Combine(docs, UploadDirectory);      //adding uploads folder in the path to store images
                Directory.CreateDirectory(destination);                               //create uploads folder in specified path
                var absolutePath = GetRealPathFromURI(Application.Context, filePath); //convert uri to a path
                var fileName     = System.IO.Path.GetFileName(absolutePath);          //get the filename from the path
                var uploadImage  = System.IO.Path.Combine(destination, fileName);     //adding the filename to the destination path
                File.Copy(absolutePath, uploadImage);                                 //copying the file to the uploads folder

                img.Username  = AppData.LoggedInUser;
                img.ImageRef  = uploadImage;
                img.CreatedAt = DateTime.Now;
                db.InsertIntoUserImageTable(img); //insert data to userimage table
            }
            catch (Exception ex)
            {
                Console.WriteLine("Thrown exception is" + ex);
            }
            var reachability = new Reachability.Net.XamarinAndroid.Reachability();//check network

            if (reachability.IsHostReachable(ReachableHost))
            {
                String guid = Guid.NewGuid().ToString();            // generate a unique id

                var imagesref = storageRef.Child("images/" + guid); //guid assigns a new unique identifier to the image before storing in firebase
                if (filePath != null)
                {
                    imagesref.PutFile(filePath)//add image to firebase storage
                    .AddOnSuccessListener(this)
                    .AddOnFailureListener(this);
                    var firebase = new FirebaseClient(FirebaseURL); //add image reference to firebase database
                    img.ImageRef = imagesref.ToString();
                    var FirebaseReference = (await firebase.Child(FirebaseUserImageChild).PostAsync <UserImage>(img)).Key;
                    img.FirebaseReference = FirebaseReference;
                    db.UpdateUserImageTable(img);
                }
                else
                {
                    Toast.MakeText(this, "First choose an image", ToastLength.Short).Show();
                }
            }
            else
            {
                Toast.MakeText(this, "Uploaded Successfully", ToastLength.Short).Show();
            }
        }
Ejemplo n.º 26
0
        private void UpdateAvatar(Uri uri)
        {
            var image = storageReference.Child($"Images/{System.Guid.NewGuid()}");

            var title   = Resources.GetString(Resource.String.change_avatar);
            var message = Resources.GetString(Resource.String.wait);

            progressDialog = Context.CreateDialog(title, message);
            progressDialog.Show();

            image.PutFile(uri)
            .AddOnSuccessListener(this)
            .AddOnFailureListener(this);
        }
Ejemplo n.º 27
0
    public async Task DownloadReference()
    {
        string tourJsonName = "tour.json";

        Debug.Log(localDLPath);

        // download json
        string localJsonPath = Path.Combine(localDLPath, tourJsonName);

        StorageReference childref = tourReference.Child(tourJsonName);

        Debug.Log("DOWNLOADING TO " + localJsonPath);
        await childref.GetFileAsync(localJsonPath);

        // download images
        foreach (string imgName in imgNames)
        {
            string localImgPath = Path.Combine(Application.streamingAssetsPath, imgName);
            localImgPath = Path.Combine(localDLPath, imgName);
            Debug.Log(localImgPath);

            await tourReference.Child(imgName).GetFileAsync(localImgPath)
            .ContinueWith(resultTask =>
            {
                if (!resultTask.IsFaulted && !resultTask.IsCanceled)
                {
                    Debug.Log("Download finished.");
                }
                else
                {
                    Debug.Log(resultTask);
                }
            });
        }

        Debug.Log("All downloads complete");
    }
Ejemplo n.º 28
0
    private void GetDataFromCloud(string uID)
    {
        FirebaseStorage storage = FirebaseStorage.DefaultInstance;

        StorageReference storage_ref = storage.GetReferenceFromUrl(networkURL);

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

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

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

        // Download to the local file system
        fileRef.GetFileAsync(path).ContinueWith(task =>
        {
            if (!task.IsFaulted && !task.IsCanceled)
            {
                Debug.Log("Stranger File downloaded.");
            }
            else
            {
                Debug.Log(task.Exception.ToString());
            }

            expectedStrangerDataCount--;

            if (expectedStrangerDataCount == 0)
            {
                strangerDataDownloaded = true;
            }

            List <WishData> data = JsonConvert.DeserializeObject <List <WishData> >(File.ReadAllText(path));

            if (data == null)
            {
            }
            else if (data.Count > 1)
            {
                //WishData f**k = data[UnityEngine.Random.Range(0, data.Count)];
                WishData f**k = data[0];
                allWishData.Add(f**k);
            }
            else
            {
                allWishData.Add(data[0]);
            }
        });
    }
Ejemplo n.º 29
0
    int handleDetectObject(byte[] data)
    {
        // Create a storage reference from our storage service
        StorageReference storage_ref =
            fbStorage.GetReferenceFromUrl("gs://sandboxvr-40119.appspot.com");


        // Create a reference to the file you want to upload
        StorageReference curImg = storage_ref.Child("images//green.jpeg");

        Debug.Log(curImg.ToString());

        StartCoroutine(uploadFile(curImg, data));
        return(0);
    }
Ejemplo n.º 30
0
 private void UploadImage()
 {
     if (filePath != null) //ada gambar
     {
         progressDialog = new ProgressDialog(this);
         progressDialog.SetTitle("Uploading...");
         progressDialog.Window.SetType(Android.Views.WindowManagerTypes.SystemAlert);
         progressDialog.Show();
         var images = storageRef.Child("images/" + Guid.NewGuid().ToString());
         images.PutFile(filePath)
         .AddOnProgressListener(this)
         .AddOnSuccessListener(this)
         .AddOnFailureListener(this);
     }
 }