Esempio n. 1
0
        public override string SavePrivate(string domain, string path, System.IO.Stream stream, DateTime expires)
        {
            var storage = GetStorage();

            var objectKey = MakePath(domain, path);
            var buffered  = stream.GetBuffered();

            UploadObjectOptions uploadObjectOptions = new UploadObjectOptions
            {
                PredefinedAcl = PredefinedObjectAcl.BucketOwnerFullControl
            };

            buffered.Position = 0;

            var uploaded = storage.UploadObject(_bucket, MakePath(domain, path), "application/octet-stream", buffered, uploadObjectOptions, null);

            uploaded.CacheControl       = String.Format("public, maxage={0}", (int)TimeSpan.FromDays(5).TotalSeconds);
            uploaded.ContentDisposition = "attachment";

            if (uploaded.Metadata == null)
            {
                uploaded.Metadata = new Dictionary <String, String>();
            }

            uploaded.Metadata["Expires"] = DateTime.UtcNow.Add(TimeSpan.FromDays(5)).ToString("R");
            uploaded.Metadata.Add("private-expire", expires.ToFileTimeUtc().ToString(CultureInfo.InvariantCulture));

            storage.UpdateObject(uploaded);

            var preSignedURL = UrlSigner.FromServiceAccountPath(_jsonPath)
                               .Sign(_bucket, MakePath(domain, path), expires, null);

            //TODO: CNAME!
            return(preSignedURL);
        }
Esempio n. 2
0
        // [END storage_list_files_with_prefix]

        // [START storage_upload_file]
        private void UploadFile(string pathToCredentials, string bucketName, string localPath,
                                string objectName = null, int retryTime = 0)
        {
            var storage = StorageClient.Create(CreateStorageClient(pathToCredentials));
            UploadObjectOptions options = new UploadObjectOptions();

            options.ChunkSize = UploadObjectOptions.MinimumChunkSize * 4;
            using (var f = File.OpenRead(localPath))
            {
                objectName = objectName ?? Path.GetFileName(localPath);
                try
                {
                    storage.UploadObject(bucketName, objectName, null, f, options, new UploadProgressReporter(f.Length));
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Upload failed due to: {ex.Message} \n {ex.StackTrace}");
                    if (retryTime < 3)
                    {
                        retryTime += 1;
                        Console.WriteLine($"Retrying {retryTime} / 3");
                        UploadFile(pathToCredentials, bucketName, localPath, objectName, retryTime);
                    }
                    else
                    {
                        Console.WriteLine($"Can't upload - giving up");
                        return;
                    }
                }
                Console.WriteLine($"Uploaded {objectName}.");
            }
        }
Esempio n. 3
0
        public void UploadObject()
        {
            var bucketName = _fixture.BucketName;

            // Snippet: UploadObject(string,string,*,*,*,*)
            var client      = StorageClient.Create();
            var source      = "world.txt";
            var destination = "places/world.txt";
            var contentType = "text/plain";

            using (var stream = File.OpenRead(source))
            {
                // IUploadProgress defined in Google.Apis.Upload namespace
                var progress = new Progress <IUploadProgress>(
                    p => Console.WriteLine($"bytes: {p.BytesSent}, status: {p.Status}")
                    );

                // var acl = PredefinedAcl.PublicRead // public
                var acl     = PredefinedObjectAcl.AuthenticatedRead; // private
                var options = new UploadObjectOptions {
                    PredefinedAcl = acl
                };
                var obj = client.UploadObject(bucketName, destination, contentType, stream, options, progress);
            }
            // End snippet

            // want to show the source in the snippet, but also
            // want to make sure it matches the one in the fixture
            Assert.Equal(source, _fixture.WorldLocalFileName);
        }
