Exemplo n.º 1
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);
    }
Exemplo n.º 2
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;
            });
        }
Exemplo n.º 3
0
        public Storage(ISettingsManager settingsManager,
                       ILogger logger)
        {
            _logger = logger;
            switch (settingsManager.StorageStrategy)
            {
            case StorageStrategy.Speed:
                _engine = Engine.Create();
                break;

            case StorageStrategy.Esent:
                _engine = Strategies.Esent.Engine.Create();
                break;

            case StorageStrategy.MemoryMappedFiles:
                _engine = Strategies.Mmf.Engine.Create();
                break;

            default:
                _engine = Engine.Create();
                break;
            }
            _metadata = StorageMetadata.ReadMetadata(_logger);
            foreach (var databaseParameters in _metadata.Databases)
            {
                _engine.OpenDatabase(databaseParameters.Value);
            }
            _serializer = DefaultSerializer.Create(_metadata);
        }
Exemplo n.º 4
0
        public Did CreateDatabase(IDatabaseParameters databaseParameters)
        {
            if (_metadata.Databases.Any(d => d.Value.Name.Equals(databaseParameters.Name)))
            {
                throw new DatabaseAlreadyExistException(String.Format("Baza danych o nazwie '{0}' już istnieje",
                                                                      databaseParameters.Name));
            }
            var newDid = Did.CreateNew();

            if (databaseParameters.Schema == null)
            {
                databaseParameters.Schema = new DatabaseSchema()
                {
                    DatabaseId = newDid,
                    Classes    = new ConcurrentDictionary <ClassId, Class>(),
                    Properties = new ConcurrentDictionary <PropertyId, Property>(),
                    Methods    = new ConcurrentDictionary <ClassId, List <IMethod> >()
                }
            }
            ;
            newDid.Duid = _metadata.Databases.Count == 0 ? 0 : _metadata.Databases.Max(d => d.Key.Duid) + 1;
            databaseParameters.DatabaseId = newDid;
            if (!_metadata.Databases.TryAdd(newDid, databaseParameters))
            {
                throw  new ApplicationException("Database creation internal storage error...");
            }
            _engine.OpenDatabase(databaseParameters);

            StorageMetadata.SaveMetadata(_metadata, _logger);
            return(newDid);
        }
Exemplo 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.
                    }
                });
            }
        });
    }
Exemplo n.º 6
0
        public async Task uploads_stream_with_meta_data()
        {
            var path      = $"texts/via_stream_with_metadata.txt";
            var metadata  = new StorageMetadata(contentType: "text/plain");
            var reference = CrossFirebaseStorage
                            .Current
                            .GetReferenceFromPath(path);

            await reference.PutBytes(Encoding.UTF8.GetBytes("Some test text"), metadata).AwaitAsync();

            var uploadedMetadata = await reference.GetMetadataAsync();

            Assert.Equal(path, uploadedMetadata.Path);
            Assert.Equal("text/plain", uploadedMetadata.ContentType);
            Assert.Equal(14, uploadedMetadata.Size);

            var customData = new Dictionary <string, string> {
                { "some_key", "some_value" }
            };
            var updatedMetadata = await reference.UpdateMetadataAsync(new StorageMetadata(contentType : "text/html", customMetadata : customData));

            Assert.Equal(path, updatedMetadata.Path);
            Assert.Equal("text/html", updatedMetadata.ContentType);
            Assert.Equal(customData, updatedMetadata.CustomMetadata);
        }
