コード例 #1
0
        public void PatchObject()
        {
            var bucketName = _fixture.BucketName;

            // Snippet: PatchObject
            var client  = StorageClient.Create();
            var name    = "patch-example.txt";
            var content = Encoding.UTF8.GetBytes("hello, world");
            var obj     = new Apis.Storage.v1.Data.Object
            {
                Bucket      = bucketName,
                Name        = name,
                ContentType = "text/json", // Deliberately incorrect
                Metadata    = new Dictionary <string, string>
                {
                    { "key1", "value1" },
                    { "key2", "value2" }
                }
            };

            client.UploadObject(obj, new MemoryStream(content));

            var patchObject = new Apis.Storage.v1.Data.Object
            {
                // The bucket and name are required; everything else is optional.
                // Only specified properties will be updated.
                Bucket      = bucketName,
                Name        = name,
                ContentType = "text/plain",
                Metadata    = new Dictionary <string, string>
                {
                    { "key2", "updated-value2" },
                    { "key3", "value3" }
                }
            };

            client.PatchObject(patchObject);
            // End snippet

            var fetchedObject = client.GetObject(bucketName, name);

            Assert.Equal(name, fetchedObject.Name);
            Assert.Equal("text/plain", fetchedObject.ContentType);
            // key1=value1 still exists, because the patch didn't remove it
            Assert.Equal("value1", fetchedObject.Metadata["key1"]);
            Assert.Equal("updated-value2", fetchedObject.Metadata["key2"]);
            Assert.Equal("value3", fetchedObject.Metadata["key3"]);
        }
コード例 #2
0
        public void UpdateObject()
        {
            var bucketName = _fixture.BucketName;

            // Snippet: UpdateObject
            var client  = StorageClient.Create();
            var name    = "update-example.txt";
            var content = Encoding.UTF8.GetBytes("hello, world");
            var obj     = new Apis.Storage.v1.Data.Object
            {
                Bucket      = bucketName,
                Name        = name,
                ContentType = "text/json",
                Metadata    = new Dictionary <string, string>
                {
                    { "key1", "value1" },
                    { "key2", "value2" }
                }
            };

            // The update call requires full object information, so we set the projection to "full" here.
            // An alternative would be to upload the object and then separately fetch it, again with
            // a full projection.
            obj = client.UploadObject(obj, new MemoryStream(content), new UploadObjectOptions {
                Projection = Projection.Full
            });
            obj.Metadata.Remove("key1");
            obj.Metadata["key2"] = "updated-value2";
            obj.Metadata["key3"] = "value3";
            obj.ContentType      = "text/plain";
            client.UpdateObject(obj);
            // End snippet

            var fetchedObject = client.GetObject(bucketName, name);

            Assert.Equal(name, fetchedObject.Name);
            Assert.False(fetchedObject.Metadata.ContainsKey("key1"));
            Assert.Equal("text/plain", fetchedObject.ContentType);
            Assert.Equal("updated-value2", fetchedObject.Metadata["key2"]);
            Assert.Equal("value3", fetchedObject.Metadata["key3"]);
        }
コード例 #3
0
        public void UpdateObject()
        {
            var bucketName = _fixture.BucketName;

            // Snippet: UpdateObject
            var client  = StorageClient.Create();
            var name    = "update-example.txt";
            var content = Encoding.UTF8.GetBytes("hello, world");
            var obj     = new Apis.Storage.v1.Data.Object
            {
                Bucket      = bucketName,
                Name        = name,
                ContentType = "text/json",
                Metadata    = new Dictionary <string, string>
                {
                    { "key1", "value1" },
                    { "key2", "value2" }
                }
            };

            obj = client.UploadObject(obj, new MemoryStream(content));
            obj.Metadata.Remove("key1");
            obj.Metadata["key2"] = "updated-value2";
            obj.Metadata["key3"] = "value3";
            obj.ContentType      = "text/plain";
            client.UpdateObject(obj);
            // End snippet

            var fetchedObject = client.GetObject(bucketName, name);

            Assert.Equal(name, fetchedObject.Name);
            Assert.False(fetchedObject.Metadata.ContainsKey("key1"));
            Assert.Equal("text/plain", fetchedObject.ContentType);
            Assert.Equal("updated-value2", fetchedObject.Metadata["key2"]);
            Assert.Equal("value3", fetchedObject.Metadata["key3"]);
        }