Esempio n. 4
0
        public override string SavePrivate(string domain, string path, System.IO.Stream stream, DateTime expires)
        {
            using var storage = GetStorage();

            var objectKey = MakePath(domain, path);
            var buffered  = TempStream.GetBuffered(stream);

            var uploadObjectOptions = new UploadObjectOptions
            {
                PredefinedAcl = PredefinedObjectAcl.BucketOwnerFullControl
            };

            buffered.Position = 0;

            var uploaded = storage.UploadObject(_bucket, MakePath(domain, path), "application/octet-stream", buffered, uploadObjectOptions, null);

            uploaded.CacheControl       = string.Format("public, maxage={0}", (int)TimeSpan.FromDays(5).TotalSeconds);
            uploaded.ContentDisposition = "attachment";

            if (uploaded.Metadata == null)
            {
                uploaded.Metadata = new Dictionary <string, string>();
            }

            uploaded.Metadata["Expires"] = DateTime.UtcNow.Add(TimeSpan.FromDays(5)).ToString("R");
            uploaded.Metadata.Add("private-expire", expires.ToFileTimeUtc().ToString(CultureInfo.InvariantCulture));

            storage.UpdateObject(uploaded);

            using var mStream = new MemoryStream(Encoding.UTF8.GetBytes(_json ?? ""));
            var preSignedURL = FromServiceAccountData(mStream).Sign(RequestTemplate.FromBucket(_bucket).WithObjectName(MakePath(domain, path)), UrlSigner.Options.FromExpiration(expires));

            //TODO: CNAME!
            return(preSignedURL);
        }
Esempio n. 5
0
        public async Task <CloudFile> UploadFileAsync(Stream stream, string bucket, string objectName, string filename, string contentType, CancellationToken cancellationToken = default, IProgress <IUploadProgress> progress = null)
        {
            Progress <Google.Apis.Upload.IUploadProgress> googleProgress = new Progress <Google.Apis.Upload.IUploadProgress>();

            if (progress != null)
            {
                googleProgress.ProgressChanged += (s, e) =>
                {
                    progress.Report(new GoogleUploadProgress(e, stream.Length));
                    GC.Collect();
                };
            }

            using (StorageClient client = await StorageClient.CreateAsync(_credential))
            {
                UploadObjectOptions options = new UploadObjectOptions
                {
                    ChunkSize = _chunkSize
                };

                var dataObject = await client.UploadObjectAsync(bucket, objectName, contentType, stream, options, cancellationToken, googleProgress);

                dataObject.ContentDisposition = $"filename=\"{filename}\"";

                dataObject = await client.PatchObjectAsync(dataObject);

                return(new CloudFile(GetDownloadLink(dataObject), dataObject.MediaLink));
            }
        }
 public override Object UploadObject(
     Object destination,
     Stream source,
     UploadObjectOptions options          = null,
     IProgress <IUploadProgress> progress = null)
 {
     return(UploadObject(destination.Bucket, destination.Name, destination.ContentType, source, options, progress));
 }
Esempio n. 7
0
        public void ValidChunkSize(int?chunkSize)
        {
            var options = new UploadObjectOptions {
                ChunkSize = chunkSize
            };

            Assert.Equal(chunkSize, options.ChunkSize);
        }
 public override Task <Object> UploadObjectAsync(
     Object destination,
     Stream source,
     UploadObjectOptions options          = null,
     CancellationToken cancellationToken  = default(CancellationToken),
     IProgress <IUploadProgress> progress = null)
 {
     return(Task.Run(() => UploadObject(destination, source, options, progress)));
 }
 public override Task <Object> UploadObjectAsync(
     string bucket,
     string objectName,
     string contentType,
     Stream source,
     UploadObjectOptions options          = null,
     CancellationToken cancellationToken  = default(CancellationToken),
     IProgress <IUploadProgress> progress = null)
 {
     return(Task.Run(() => UploadObject(bucket, objectName, contentType, source, options, progress)));
 }
Esempio n. 10
0
        public Uri Save(string domain, string path, Stream stream, string contentType,
                        string contentDisposition, ACL acl, string contentEncoding = null, int cacheDays = 5)
        {
            var buffered = stream.GetBuffered();

            if (QuotaController != null)
            {
                QuotaController.QuotaUsedCheck(buffered.Length);
            }

            var mime = string.IsNullOrEmpty(contentType)
                        ? MimeMapping.GetMimeMapping(Path.GetFileName(path))
                        : contentType;

            var storage = GetStorage();

            UploadObjectOptions uploadObjectOptions = new UploadObjectOptions
            {
                PredefinedAcl = acl == ACL.Auto ? GetDomainACL(domain) : GetGoogleCloudAcl(acl)
            };

            buffered.Position = 0;

            var uploaded = storage.UploadObject(_bucket, MakePath(domain, path), mime, buffered, uploadObjectOptions, null);

            uploaded.ContentEncoding = contentEncoding;
            uploaded.CacheControl    = String.Format("public, maxage={0}", (int)TimeSpan.FromDays(cacheDays).TotalSeconds);

            if (uploaded.Metadata == null)
            {
                uploaded.Metadata = new Dictionary <String, String>();
            }

            uploaded.Metadata["Expires"] = DateTime.UtcNow.Add(TimeSpan.FromDays(cacheDays)).ToString("R");

            if (!string.IsNullOrEmpty(contentDisposition))
            {
                uploaded.ContentDisposition = contentDisposition;
            }
            else if (mime == "application/octet-stream")
            {
                uploaded.ContentDisposition = "attachment";
            }

            storage.UpdateObject(uploaded);

            //           InvalidateCloudFront(MakePath(domain, path));

            QuotaUsedAdd(domain, buffered.Length);

            return(GetUri(domain, path));
        }