Exemplo n.º 7
0
        public void AddNewQuest(UIImage image)
        {
            /*object[] alcoholKeys = { "Nombre", "Edad", "Correo", "Password", "Sexo", "rutaImagen" };
             * object[] alcoholValues = { "Andrea Hernandez De Alba", "21", "*****@*****.**", "123456789", "M", "qwerty" };
             * var qs2 = NSDictionary.FromObjectsAndKeys(alcoholValues, alcoholKeys, alcoholKeys.Length);
             * DatabaseReference rootNode = Database.DefaultInstance.GetRootReference();
             * DatabaseReference productosNode = rootNode.GetChild("0").GetChild("Usuarios");
             * DatabaseReference productoNode = productosNode.GetChildByAutoId();
             * productoNode.SetValue<NSDictionary>(qs2);*/
            var profileImageRef = rootRefStorage.GetChild($"/1/profile.jpg");

            var imageMetadata = new StorageMetadata
            {
                ContentType = "image/jpeg"
            };

            image = ResizeImage(image, 170, 170);

            profileImageRef.PutData(image.AsJPEG(), imageMetadata, (metadata, error) =>
            {
                if (error != null)
                {
                    Console.WriteLine("Error");
                }
            });
        }
        public IStorageResult <IStorageMetadata, TContext> Store(TRecord record, TContext context)
        {
            var metadata = new StorageMetadata();

            try
            {
                this.OnPreInsert(record, context);

                using (var db = this.factory.Create <TDbContext>())
                {
                    db.Set <TRecord>().Add(record);

                    db.SaveChanges();
                }

                this.OnPostInsert(record, context);
            }
            catch (Exception ex)
            {
                metadata.Exception = ex;
            }

            metadata.EndTime = DateTimeOffset.Now;

            return(new StorageResult <IStorageMetadata, TContext>(metadata, context));
        }
Exemplo n.º 9
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);
            }
        });
    }
Exemplo n.º 10
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;
        }
    }
Exemplo n.º 11
0
 public void SaveSchema(IDatabaseSchema schema)
 {
     if (!_metadata.Databases.ContainsKey(schema.DatabaseId))
     {
         throw new DatabaseNotFoundException(String.Format("Nie odnaleziono bazy danych o id: '{0}'",
                                                           schema.DatabaseId));
     }
     _metadata.Databases[schema.DatabaseId].Schema = schema;
     StorageMetadata.SaveMetadata(_metadata, _logger);
 }
Exemplo n.º 12
0
 private Storage(IEngine engine,
                 ISerializer serializer,
                 StorageMetadata metadata,
                 ILogger logger)
 {
     _engine     = engine;
     _metadata   = metadata;
     _logger     = logger;
     _serializer = serializer;
 }
Exemplo n.º 13
0
        void Init(string applicationKey, string privateKey, UriPrototype storageurl, UriPrototype messengerUrl)
        {
            ApplicationKey = applicationKey;
            PrivateKey     = privateKey;
            MessengerUrl   = messengerUrl;
            Metadata       = new StorageMetadata();
            Repository     = new StorageRepository(applicationKey, PrivateKey, storageurl);

            Connect();
        }
Exemplo n.º 14
0
 public void Dispose()
 {
     if (_engine != null)
     {
         _engine.Dispose();
     }
     if (_metadata != null)
     {
         StorageMetadata.SaveMetadata(_metadata, _logger);
     }
 }
Exemplo n.º 15
0
        public void InitializeSystem(User dataOwner, Role dataOwnerRootRole)
        {
            this.metadata = new StorageMetadata();
            this.metadata.DataOwnerUserId = dataOwner.Id;
            this.metadata.DataOwnerRoleId = dataOwnerRootRole.Id;

            CreateUser(dataOwner);
            CreateRole(dataOwnerRootRole);

            SaveMetadata();
        }
Exemplo n.º 16
0
    private IEnumerator GetFileUri(StorageMetadata storageMetadata)
    {
        var uritask = storageMetadata.Reference.GetDownloadUrlAsync();

        yield return(new WaitUntil(() => uritask.IsCompleted));

        String uri = uritask.Result.ToString();

        imageURLs.Add(uri);

        CodelabUtils._ShowAndroidToastMessage($"Successfully stored Uri to list : {uri}");
    }
Exemplo n.º 17
0
 void HandleStorageGetPutUpdateCompletionHandler(StorageMetadata metadata, NSError error)
 {
     if (error == null)
     {
         ToastIOS.Toast.MakeText("Upload Successful").Show();
         imageView.Image = null;
         imageTitle.Text = string.Empty;
     }
     else
     {
         ToastIOS.Toast.MakeText("Upload Failed").Show();
         Console.WriteLine("Error " + error.Description);
     }
 }
        // Upload image to Firebase Storage.
        void SaveImageToStorage(string imageId, UIImage image)
        {
            var imageMetadata = new StorageMetadata {
                ContentType = "image/jpeg"
            };
            StorageReference storageImageNode = storageImagesNode.GetChild(imageId);

            storageImageNode.PutData(image.AsJPEG(), imageMetadata, (metadata, error) => {
                if (error != null)
                {
                    Console.WriteLine(error.LocalizedDescription);
                }
            });
        }