コード例 #4
0
 public CustomMediaUpload(IClientService service, Apis.Storage.v1.Data.Object body, string bucket,
                          Stream stream, string contentType)
     : base(service, body, bucket, stream, contentType)
 {
 }
            /// <summary>
            /// Uploads a local file to a given bucket. The object's name will be the same as
            /// provided file path. (e.g. "C:\foo\bar.txt".)
            /// </summary>
            public Apis.Storage.v1.Data.Object UploadLocalFile(string filePath, string bucketName)
            {
                string fileName = "toImport";
                Stream contentStream = new FileStream(filePath, FileMode.Open);
                Apis.Storage.v1.Data.Object newGcsObject = new Apis.Storage.v1.Data.Object
                {
                    Bucket = bucketName,
                    Name = fileName,
                    ContentType = "application/octet-stream"
                };
                ObjectsResource.InsertMediaUpload insertReq = _bucketService.Objects.Insert(
                    newGcsObject, bucketName, contentStream, "application/octet-stream");
                var finalProgress = insertReq.Upload();
                if (finalProgress.Exception != null)
                {
                    throw finalProgress.Exception;
                }
                contentStream.Close();

                return _bucketService.Objects.Get(bucketName, fileName).Execute();
            }
        protected override void ProcessRecord()
        {
            if (!ImportFilePath.StartsWith("gs://"))
            {
                if (ShouldProcess($"{Project}/{Instance}/{ImportFilePath}",
                    "Create a new Google Cloud Storage bucket and upload the file to it for import.",
                    "Will be deleted after the import completes"))
                {
                    _tempUploader = new GcsFileUploader(GetBaseClientServiceInitializer(), Project);
                    Random rnd = new Random();
                    int bucketRnd = rnd.Next(1000000);
                    string bucketName = "import" + bucketRnd.ToString();
                    WriteVerbose($"Creating a Google Cloud Storage Bucket for the file at {ImportFilePath}.");
                    _tempGcsBucket = _tempUploader.CreateBucket(bucketName);
                    try
                    {
                        WriteVerbose($"Uploading the file at {ImportFilePath} to the new Google Cloud Storage Bucket.");
                        _tempGcsObject = _tempUploader.UploadLocalFile(ImportFilePath, bucketName);
                    }
                    catch (Exception e)
                    {
                        _tempUploader.DeleteBucket(_tempGcsBucket);
                        throw e;
                    }
                    DatabaseInstance myInstance = Service.Instances.Get(Project, Instance).Execute();
                    WriteVerbose("Updating the permissions for the uploaded file.");
                    _tempUploader.AdjustAcl(_tempGcsObject, myInstance.ServiceAccountEmailAddress);
                    ImportFilePath = string.Format("gs://{0}/{1}", bucketName, "toImport");
                }
                else return;
            }

            InstancesImportRequest body = new InstancesImportRequest
            {
                ImportContext = new ImportContext
                {
                    Kind = "sql#importContext",
                    Uri = ImportFilePath,
                    FileType = ParameterSetName.ToString(),
                    Database = Database,
                }
            };

            if (ParameterSetName == ParameterSetNames.Csv)
            {
                body.ImportContext.CsvImportOptions = new ImportContext.CsvImportOptionsData
                {
                    Columns = Column,
                    Table = DestinationTable
                };
            }
            InstancesResource.ImportRequest request = Service.Instances.Import(body, Project, Instance);
            WriteVerbose($"Importing the file at '{ImportFilePath}' to Instance '{Instance}'.");
            Operation result = request.Execute();
            result = WaitForSqlOperation(result);
            if (_tempUploader != null)
            {
                WriteVerbose("Deleting the Google Cloud Storage Bucket that was created, along with uploaded file.");
                _tempUploader.DeleteObject(_tempGcsObject);
                _tempUploader.DeleteBucket(_tempGcsBucket);
            }
            if (result.Error != null)
            {
                foreach (OperationError error in result.Error.Errors)
                {
                    throw new GoogleApiException("Google Cloud SQL API", error.Message + error.Code);
                }
            }
        }