Esempio n. 11
0
        private static UploadObjectOptions GetUploadOptions(GxFileType fileType)
        {
            UploadObjectOptions options = new UploadObjectOptions();

            if (fileType.HasFlag(GxFileType.Private))
            {
                options.PredefinedAcl = PredefinedObjectAcl.ProjectPrivate;
            }
            else
            {
                options.PredefinedAcl = PredefinedObjectAcl.PublicRead;
            }
            return(options);
        }
        public void ModifyMediaUpload_DefaultOptions()
        {
            var upload  = new InsertMediaUpload(new DummyService(), null, "bucket", new MemoryStream(), null);
            var options = new UploadObjectOptions();

            options.ModifyMediaUpload(upload);
            Assert.Equal(ResumableUpload <InsertMediaUpload> .DefaultChunkSize, upload.ChunkSize);
            Assert.Null(upload.IfGenerationMatch);
            Assert.Null(upload.IfGenerationNotMatch);
            Assert.Null(upload.IfMetagenerationMatch);
            Assert.Null(upload.IfMetagenerationNotMatch);
            Assert.Null(upload.PredefinedAcl);
            Assert.Null(upload.Projection);
        }
Esempio n. 13
0
        public void CorsUpload()
        {
            var name        = IdGenerator.FromGuid();
            var contentType = "application/octet-stream";
            var source      = GenerateData(100);
            var options     = new UploadObjectOptions {
                Origin = "http://nodatime.org"
            };
            var result = _fixture.Client.UploadObject(_fixture.MultiVersionBucket, name, contentType, source, options);

            Assert.Equal(_fixture.MultiVersionBucket, result.Bucket);
            Assert.Equal(name, result.Name);
            Assert.Equal(contentType, result.ContentType);
            ValidateData(_fixture.MultiVersionBucket, name, source);
        }
Esempio n. 14
0
        public async Task UploadObjectAsync_InvalidHash_ThrowOnly()
        {
            var client      = StorageClient.Create();
            var interceptor = new BreakUploadInterceptor();

            client.Service.HttpClient.MessageHandler.AddExecuteInterceptor(interceptor);
            var stream  = GenerateData(50);
            var name    = IdGenerator.FromGuid();
            var bucket  = _fixture.MultiVersionBucket;
            var options = new UploadObjectOptions {
                UploadValidationMode = UploadValidationMode.ThrowOnly
            };
            await Assert.ThrowsAsync <UploadValidationException>(() => client.UploadObjectAsync(bucket, name, null, stream, options));

            // We don't delete the object, so it's still present.
            ValidateData(bucket, name, new MemoryStream(interceptor.UploadedBytes));
        }
Esempio n. 15
0
        public async Task UploadObjectAsync_InvalidHash_None()
        {
            var client      = StorageClient.Create();
            var interceptor = new BreakUploadInterceptor();

            client.Service.HttpClient.MessageHandler.AddExecuteInterceptor(interceptor);
            var stream  = GenerateData(50);
            var name    = IdGenerator.FromGuid();
            var bucket  = _fixture.MultiVersionBucket;
            var options = new UploadObjectOptions {
                UploadValidationMode = UploadValidationMode.None
            };
            // Upload succeeds despite the data being broken.
            await client.UploadObjectAsync(bucket, name, null, stream, options);

            // The object should contain our "wrong" bytes.
            ValidateData(bucket, name, new MemoryStream(interceptor.UploadedBytes));
        }