Exemplo n.º 19
0
        public DeleteDatabaseStatus RemoveDatabase(IDatabaseRemoveParameters databaseRemoveParameters)
        {
            if (!_metadata.Databases.ContainsKey(databaseRemoveParameters.DatabaseToRemove))
            {
                throw new DatabaseNotFoundException(String.Format("Nie odnaleziono bazy danych o id: '{0}'",
                                                                  databaseRemoveParameters.DatabaseToRemove));
            }

            IDatabaseParameters parameters = null;

            _metadata.Databases.TryRemove(databaseRemoveParameters.DatabaseToRemove, out parameters);

            StorageMetadata.SaveMetadata(_metadata, _logger);
            return(new DeleteDatabaseStatus());
        }
Exemplo n.º 20
0
        /// <summary>
        /// upload VRM file to server
        /// </summary>
        /// <param name="filepath">Current VRM model path</param>
        public async Task UploadVRM(string filepath)
        {
            var fileType             = new MetadataChange();
            StorageReference vrmPath = Storage_ref.Child("VRP/" + CurrentUser.UserId + "/vrm/" + Path.GetFileName(filepath));
            //get thumbnail form vrm
            var context = new VRMImporterContext();

            byte[] vrmByte = null;
            using (FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read))
            {
                vrmByte = new byte[fs.Length];
                fs.Read(vrmByte, 0, vrmByte.Length);
                context.ParseGlb(vrmByte);
            }
            var meta = context.ReadMeta(true);

            string th;

            byte[] thumbnailData = meta.Thumbnail.EncodeToPNG();
            try
            {
                th = Convert.ToBase64String(thumbnailData);
            }
            catch (Exception e)
            {
                th = "";
            }
            isUploading          = true;
            fileType.ContentType = "application/vrm";

            await vrmPath.PutBytesAsync(vrmByte, fileType).ContinueWith((Task <StorageMetadata> task) =>
            {
                if (task.IsFaulted || task.IsCanceled)
                {
                    Debug.Log(task.Exception.ToString());
                    // Uh-oh, an error occurred!
                    isUploading = false;
                }
                else
                {
                    // Metadata contains file metadata such as size, content-type, and download URL.
                    metadata = task.Result;
                    Debug.Log("Finished uploading...");
                }
                isUploading = false;
            });
        }
Exemplo n.º 21
0
    // Convert a Metadata object to a string.
    protected string MetadataToString(StorageMetadata metadata, bool onlyMutableFields)
    {
        var fieldsAndValues = new Dictionary <string, object> {
            { "ContentType", metadata.ContentType },
            { "CacheControl", metadata.CacheControl },
            { "ContentDisposition", metadata.ContentDisposition },
            { "ContentEncoding", metadata.ContentEncoding },
            { "ContentLanguage", metadata.ContentLanguage }
        };

        if (!onlyMutableFields)
        {
            foreach (var kv in new Dictionary <string, object> {
                { "Reference", metadata.Reference != null ?
                  metadata.Reference.Path : null },
                { "Path", metadata.Path },
                { "Name", metadata.Name },
                { "Bucket", metadata.Bucket },
                { "Generation", metadata.Generation },
                { "MetadataGeneration", metadata.MetadataGeneration },
                { "CreationTimeMillis", metadata.CreationTimeMillis },
                { "UpdatedTimeMillis", metadata.UpdatedTimeMillis },
                { "SizeBytes", metadata.SizeBytes },
                { "Md5Hash", metadata.Md5Hash },
                { "DownloadUrl", metadata.DownloadUrl }
            })
            {
                fieldsAndValues[kv.Key] = kv.Value;
            }
            var urls = metadata.DownloadUrls;
            for (int i = 0; i < urls.Count; ++i)
            {
                fieldsAndValues[String.Format("DownloadUrls[{0}]", i)] = urls[i];
            }
        }
        foreach (var key in metadata.CustomMetadataKeys)
        {
            fieldsAndValues[key] = metadata.GetCustomMetadata(key);
        }
        var fieldAndValueStrings = new List <string>();

        foreach (var kv in fieldsAndValues)
        {
            fieldAndValueStrings.Add(String.Format("{0}={1}", kv.Key, kv.Value));
        }
        return(String.Join("\n", fieldAndValueStrings.ToArray()));
    }