Esempio n. 16
0
        public void UploadObject_InvalidHash_DeleteAndThrow()
        {
            var client      = StorageClient.Create();
            var interceptor = new BreakUploadInterceptor();

            client.Service.HttpClient.MessageHandler.AddExecuteInterceptor(interceptor);
            var stream  = GenerateData(50);
            var name    = IdGenerator.FromGuid();
            var bucket  = _fixture.MultiVersionBucket;
            var options = new UploadObjectOptions {
                UploadValidationMode = UploadValidationMode.DeleteAndThrow
            };

            Assert.Throws <UploadValidationException>(() => client.UploadObject(bucket, name, null, stream, options));
            var notFound = Assert.Throws <GoogleApiException>(() => _fixture.Client.GetObject(bucket, name));

            Assert.Equal(HttpStatusCode.NotFound, notFound.HttpStatusCode);
        }
Esempio n. 17
0
        public virtual Object UploadObject(string bucket, string objectName, string contentType, Stream source, Stream destination, UploadObjectOptions options = null, IProgress <IUploadProgress> progress = null)
        {
            var client = StorageClient.Create();

            using (var stream = File.OpenRead(source))
            {
                // IUploadProgress defined in Google.Apis.Upload namespace
                var progress = new Progress <IUploadProgress>(
                    p => Console.WriteLine($"bytes: {p.BytesSent}, status: {p.Status}")
                    );

                // var acl = PredefinedAcl.PublicRead // public
                var acl     = PredefinedObjectAcl.AuthenticatedRead; // private
                var options = new UploadObjectOptions {
                    PredefinedAcl = acl
                };
                var obj = client.UploadObject(bucket, destination, contentType, stream, options, progress);
            }
        }
Esempio n. 18
0
        public async Task UploadObjectAsync_InvalidHash_DeleteAndThrow_DeleteFails()
        {
            var client      = StorageClient.Create();
            var interceptor = new BreakUploadInterceptor();

            client.Service.HttpClient.MessageHandler.AddExecuteInterceptor(interceptor);
            client.Service.HttpClient.MessageHandler.AddExecuteInterceptor(new BreakDeleteInterceptor());
            var stream  = GenerateData(50);
            var name    = IdGenerator.FromGuid();
            var bucket  = _fixture.MultiVersionBucket;
            var options = new UploadObjectOptions {
                UploadValidationMode = UploadValidationMode.DeleteAndThrow
            };
            var ex = await Assert.ThrowsAsync <UploadValidationException>(() => client.UploadObjectAsync(bucket, name, null, stream, options));

            Assert.NotNull(ex.AdditionalFailures);
            // The deletion failed, so the uploaded object still exists.
            ValidateData(bucket, name, new MemoryStream(interceptor.UploadedBytes));
        }
Esempio n. 19
0
        public void ModifyMediaUpload_MatchNotMatchConflicts()
        {
            var upload = new InsertMediaUpload(new DummyService(), null, "bucket", new MemoryStream(), null);

            Assert.Throws <ArgumentException>(() =>
            {
                var options = new UploadObjectOptions {
                    IfGenerationMatch = 1L, IfGenerationNotMatch = 2L
                };
                options.ModifyMediaUpload(upload);
            });
            Assert.Throws <ArgumentException>(() =>
            {
                var options = new UploadObjectOptions {
                    IfMetagenerationMatch = 1L, IfMetagenerationNotMatch = 2L
                };
                options.ModifyMediaUpload(upload);
            });
        }
Esempio n. 20
0
        public void ModifyMediaUpload_AllOptions_NegativeMatch()
        {
            var upload  = new InsertMediaUpload(new DummyService(), null, "bucket", new MemoryStream(), null);
            var options = new UploadObjectOptions
            {
                ChunkSize                = UploadObjectOptions.MinimumChunkSize * 3,
                IfGenerationNotMatch     = 1L,
                IfMetagenerationNotMatch = 2L,
                PredefinedAcl            = PredefinedObjectAcl.BucketOwnerRead,
                Projection               = Projection.Full
            };

            options.ModifyMediaUpload(upload);
            Assert.Null(upload.IfGenerationMatch);
            Assert.Equal(1L, upload.IfGenerationNotMatch);
            Assert.Null(upload.IfMetagenerationMatch);
            Assert.Equal(2L, upload.IfMetagenerationNotMatch);
            Assert.Equal(PredefinedAclEnum.BucketOwnerRead, upload.PredefinedAcl);
            Assert.Equal(ProjectionEnum.Full, upload.Projection);
        }
Esempio n. 21
0
        private async void button1_Click(object sender, EventArgs e)
        {
            var dlg = new OpenFileDialog();

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                using (var fileStream = new FileStream(dlg.FileName, FileMode.Open,
                                                       FileAccess.Read, FileShare.Read))
                {
                    progressBar1.Maximum = (int)fileStream.Length;

                    var uploadObjectOptions = new UploadObjectOptions
                    {
                        ChunkSize = UploadObjectOptions.MinimumChunkSize
                    };
                    var progressReporter = new Progress <IUploadProgress>(OnUploadProgress);
                    await storageClient.UploadObjectAsync(bucketName, Path.GetFileName(dlg.FileName), MimeUtility.GetMimeMapping(dlg.FileName), fileStream, uploadObjectOptions, progress : progressReporter).ConfigureAwait(true);

                    btn_getFiles_Click(sender, e);
                }
            }
        }
        // *************************************************************************************************************
        // UPLOAD OBJECT

        public override Object UploadObject(
            string bucket,
            string objectName,
            string contentType,
            Stream source,
            UploadObjectOptions options          = null,
            IProgress <IUploadProgress> progress = null)
        {
            var key = Key(bucket, objectName);

            byte[] data;
            using (var buffer = new MemoryStream())
            {
                source.CopyTo(buffer);
                buffer.Flush();
                data = buffer.ToArray();
            }
            var entry = new Entry(objectName, contentType ?? "application/octet-stream", data);

            _entries.AddOrUpdate(key, entry, (_, __) => entry);
            return(entry.ToObject(bucket));
        }
Esempio n. 23
0
        public async Task <IFileInformation> StoreFile(Stream fileStream)
        {
            var uniqueName = Guid.NewGuid().ToString();
            // try
            // {
            //     uniqueName = uniqueName.ApplyExtension(name, contentType);
            // }
            // catch (Exception ex)
            // {
            //     _logger.LogWarning(ex.Message);
            // }

            var uploadOptions = new UploadObjectOptions {
                ChunkSize = CHUNK_SIZE
            };
            await _googleClient.UploadObjectAsync(GoogleSettings.Bucket, uniqueName, "application/octet-stream", fileStream, uploadOptions);

            var info = new GoogleFileInformation {
                StorageIdentifier = uniqueName
            };

            return(info);
        }
Esempio n. 24
0
        public async Task UploadObjectWithSessionUri()
        {
            var bucketName = _fixture.BucketName;

            // Sample: UploadObjectWithSessionUri
            var client      = StorageClient.Create();
            var source      = "world.txt";
            var destination = "places/world.txt";
            var contentType = "text/plain";

            // var acl = PredefinedAcl.PublicRead // public
            var acl     = PredefinedObjectAcl.AuthenticatedRead; // private
            var options = new UploadObjectOptions {
                PredefinedAcl = acl
            };
            // Create a temporary uploader so the upload session can be manually initiated without actually uploading.
            var tempUploader = client.CreateObjectUploader(bucketName, destination, contentType, new MemoryStream(), options);
            var uploadUri    = await tempUploader.InitiateSessionAsync();

            // Send uploadUri to (unauthenticated) client application, so it can perform the upload:
            using (var stream = File.OpenRead(source))
            {
                // IUploadProgress defined in Google.Apis.Upload namespace
                IProgress <IUploadProgress> progress = new Progress <IUploadProgress>(
                    p => Console.WriteLine($"bytes: {p.BytesSent}, status: {p.Status}")
                    );

                var actualUploader = ResumableUpload.CreateFromUploadUri(uploadUri, stream);
                actualUploader.ProgressChanged += progress.Report;
                await actualUploader.UploadAsync();
            }
            // End sample

            // want to show the source in the snippet, but also
            // want to make sure it matches the one in the fixture
            Assert.Equal(source, _fixture.WorldLocalFileName);
        }