Exemplo n.º 22
0
    public void DownloadLatestMap(DownloadCallback callback)
    {
        reference.GetMetadataAsync().ContinueWith((Task <StorageMetadata> metadataTask) =>
        {
            if (metadataTask.IsFaulted || metadataTask.IsCanceled)
            {
                Debug.Log("Failed to download metadata.");
                Debug.Log(metadataTask.Exception.InnerException.Message);
            }
            else if (metadataTask.IsCompleted)
            {
                Debug.Log("Metadata successfully downloaded.");
                StorageMetadata meta = metadataTask.Result;

                // If there's no local map or local map is old, download new map from cloud.
                if (!MapExists || meta.CreationTimeMillis > File.GetLastWriteTimeUtc(WorldMapPath))
                {
                    Debug.Log("Beginning map download.");
                    DownloadInProgress = true;
                    reference.GetFileAsync(FirebaseWorldMapPath).ContinueWith(mapTask =>
                    {
                        DownloadInProgress = false;

                        if (mapTask.IsFaulted || mapTask.IsCanceled)
                        {
                            Debug.Log("Failed to download map.");
                            Debug.Log(mapTask.Exception.InnerException.Message);
                        }
                        else if (mapTask.IsCompleted)
                        {
                            Debug.Log("Map successfully downloaded.");
                            callback();
                        }
                    });
                }
                else
                {
                    Debug.Log("No need to download new map.");
                    callback();
                }
            }
        });
    }
Exemplo n.º 23
0
        public Did RenameDatabase(IDatabaseParameters databaseParameters, string databaseNweName, ISettingsManager settingsManager)
        {
            DatabaseParameters renamedParameters = new DatabaseParameters(databaseNweName, settingsManager);

            renamedParameters.DatabaseId     = databaseParameters.DatabaseId;
            renamedParameters.Schema         = databaseParameters.Schema;
            renamedParameters.PageSize       = databaseParameters.PageSize;
            renamedParameters.OptimizeSize   = databaseParameters.OptimizeSize;
            renamedParameters.StartupSize    = databaseParameters.StartupSize;
            renamedParameters.IncreaseFactor = databaseParameters.IncreaseFactor;

            _metadata.Databases[databaseParameters.DatabaseId] = renamedParameters;

            StorageMetadata.SaveMetadata(_metadata, _logger);
            //_engine.Dispose();
            //File.Move(databaseParameters.DataFileFullPath, renamedParameters.DataFileFullPath);
            _engine.OpenDatabase(renamedParameters);
            return(renamedParameters.DatabaseId);
        }
Exemplo n.º 24
0
        public void AddImage(UIImage image)
        {
            var profileImageRef = rootRefStorage.GetChild($"/users/{DataPersistanceClass.persona.Id}.jpg");

            var imageMetadata = new StorageMetadata
            {
                ContentType = "image/jpeg"
            };

            image = ResizeImage(image, 170, 170);

            profileImageRef.PutData(image.AsJPEG(), imageMetadata, (metadata, error) =>
            {
                if (error != null)
                {
                    Console.WriteLine("Error");
                }
            });
        }
        public static StorageMetadata ToStorageMetadata(this MetadataChange self)
        {
            if (self == null)
            {
                return(null);
            }

            var storageMetadata = new StorageMetadata();

            if (self.IsCacheControlChanged)
            {
                storageMetadata.CacheControl = self.CacheControl;
            }

            if (self.IsContentDispositionChanged)
            {
                storageMetadata.ContentDisposition = self.ContentDisposition;
            }

            if (self.IsContentEncodingChanged)
            {
                storageMetadata.ContentEncoding = self.ContentEncoding;
            }

            if (self.IsContentLanguageChanged)
            {
                storageMetadata.ContentLanguage = self.ContentLanguage;
            }

            if (self.IsContentTypeChanged)
            {
                storageMetadata.ContentType = self.ContentType;
            }

            if (self.CustomMetadata != null)
            {
                storageMetadata.CustomMetadata = new NSDictionary <NSString, NSString>(self.CustomMetadata.Keys.Select(s => new NSString(s)).ToArray(),
                                                                                       self.CustomMetadata.Values.Select(s => new NSString(s)).ToArray());
            }

            return(storageMetadata);
        }