Esempio n. 25
0
        private async Task <PropertyImage> UploadEachFile(string url, bool isVariation)
        {
            if (!string.IsNullOrEmpty(url))
            {
                var extension       = Path.GetExtension(url);
                var filName         = GetFileName(url, extension);
                var deleteExtension = DeleteExtension(filName, extension);
                var variation       = !isVariation ? "" : GetVariation(url, extension);
                using (var fileStream = new FileStream(url, FileMode.Open,
                                                       FileAccess.Read, FileShare.Read))
                {
                    progressBar1.Maximum = (int)fileStream.Length;

                    var uploadObjectOptions = new UploadObjectOptions
                    {
                        ChunkSize = UploadObjectOptions.MinimumChunkSize
                    };
                    var progressReporter = new Progress <IUploadProgress>(OnUploadProgress);
                    var objectName       = $"{Guid.NewGuid().ToString()}.jpg";
                    var data             = await storageClient.UploadObjectAsync(bucketName,
                                                                                 objectName,
                                                                                 MimeUtility.GetMimeMapping(url),
                                                                                 fileStream, uploadObjectOptions,
                                                                                 progress : progressReporter
                                                                                 ).ConfigureAwait(true);

                    var link = $"http://storage.googleapis.com/{bucketName}/" + data.Name;
                    return(new PropertyImage()
                    {
                        FileName = deleteExtension,
                        PropertyVariation = variation,
                        Url = link
                    });
                }
            }
            return(new PropertyImage());
        }
Esempio n. 26
0
        public void ModifyMediaUpload_AllOptions_PositiveMatch()
        {
            var upload  = new CustomMediaUpload(new DummyService(), null, "bucket", new MemoryStream(), null);
            var options = new UploadObjectOptions
            {
                ChunkSize             = UploadObjectOptions.MinimumChunkSize * 3,
                IfGenerationMatch     = 1L,
                IfMetagenerationMatch = 2L,
                KmsKeyName            = "key",
                PredefinedAcl         = PredefinedObjectAcl.BucketOwnerRead,
                Projection            = Projection.Full,
                UserProject           = "proj"
            };

            options.ModifyMediaUpload(upload);
            Assert.Equal(1L, upload.IfGenerationMatch);
            Assert.Null(upload.IfGenerationNotMatch);
            Assert.Equal(2L, upload.IfMetagenerationMatch);
            Assert.Null(upload.IfMetagenerationNotMatch);
            Assert.Equal("key", upload.KmsKeyName);
            Assert.Equal(PredefinedAclEnum.BucketOwnerRead, upload.PredefinedAcl);
            Assert.Equal(ProjectionEnum.Full, upload.Projection);
            Assert.Equal("proj", upload.UserProject);
        }
Esempio n. 27
0
        /// <summary>
        /// Uploads the file onto Google Storage.
        /// </summary>
        private async Task GSUpload()
        {
            OnGSUploading(EventArgs.Empty);

            try
            {
                var client      = StorageClient.Create();
                var objectName  = System.IO.Path.GetFileName(ReencodedPath);
                var contentType = "text/plain";

                var options = new UploadObjectOptions();
                // Create a temporary uploader so the upload session can be manually initiated without actually uploading.
                var tempUploader = client.CreateObjectUploader(Bucket, objectName, contentType, new MemoryStream(), options);
                var uploadUri    = await tempUploader.InitiateSessionAsync();

                // Send uploadUri to (unauthenticated) client application, so it can perform the upload:
                using (var stream = File.OpenRead(ReencodedPath))
                {
                    IProgress <IUploadProgress> progress = new Progress <IUploadProgress>(
                        p => { GSUploadProgress = (float)p.BytesSent / stream.Length * 100; OnGSUploading(EventArgs.Empty); }
                        );

                    var actualUploader = ResumableUpload.CreateFromUploadUri(uploadUri, stream);
                    actualUploader.ProgressChanged += progress.Report;
                    actualUploader.ChunkSize        = ResumableUpload.MinimumChunkSize * 4;
                    await actualUploader.UploadAsync();
                }

                GSUri = GetGSUriFromObjectName(Bucket, objectName);
                OnGSUploaded(EventArgs.Empty);
            }
            catch (Exception e)
            {
                throw new GSUploadException("An error occured while uploading the file.", e);
            }
        }
Esempio n. 28
0
        private void CreateFolder(String name, string table = null, string field = null)
        {
            name = StorageUtils.NormalizeDirectoryName(name);
            if (table != null)
            {
                name += table + StorageUtils.DELIMITER;
            }
            if (field != null)
            {
                name += field + StorageUtils.DELIMITER;
            }
            Google.Apis.Storage.v1.Data.Object folder = new Google.Apis.Storage.v1.Data.Object();
            folder.Name   = name;
            folder.Bucket = Bucket;

            UploadObjectOptions options = new UploadObjectOptions();

            options.PredefinedAcl = PredefinedObjectAcl.PublicRead;

            using (var stream = new MemoryStream())
            {
                Client.UploadObject(folder, stream, options);
            }
        }
Esempio n. 29
0
 public GoogleObject UploadObject(string bucketName, string objectName, string contentType, MemoryStream source, UploadObjectOptions options)
 {
     return(_wrappedClient.UploadObject(bucketName, objectName, contentType, source, options, null));
 }
Esempio n. 30
0
        public static void mistorage()
        {
            StorageClient storageClient = StorageClient.Create();

            while (true)
            {
                listachk = VerificadorImagenes.validadorImage();
                if (listachk.Count() != 0)
                {
                    int compa = Convert.ToInt32(listachk[0].CMCIAID);
                    listadato = Obtiene.InfoStora(compa);
                    //string img64, int idActividad, int idRespuesta
                    using (SqlConnection con = new SqlConnection(Obtiene.connString))
                    {
                        con.Open();
                        using (DataClasses1DataContext dc = new TareaStoragePepsi.DataClasses1DataContext(con))
                        {
                            dc.SubmitChanges();
                            for (int i = 0; i <= (listachk.Count() - 1); i++)
                            {
                                Console.WriteLine(listachk[i].CLCHKID);
                                Random         rnd   = new Random();
                                int            tmp   = rnd.Next(1000);
                                DateTimeOffset now   = DateTimeOffset.Now;
                                string         route = Convert.ToString(listadato[0].IdFolder) + now.ToString("yyyy-MM") + "/";
                                route += string.Format("{0:00000}", Convert.ToString(listachk[i].CLCHKID)) + "/";
                                string fileName = route + string.Format("{0:000}", Convert.ToString(listachk[i].CMCIAID)) + "_" + string.Format("{0:000}", Convert.ToString(listachk[i].CLCHKID)) + "_" + string.Format("{0:000}", Convert.ToString(listachk[i].CLCHKPROID)) + "_" + string.Format("{0:000}", Convert.ToString(listachk[i].CLCHKACTID)) + "_" + string.Format("{0:000}", Convert.ToString(listachk[i].CLCHKIMGLIN)) + "_" + string.Format("{0:000}", tmp) + ".jpeg";
                                try
                                {
                                    var options = new UploadObjectOptions {
                                        PredefinedAcl = PredefinedObjectAcl.PublicRead
                                    };
                                    var      obj1 = storageClient.UploadObject(Convert.ToString(listadato[0].IdBucket), fileName, "image/jpeg", new MemoryStream(listachk[i].CLCHKIMGBLOB), options);
                                    CLCHKIMG ima  = dc.CLCHKIMG.FirstOrDefault(actu => actu.CMCIAID.Equals(listachk[i].CMCIAID) && actu.CLCHKID.Equals(listachk[i].CLCHKID) && actu.CLCHKPROID.Equals(listachk[i].CLCHKPROID) && actu.CLCHKACTID.Equals(listachk[i].CLCHKACTID) && actu.CLCHKIMGLIN.Equals(listachk[i].CLCHKIMGLIN));
                                    ima.CLCHKIMGSTORAGE = 1;
                                    try
                                    {
                                        CLCHKTAR tarea = dc.CLCHKTAR.FirstOrDefault(tar => tar.CMCIAID.Equals(listachk[i].CMCIAID) && tar.CLCHKID.Equals(listachk[i].CLCHKID) && tar.CLCHKPROID.Equals(listachk[i].CLCHKPROID) && tar.CLCHKACTID.Equals(listachk[i].CLCHKACTID) && tar.CLCHKTARLIN.Equals(listachk[i].CLCHKIMGLIN));
                                        tarea.CLCHKTARTXC = listadato[0].IdUrl + listadato[0].IdBucket + '/' + obj1.Name.ToString();
                                        dc.SubmitChanges();
                                    }
                                    catch (Exception)
                                    {
                                        Console.WriteLine("Los datos no coinciden en la tabla CLCHKTAR", listachk[i].CMCIAID + "-" + listachk[i].CLCHKID + "-" + listachk[i].CLCHKPROID + "-" + listachk[i].CLCHKACTID + "-" + listachk[i].CLCHKIMGLIN);
                                    }
                                    finally
                                    {
                                    }
                                }
                                catch (Google.GoogleApiException e)
                                {
                                    // The bucket already exists.  That's fine.
                                    // throw e;
                                }
                            }
                        }
                    }
                }
                else
                {
                    //liberar memoria
                    break;
                }
            }
        }