Exemplo n.º 26
0
    public static void UploadBytes(byte[] bytes, string saveName, string saveAt)
    {
        StorageReference postTextRef = storage.RootReference.Child(saveAt + "/" + saveName);

        postTextRef.PutBytesAsync(bytes).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 md5hash.
                StorageMetadata metadata = task.Result;
                string md5Hash           = metadata.Md5Hash;
                Debug.Log("Finished uploading...");
                Debug.Log("md5 hash = " + md5Hash);
            }
        });
    }
Exemplo n.º 27
0
    public void GetMetadataTask(string path)
    {
        // Create reference to the file whose metadata we want to retrieve
        var storage = FirebaseStorage.DefaultInstance;
        // 파일이름 임의로 지정
        var screenshotReference = storage.GetReference(path).Child($"/screenshots/2020-07-29+22-38-14.png");

        screenshotReference.GetMetadataAsync().ContinueWith((Task <StorageMetadata> task) =>
        {
            if (task.Exception != null)
            {
                Debug.LogError("메타데이터 수집에 실패했습니다." + task.Exception);
            }
            else
            {
                StorageMetadata meta = task.Result;
                Debug.Log("메타데이터 수집에 성공했습니다." + meta.Path);
            }
        });
    }
Exemplo n.º 28
0
    public static void SaveItemImage(Item item)
    {
        // Create a reference for the image
        StorageReference imageReference = FirebaseStorage.DefaultInstance.GetReference("images").Child("items").Child(item.itemId);

        // Upload the image to the path (images/items/(item.itemName))
        imageReference.PutFileAsync(item.itemImagePath.ToString()).ContinueWith((Task <StorageMetadata> task) =>
        {
            if (task.IsCanceled || task.IsFaulted)
            {
                // Error happened
                Debug.Log(task.Exception.ToString());
                ViewMessageOnScreen(task.Exception.ToString());
            }
            else
            {
                // Metadata contains file metadata such as file size, content type and downloadURL
                StorageMetadata metadata = task.Result;
                Debug.Log("Finished Uploading .... ");
                // Gets the download url
                imageReference.GetDownloadUrlAsync().ContinueWith((url) =>
                {
                    if (url.IsCompleted)
                    {
                        Debug.Log("Image download url: " + url.Result.AbsoluteUri.ToString());
                        FirebaseDatabase.DefaultInstance.GetReference("items").Child(item.itemId).Child("itemImageDownloadUrl").SetValueAsync(url.Result.AbsoluteUri.ToString());
                        //FirebaseDatabase.DefaultInstance.GetReference("users").Child(Globals.userId).Child("cart").Child(item.itemName).Child("itemImageDownloadUrl").SetValueAsync(url.Result.AbsoluteUri.ToString());
                        item.itemImageDownloadUrl = url.Result.AbsoluteUri.ToString();
                        snapshotsLoaded           = true;
                        ViewMessageOnScreen("Uploaded Image ... ");
                        //AddItemToUserCart(item, Globals.userId.ToString());
                    }
                    else
                    {
                        Debug.Log("Image not uploaded ... ");
                        ViewMessageOnScreen("Image not uploaded check internet connection ... ");
                    }
                });
            }
        });
    }
Exemplo n.º 29
0
    public void Post()
    {
        clone = UIHelper.PushAndGetPrefabToParent(post, content.transform, 0);
        PostElement pe = clone.GetComponent <PostElement>();

        pe.postText = postText.text;

        // Upload Text
        FirebaseStorage  storage     = FirebaseStorage.DefaultInstance;
        StorageReference postTextRef = storage.RootReference.Child("posts/" + "username" + "/" + "nextID" + "/" + "postText");

        byte[] postTextbytes = Encoding.ASCII.GetBytes(pe.postText);

        postTextRef.PutBytesAsync(postTextbytes).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 md5hash.
                StorageMetadata metadata = task.Result;
                string md5Hash           = metadata.Md5Hash;
                Debug.Log("Finished uploading...");
                Debug.Log("md5 hash = " + md5Hash);
            }
        });

        if (imgBoard.transform.childCount > 0)   //there're images
        {
            foreach (Transform child in imgBoard.transform)
            {
                pe.ImageQueue.Add(child.gameObject.GetComponent <Image>());
            }
        }

        StartCoroutine(SiblingUpdate());
        pe.updateAll();
    }
Exemplo n.º 30
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();
                }
            }
                          );
        }
    }