static void SaveObjectInAws(Stream pObject, string keyname)
        {
            try
            {
                using (var client = Amazon.AWSClientFactory.CreateAmazonS3Client())
                {
                    // simple object put
                    PutObjectRequest request = new PutObjectRequest();
                    request.WithBucketName(ConfigurationManager.AppSettings["bucketname"]).WithKey(keyname).WithInputStream(pObject);

                    using (client.PutObject(request)) { }
                }
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                if (amazonS3Exception.ErrorCode != null &&
                    (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") ||
                    amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                {
                    Console.WriteLine("Please check the provided AWS Credentials.");
                    Console.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3");
                    throw;
                }

                Console.WriteLine("An error occurred with the message '{0}' when writing an object", amazonS3Exception.Message);
                throw;
            }
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            using (AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client())
            {
                try
                {
                    NameValueCollection appConfig = ConfigurationManager.AppSettings;

                    // get file path
                    string folder = Path.GetFullPath(Environment.CurrentDirectory + "../../../../S3Uploader/");

                    // write uploader form to s3
                    const string uploaderTemplate = "uploader.html";
                    string file = Path.Combine(folder, "Templates/" + uploaderTemplate);

                    var request = new PutObjectRequest();
                    request.WithBucketName(appConfig["AWSBucket"])
                        .WithKey(appConfig["AWSUploaderPath"] + uploaderTemplate)
                        .WithInputStream(File.OpenRead(file));

                    request.CannedACL = S3CannedACL.PublicRead;
                    request.StorageClass = S3StorageClass.ReducedRedundancy;

                    S3Response response = client.PutObject(request);
                    response.Dispose();

                    // write js to s3
                    var jsFileNames = new[] { "jquery.fileupload.js", "jquery.iframe-transport.js", "s3_uploader.js" };
                    foreach (var jsFileName in jsFileNames)
                    {
                        file = Path.Combine(folder, "Scripts/s3_uploader/" + jsFileName);
                        request = new PutObjectRequest();

                        request.WithBucketName(appConfig["AWSBucket"])
                            .WithKey(appConfig["AWSUploaderPath"] + "js/" + jsFileName)
                            .WithInputStream(File.OpenRead(file));

                        request.CannedACL = S3CannedACL.PublicRead;
                        request.StorageClass = S3StorageClass.ReducedRedundancy;

                        response = client.PutObject(request);
                        response.Dispose();
                    }
                }
                catch (AmazonS3Exception amazonS3Exception)
                {
                    if (amazonS3Exception.ErrorCode != null &&
                        (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") ||
                        amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                    {
                        Console.WriteLine("Please check the provided AWS Credentials.");
                        Console.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3");
                    }
                    else
                    {
                        Console.WriteLine("An error occurred with the message '{0}' when writing an object", amazonS3Exception.Message);
                    }
                }
            }
        }
 /// <summary>
 /// Saves image to images.climbfind.com
 /// </summary>
 /// <param name="stream"></param>
 /// <param name="filePath"></param>
 /// <param name="key"></param>
 public override void SaveImage(Stream stream, string filePath, string key)
 {
     try
     {
         using (var client = Amazon.AWSClientFactory.CreateAmazonS3Client(Stgs.AWSAccessKey, Stgs.AWSSecretKey, S3Config))
         {
             // simple object put
             PutObjectRequest request = new PutObjectRequest();
             request.WithBucketName("images.climbfind.com" + filePath);
             request.WithInputStream(stream);
             request.ContentType = "image/jpeg";
             request.Key = key;
             request.WithCannedACL(S3CannedACL.PublicRead);
             client.PutObject(request);
         }
     }
     catch (AmazonS3Exception amazonS3Exception)
     {
         if (amazonS3Exception.ErrorCode != null &&
             (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") ||
             amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
         {
             Console.WriteLine("Please check the provided AWS Credentials.");
             Console.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3");
         }
         else
         {
             Console.WriteLine("An error occurred with the message '{0}' when writing an object", amazonS3Exception.Message);
         }
     }
 }
        public string PutImage(IWebCamImage webCamImage, out string key)
        {
            if (webCamImage.Data != null) // accept the file
            {
                // AWS credentials.
                const string accessKey = "{sensitive}";
                const string secretKey = "{sensitive}";

                // Setup the filename.
                string fileName = Guid.NewGuid() + ".jpg";
                string url = null;

                // Drop the image.
                AmazonS3 client;
                using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKey, secretKey))
                {
                    var request = new PutObjectRequest();
                    var config = ConfigurationManager.AppSettings;
                    request.WithBucketName(config["awsBucket"])
                        .WithCannedACL(S3CannedACL.PublicRead)
                        .WithKey(fileName).WithInputStream(new MemoryStream(webCamImage.Data));
                    S3Response response = client.PutObject(request);
                    url = config["awsRootUrl"] + "/" + config["awsBucket"] + "/" + fileName;
                }

                // Return our result.
                key = fileName;
                return url;
            }
            key = null;
            return null;
        }
Ejemplo n.º 5
0
 public static string CreateNewFolder(AmazonS3 client, string foldername)
 {
     String S3_KEY = foldername;
     PutObjectRequest request = new PutObjectRequest();
     request.WithBucketName(BUCKET_NAME);
     request.WithKey(S3_KEY);
     request.WithContentBody("");
     client.PutObject(request);
     return S3_KEY;
 }
        public void PutScreenshot(Amazon.S3.AmazonS3 amazonS3Client, string bucketName, string path, Stream stream)
        {
            var putObjectRequest = new PutObjectRequest();

            putObjectRequest.WithInputStream(stream);
            putObjectRequest.WithBucketName(bucketName);
            putObjectRequest.WithKey(path);

            amazonS3Client.PutObject(putObjectRequest);
        }
        public void CreateObject(string bucketName, Stream fileStream)
        {
            PutObjectRequest request = new PutObjectRequest();
            request.WithBucketName(bucketName);
            request.WithInputStream(fileStream);
            request.CannedACL = S3CannedACL.PublicRead;

            S3Response response = _client.PutObject(request);
            response.Dispose();
        }
Ejemplo n.º 8
0
 public static string CreateNewFileInFolder(AmazonS3 client, string foldername, string filepath)
 {
     String S3_KEY = foldername + "/" + System.IO.Path.GetFileName(filepath);
     PutObjectRequest request = new PutObjectRequest();
     request.WithBucketName(BUCKET_NAME);
     request.WithKey(S3_KEY);
     request.WithFilePath(filepath);
     //request.WithContentBody("This is body of S3 object.");
     client.PutObject(request);
     return S3_KEY;
 }
        public string CreateObject(string bucketName, Stream fileStream, string contentType, string objectKey)
        {
            PutObjectRequest request = new PutObjectRequest();
            request.WithBucketName(bucketName).WithContentType(contentType).WithKey(objectKey);
            request.WithInputStream(fileStream);
            request.CannedACL = S3CannedACL.PublicRead;

            S3Response response = _client.PutObject(request);
            response.Dispose();
            return response.RequestId;
        }
Ejemplo n.º 10
0
 /// <summary>
 /// The save file.
 /// </summary>
 /// <param name="awsAccessKey">
 /// The AWS access key.
 /// </param>
 /// <param name="awsSecretKey">
 /// The AWS secret key.
 /// </param>
 /// <param name="bucket">
 /// The bucket.
 /// </param>
 /// <param name="path">
 /// The path.
 /// </param>
 /// <param name="fileStream">
 /// The file stream.
 /// </param>
 public static void SaveFile(string awsAccessKey, string awsSecretKey, string bucket, string path, Stream fileStream)
 {
     using (var amazonClient = AWSClientFactory.CreateAmazonS3Client(awsAccessKey, awsSecretKey))
     {
         var createFileRequest = new PutObjectRequest
                                     {
                                         CannedACL = S3CannedACL.PublicRead,
                                         Timeout = int.MaxValue
                                     };
         createFileRequest.WithKey(path);
         createFileRequest.WithBucketName(bucket);
         createFileRequest.WithInputStream(fileStream);
         amazonClient.PutObject(createFileRequest);
     }
 }
Ejemplo n.º 11
0
        public string InsertObject(Stream stream, string keyName)
        {
            var putRequest = new PutObjectRequest();
            putRequest
            .WithBucketName(BucketName)
            .WithKey(keyName)
            .WithCannedACL(S3CannedACL.PublicRead)
            .WithInputStream(stream);

            using (AmazonS3 client = AWSClientFactory.CreateAmazonS3Client(AccessKeyId, SecretAccessKeyId))
            {
                S3Response putResponse = client.PutObject(putRequest);

                return string.Format("http://s3.amazonaws.com/{0}/{1}", BucketName, keyName);
            }
        }
Ejemplo n.º 12
0
        public static void WriteObjectRequest(string bucketName, string fileName, Stream fileContent, AmazonS3Client s3Client)
        {
            if (String.IsNullOrEmpty(fileName))
                {
                    return;
                }

                PutObjectRequest putObjectRequest = new PutObjectRequest();

                putObjectRequest.WithBucketName(bucketName)
                    .WithKey(fileName)
                    .WithStorageClass(S3StorageClass.Standard)
                    .WithCannedACL(S3CannedACL.PublicRead)
                    .WithInputStream(fileContent);

                S3Response response = s3Client.PutObject(putObjectRequest);
                response.Dispose();
        }
Ejemplo n.º 13
0
         public bool UploadFileToS3Object(string s3ObjectName, string filePath)
         {

             try
             {
                 PutObjectRequest request = new PutObjectRequest();
                 request.WithBucketName(bucketName);
                 request.WithKey(s3ObjectName);
                 request.WithFilePath(filePath);//request.WithContentBody
                 amazonS3Client.PutObject(request);
                 return true;
             }
             catch (Exception e)
             {
                 structuredLog("E", "Exception in UploadFileToS3Object: "+e);
                 return false;
             }

         }
Ejemplo n.º 14
0
        public StorageEntry AddEntry(StorageEntry entry)
        {
            // 本体作成
            using (var stream = new MemoryStream(entry.Contents))
            {
                var request = new PutObjectRequest { InputStream = stream };
                request.WithBucketName(BucketName)
                       .WithKey(entry.Name)
                       .WithContentType(entry.ContentType);

                using (var s3 = GetAmazonS3())
                {
                    var response = s3.PutObject(request);
                    response.Dispose();
                }
            }

            return entry;
        }
Ejemplo n.º 15
0
        private void UploadEvents(LoggingEvent[] events, AmazonS3 client)
        {
            var key = Filename(Guid.NewGuid().ToString());

            var content = new StringBuilder(events.Count());
            Array.ForEach(events, logEvent =>
                {
                    using (var writer = new StringWriter())
                    {
                        Layout.Format(writer, logEvent);
                        content.AppendLine(writer.ToString());
                    }
                });

            var request = new PutObjectRequest();
            request.WithBucketName(_bucketName);
            request.WithKey(key);
            request.WithContentBody(content.ToString());
            client.PutObject(request);
        }
Ejemplo n.º 16
0
        private static void ResizeAndUpload(Stream aStream, AmazonS3 anS3Client, string aBucketName, string aNewImageName, int aSize)
        {
            Image myOriginal = Image.FromStream(aStream);
            Image myActual = ScaleBySize(myOriginal, aSize);

            MemoryStream myMemoryStream = imageToMemoryStream(myActual);

            PutObjectRequest myRequest = new PutObjectRequest();

            myRequest.WithBucketName(aBucketName)
                .WithCannedACL(S3CannedACL.PublicRead)
                .WithKey(aNewImageName)
                .InputStream = myMemoryStream;

            S3Response myResponse = anS3Client.PutObject(myRequest);

            myActual.Dispose();
            myMemoryStream.Dispose();
            myOriginal.Dispose();
        }
Ejemplo n.º 17
0
        protected void Add(string bucketName, Guid id, object newItem)
        {
            string serializedUser = JsonConvert.SerializeObject(newItem);
            byte[] byteStream = Encoding.UTF8.GetBytes(serializedUser);

            var metadata = new NameValueCollection();
            metadata.Add(IdKey, id.ToString());
            metadata.Add(SizeKey, byteStream.Length.ToString());
            metadata.Add(CreationTimeKey, DateTime.UtcNow.ToString());
            metadata.Add(LastWriteTimeKey, DateTime.UtcNow.ToString());

            var stream = new MemoryStream();
            stream.Write(byteStream, 0, byteStream.Length);

            var req = new PutObjectRequest();
            req.WithInputStream(stream);

            using (AmazonS3Client client = SetupClient())
            {
                client.PutObject(req.WithBucketName(bucketName).WithKey(id.ToString()).WithMetaData(metadata));
            }
        }
        string UploadToAmazon(string fileName, Stream fileStream)
        {
            try
            {
                string uniqueKeyItemName = string.Format("{0}-{1}", keyName, fileName);
                PutObjectRequest request = new PutObjectRequest();
                request.WithInputStream(fileStream);
                request.WithBucketName(bucketName)
                    .WithKey(uniqueKeyItemName);
                request.WithMetaData("title", fileName);
                // Add a header to the request.
                //request.AddHeaders(AmazonS3Util.CreateHeaderEntry ("ContentType", contentType));

                S3CannedACL anonPolicy = S3CannedACL.PublicRead;
                request.WithCannedACL(anonPolicy);
                S3Response response = client.PutObject(request);

               //GetPreSignedUrlRequest publicUrlRequest = new GetPreSignedUrlRequest().WithBucketName(bucketName).WithKey( uniqueKeyItemName ).WithExpires(DateTime.Now.AddMonths(3) );
                //var urlResponse = client.GetPreSignedURL(publicUrlRequest);
                response.Dispose();
                var urlResponse = string.Format("https://s3.amazonaws.com/{0}/{1}", bucketName, uniqueKeyItemName );
                return urlResponse;
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                if (amazonS3Exception.ErrorCode != null &&
                    (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
                    ||
                    amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                {
                    throw new Exception("Error - Invalid Credentials - please check the provided AWS Credentials", amazonS3Exception);
                }
                else
                {
                    throw new Exception(String.Format("Error occured when uploading media: {0}",amazonS3Exception.Message),amazonS3Exception);
                }
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Saves an HTTP POSTed file
        /// </summary>
        /// <param name="localFile">HTTP POSTed file</param>
        /// <param name="path">Web path to file's folder</param>
        /// <param name="fileName">File name</param>
        public void SaveFile(string localFile, string path, string fileName)
        {
            // Check if the local file exsit
            if (!File.Exists(localFile))
            {
                return;
            }

            // Prepare put request
            var request = new PutObjectRequest();

            request.WithBucketName(_bucketName)
                .WithCannedACL(S3CannedACL.PublicRead)
                .WithFilePath(localFile)
                .WithKey(GetKey(path, fileName))
                .WithTimeout(-1);

            // Put file
            try
            {
                var response = _client.PutObject(request);
                response.Dispose();
            }
            catch (Exception ex)
            {
                LogHelper.Error<AmazonS3FileSystem>(ex.Message, ex);
            }
        }
Ejemplo n.º 20
0
		private void UploadToS3(string backupPath, PeriodicBackupSetup localBackupConfigs)
		{
			var awsRegion = RegionEndpoint.GetBySystemName(localBackupConfigs.AwsRegionEndpoint) ?? RegionEndpoint.USEast1;

			using (var client = new Amazon.S3.AmazonS3Client(awsAccessKey, awsSecretKey, awsRegion))
			using (var fileStream = File.OpenRead(backupPath))
			{
				var key = Path.GetFileName(backupPath);
				var request = new PutObjectRequest();
				request.WithMetaData("Description", GetArchiveDescription());
				request.WithInputStream(fileStream);
				request.WithBucketName(localBackupConfigs.S3BucketName);
				request.WithKey(key);

				using (client.PutObject(request))
				{
					logger.Info(string.Format("Successfully uploaded backup {0} to S3 bucket {1}, with key {2}",
											  Path.GetFileName(backupPath), localBackupConfigs.S3BucketName, key));
				}
			}
		}
Ejemplo n.º 21
0
        private static void UploadFile(string filePath, string key, string bucket)
        {
            string AWSAccessKey = ConfigurationManager.AppSettings["AWSAccessKey"];
            string AWSSecretKey = ConfigurationManager.AppSettings["AWSSecretKey"];

            using (AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(AWSAccessKey, AWSSecretKey))
            {
                PutObjectRequest request = new PutObjectRequest();
                request.WithBucketName(bucket);
                request.WithKey(key);
                request.WithFilePath(filePath);
                request.CannedACL = S3CannedACL.PublicRead;

                client.PutObject(request);
            }
        }
Ejemplo n.º 22
0
        public void UploadObject(UploadRequest request)
        {
            CheckUri(request.Uri);

            try
            {
                var putRequest = new PutObjectRequest();
                using (var client = CreateAmazonS3Client())
                {
                    var absolutePath = HttpUtility.UrlDecode(request.Uri.AbsolutePath);
                    var key = absolutePath.TrimStart(Convert.ToChar("/"));

                    putRequest.WithBucketName(bucketName)
                        .WithKey(key)
                        .WithInputStream(request.InputStream);

                    if (accessControlEnabledGlobally && !request.IgnoreAccessControl)
                    {
                        putRequest.WithCannedACL(S3CannedACL.Private);
                    }
                    else
                    {
                        putRequest.WithCannedACL(S3CannedACL.PublicRead);
                    }

                    if (request.Headers != null && request.Headers.Count > 0)
                    {
                        putRequest.AddHeaders(request.Headers);
                    }

                    if (request.MetaData != null && request.MetaData.Count > 0)
                    {
                        putRequest.WithMetaData(request.MetaData);
                    }

                    putRequest.ContentType = MimeTypeUtility.DetermineContentType(request.Uri);

                    using (client.PutObject(putRequest))
                    {
                    }
                }
            }
            catch (Exception e)
            {
                throw new StorageException(string.Format("Failed to upload object with request {0}.", request), e);
            }
        }
		private void DoUpload(string backupPath, PeriodicBackupSetup backupConfigs)
		{
			var AWSRegion = RegionEndpoint.GetBySystemName(backupConfigs.AwsRegionEndpoint) ?? RegionEndpoint.USEast1;

			var desc = string.Format("Raven.Database.Backup {0} {1}", Database.Name,
			                     DateTimeOffset.UtcNow.ToString("u"));

			if (!string.IsNullOrWhiteSpace(backupConfigs.GlacierVaultName))
			{
				var manager = new ArchiveTransferManager(awsAccessKey, awsSecretKey, AWSRegion);
				var archiveId = manager.Upload(backupConfigs.GlacierVaultName, desc, backupPath).ArchiveId;
				logger.Info(string.Format("Successfully uploaded backup {0} to Glacier, archive ID: {1}", Path.GetFileName(backupPath),
										  archiveId));
				return;
			}

			if (!string.IsNullOrWhiteSpace(backupConfigs.S3BucketName))
			{
				var client = new Amazon.S3.AmazonS3Client(awsAccessKey, awsSecretKey, AWSRegion);

				using (var fileStream = File.OpenRead(backupPath))
				{
					var key = Path.GetFileName(backupPath);
					var request = new PutObjectRequest();
					request.WithMetaData("Description", desc);
					request.WithInputStream(fileStream);
					request.WithBucketName(backupConfigs.S3BucketName);
					request.WithKey(key);

					using (S3Response _ = client.PutObject(request))
					{
						logger.Info(string.Format("Successfully uploaded backup {0} to S3 bucket {1}, with key {2}",
							Path.GetFileName(backupPath), backupConfigs.S3BucketName, key));
						return;
					}
				}
			}
		}
Ejemplo n.º 24
0
        public void Upload(string fileName, Stream stream)
        {
            var request = new PutObjectRequest();
            request.WithBucketName(this._bucketName).WithKey(fileName).WithInputStream(stream);
            request.CannedACL = S3CannedACL.PublicRead;
            request.StorageClass = S3StorageClass.ReducedRedundancy;
            request.Timeout = 1080000;
            S3Response response = this._client.PutObject(request);

            response.Dispose();
        }
Ejemplo n.º 25
0
        public static bool UploadFile(byte[] file, string name)
        {
            try
            {
                PutObjectRequest request = new PutObjectRequest();
                request.WithBucketName(BucketName)
                    .WithKey(name)
                    .WithCannedACL(S3CannedACL.PublicRead)
                    .WithInputStream(new MemoryStream(file))
                    .AddHeader("Expires", DateTime.Now.AddYears(1).ToString("R"));

                AmazonS3Config config = new AmazonS3Config();
                config.CommunicationProtocol = Protocol.HTTP;

                using (AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(AccessKeyID, SecretAccessKeyID, config))
                using (S3Response response = client.PutObject(request))
                {
                    if (response != null)
                        return true;
                    else
                        return false;
                }
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
            #if(DEBUG)
                if (amazonS3Exception.ErrorCode != null &&
                    (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") ||
                    amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                {
                    Console.WriteLine("Please check the provided AWS Credentials.");
                    Console.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3");
                }
                else
                {
                    Console.WriteLine("An error occurred with the message '{0}' when writing an object", amazonS3Exception.Message);
                }
            #endif
                return false;
            }
            catch (Exception e)
            {
                return false;
            }
        }
Ejemplo n.º 26
0
        public ActionResult Index(HttpPostedFileBase file)
        {
            if (file.ContentLength > 0)
            {
                using (AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(AWSAccessKey, AWSSecretKey))
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var t = (DateTime.UtcNow - new DateTime(1970, 1, 1));

                    var key = string.Format("{0}{1}-{2}", AWSFolder, (int)t.TotalSeconds, fileName);

                    var request = new PutObjectRequest();

                    request.WithBucketName(AWSBucket)
                           .WithCannedACL(S3CannedACL.PublicRead)
                           .WithKey(key).InputStream = file.InputStream;

                    using (PutObjectResponse response = client.PutObject(request)) { }
                }
            }

            return RedirectToAction("Index");
        }
Ejemplo n.º 27
0
        private static void UploadFile(string mediaBucket, FileInfo file, string mediaFolder)
        {
            try {
                // simple object put
                PutObjectRequest request = new PutObjectRequest();
                request.WithBucketName(mediaBucket)
                    .WithFilePath(file.FullName)
                    .WithKey(GetAwsKey(file, mediaFolder))
                    .WithStorageClass(S3StorageClass.ReducedRedundancy);
            //					.WithGenerateChecksum(true);

                using (var response = client.PutObject(request)) {
                    // request.MD5Digest == response.

                }

            }
            catch (AmazonS3Exception amazonS3Exception) {
                if (amazonS3Exception.ErrorCode != null &&
                    (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") ||
                    amazonS3Exception.ErrorCode.Equals("InvalidSecurity"))) {
                    Console.WriteLine("Please check the provided AWS Credentials.");
                    Console.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3");
                } else {
                    Console.WriteLine("An error occurred with the message '{0}' when writing an object", amazonS3Exception.Message);
                }
            }
            catch (Exception ex) {

                Console.WriteLine("An error occurred with the message '{0}' when writing an object", ex.Message);

            }
        }
Ejemplo n.º 28
0
        public static void ACLSerial(String filePath)
        {
            System.Console.WriteLine("\nhello,ACL!!");
            NameValueCollection appConfig = ConfigurationManager.AppSettings;

            AmazonS3 s3Client = AWSClientFactory.CreateAmazonS3Client(appConfig["AWSAccessKey"], appConfig["AWSSecretKey"]);
            String bucketName = "chutest";
            String objectName = "hello";
            //versioning test
            String vbucketName = "netversion";

            //**********************************************************************************************************************************************************
            // Set Version test 環境,目前新增一專用 bucket = netversion,內有兩筆 Object 資訊(Object 已刪除,帶有 delete marker),為了測試方便,此環境不共用也不刪除
            // 若於佈板後刪除環境,請預先建立環境,執行132~150行程式
            //**********************************************************************************************************************************************************

            //PutBucket
            /*    System.Console.WriteLine("PutBucket-version: {0}\n", vbucketName);
                s3Client.PutBucket(new PutBucketRequest().WithBucketName(vbucketName));

                //PutBucketVersioning
                SetBucketVersioningResponse putVersioningResult = s3Client.SetBucketVersioning(new SetBucketVersioningRequest().WithBucketName(vbucketName).WithVersioningConfig(new S3BucketVersioningConfig().WithStatus("Enabled")));
                System.Console.WriteLine("PutBucketVersioning, requestID:{0}\n", putVersioningResult.RequestId);

                //PutObject
                System.Console.WriteLine("PutObject!");
                PutObjectRequest objectVersionRequest = new PutObjectRequest();
                objectVersionRequest.WithBucketName(vbucketName);
                objectVersionRequest.WithKey(objectName);
                objectVersionRequest.WithFilePath(filePath);
                PutObjectResponse objectVersionResult = s3Client.PutObject(objectVersionRequest);
                System.Console.WriteLine("Uploaded Object Etag: {0}\n", objectVersionResult.ETag);

                //DeleteObject
                System.Console.WriteLine("Delete Object!");
                s3Client.DeleteObject(new DeleteObjectRequest().WithBucketName(vbucketName).WithKey(objectName));
            */

            //PutBucket
            System.Console.WriteLine("PutBucket: {0}\n", bucketName);
            s3Client.PutBucket(new PutBucketRequest().WithBucketName(bucketName));

            //PutObject
            System.Console.WriteLine("PutObject!");
            PutObjectRequest request = new PutObjectRequest();
            request.WithBucketName(bucketName);
            request.WithKey(objectName);
            request.WithFilePath(filePath);
            PutObjectResponse PutResult = s3Client.PutObject(request);
            System.Console.WriteLine("Uploaded Object Etag: {0}\n", PutResult.ETag);

            //PutBucketACL
            SetACLRequest aclRequest = new SetACLRequest();
            S3AccessControlList aclConfig = new S3AccessControlList();
            aclConfig.WithOwner(new Owner().WithDisplayName("hrchu").WithId("canonicalidhrchu"));
            aclConfig.WithGrants(new S3Grant().WithGrantee(new S3Grantee().WithCanonicalUser("canonicalidhrchu","hrchu")).WithPermission(S3Permission.FULL_CONTROL));
            aclConfig.WithGrants(new S3Grant().WithGrantee(new S3Grantee().WithCanonicalUser("canonicalidannyren", "annyren")).WithPermission(S3Permission.READ_ACP));

            aclRequest.WithBucketName(bucketName);
            aclRequest.WithACL(aclConfig);

            SetACLResponse putBucketACLResult = s3Client.SetACL(aclRequest);
            System.Console.WriteLine("\nPutBucketACL, requestID:{0}",putBucketACLResult.RequestId);

            //GetBucketACL
            GetACLResponse getBucketACLResult = s3Client.GetACL(new GetACLRequest().WithBucketName(bucketName));
            System.Console.WriteLine("\nGetBucketACL Result:\n{0}\n",getBucketACLResult.ResponseXml);

            //**********************************************************************************************************************************************************

            //PutBucketACL (cannedacl)
            SetACLRequest cannedaclRequest = new SetACLRequest();
            cannedaclRequest.WithBucketName(bucketName);
            cannedaclRequest.WithCannedACL(S3CannedACL.PublicRead);

            SetACLResponse putBucketCannedACLResult = s3Client.SetACL(cannedaclRequest);
            System.Console.WriteLine("\nPutBucketCannedACL, requestID:{0}", putBucketCannedACLResult.RequestId);

            //GetBucketACL
            GetACLResponse getBucketCannedACLResult = s3Client.GetACL(new GetACLRequest().WithBucketName(bucketName));
            System.Console.WriteLine("\nGetBucketCannedACL Result:\n{0}\n", getBucketCannedACLResult.ResponseXml);

            //**********************************************************************************************************************************************************

            //PutObjectACL
            SetACLRequest objectACLRequest = new SetACLRequest();
            S3AccessControlList objectACLConfig = new S3AccessControlList();
            objectACLConfig.WithOwner(new Owner().WithDisplayName("hrchu").WithId("canonicalidhrchu"));
            objectACLConfig.WithGrants(new S3Grant().WithGrantee(new S3Grantee().WithCanonicalUser("canonicalidhrchu", "hrchu")).WithPermission(S3Permission.FULL_CONTROL));
            objectACLConfig.WithGrants(new S3Grant().WithGrantee(new S3Grantee().WithCanonicalUser("canonicalidannyren", "annyren")).WithPermission(S3Permission.WRITE_ACP));

            objectACLRequest.WithBucketName(bucketName);
            objectACLRequest.WithKey(objectName);
            objectACLRequest.WithACL(objectACLConfig);

            SetACLResponse putObjectACLResult = s3Client.SetACL(objectACLRequest);
            System.Console.WriteLine("\nPutObjectACL, requestID:{0}", putObjectACLResult.RequestId);

            //GetObjectACl
            GetACLResponse getObjectACLResult = s3Client.GetACL(new GetACLRequest().WithBucketName(bucketName).WithKey(objectName));
            System.Console.WriteLine("\nGetObjectACL Result:\n{0}\n", getObjectACLResult.ResponseXml);

            //**********************************************************************************************************************************************************

            //PutObjectACL (cannedacl)
            SetACLRequest objectCannedACLRequest = new SetACLRequest();

            objectCannedACLRequest.WithBucketName(bucketName);
            objectCannedACLRequest.WithKey(objectName);
            objectCannedACLRequest.WithCannedACL(S3CannedACL.PublicRead);

            SetACLResponse putObjectCannedACLResult = s3Client.SetACL(objectCannedACLRequest);
            System.Console.WriteLine("\nPutObjectCannedACL, requestID:{0}", putObjectCannedACLResult.RequestId);

            //GetObjectACl
            GetACLResponse getObjectCannedACLResult = s3Client.GetACL(new GetACLRequest().WithBucketName(bucketName).WithKey(objectName));
            System.Console.WriteLine("\nGetObjectCannedACL Result:\n{0}\n", getObjectCannedACLResult.ResponseXml);

            //**********************************************************************************************************************************************************

            //DeleteObject
            System.Console.WriteLine("Delete Object!");
            s3Client.DeleteObject(new DeleteObjectRequest().WithBucketName(bucketName).WithKey(objectName));
            //DeleteBucket
            System.Console.WriteLine("Delete Bucket!");
            s3Client.DeleteBucket(new DeleteBucketRequest().WithBucketName(bucketName));

            //PutObjectACL-version test*********************************************************************************************************************************
            String versionid = "784cca47e2a7423f97dedde6a72f9b3d";

            //PutObjectACL-versionid
              SetACLRequest objectVersionACLRequest = new SetACLRequest();
              S3AccessControlList objectVersionACLConfig = new S3AccessControlList();
              objectVersionACLConfig.WithOwner(new Owner().WithDisplayName("hrchu").WithId("canonicalidhrchu"));
              objectVersionACLConfig.WithGrants(new S3Grant().WithGrantee(new S3Grantee().WithCanonicalUser("canonicalidhrchu", "hrchu")).WithPermission(S3Permission.FULL_CONTROL));
              objectVersionACLConfig.WithGrants(new S3Grant().WithGrantee(new S3Grantee().WithCanonicalUser("canonicalidannyren", "annyren")).WithPermission(S3Permission.WRITE_ACP));

              objectVersionACLRequest.WithBucketName(vbucketName);
              objectVersionACLRequest.WithKey(objectName);
              objectVersionACLRequest.WithVersionId(versionid);
              objectVersionACLRequest.WithACL(objectVersionACLConfig);

              SetACLResponse putObjectVersionACLResult = s3Client.SetACL(objectVersionACLRequest);
              System.Console.WriteLine("\nPutObjectACL Version, requestID:{0}", putObjectVersionACLResult.RequestId);

              //GetObjectACl-versionid
              GetACLResponse getObjectVersionACLResult = s3Client.GetACL(new GetACLRequest().WithBucketName(vbucketName).WithKey(objectName).WithVersionId(versionid));
              System.Console.WriteLine("\nGetObjectACL Version Result:\n{0}\n", getObjectVersionACLResult.ResponseXml);

              //PutObjectACL (cannedacl)-versionid
              SetACLRequest objectVersionCannedACLRequest = new SetACLRequest();

              objectVersionCannedACLRequest.WithBucketName(vbucketName);
              objectVersionCannedACLRequest.WithKey(objectName);
              objectVersionCannedACLRequest.WithVersionId(versionid);
              objectVersionCannedACLRequest.WithCannedACL(S3CannedACL.PublicRead);

              SetACLResponse putObjectVersionCannedACLResult = s3Client.SetACL(objectVersionCannedACLRequest);
              System.Console.WriteLine("\nPutObjectCannedACL Version, requestID:{0}", putObjectVersionCannedACLResult.RequestId);

              //GetObjectACl(cannedacl)-versionid
              GetACLResponse getObjectVersionCannedACLResult = s3Client.GetACL(new GetACLRequest().WithBucketName(vbucketName).WithKey(objectName).WithVersionId(versionid));
              System.Console.WriteLine("\nGetObjectCannedACL Version Result:\n{0}\n", getObjectVersionCannedACLResult.ResponseXml);

            System.Console.WriteLine("END!");
        }
        private static string SaveHtml(string p)
        {
            string folder = Convert.ToString(Guid.NewGuid());
            string bucketName = Settings.Default.BucketName + "/" + Settings.Default.KenyaVideo + "/" + folder;
            PutObjectRequest putObjectNewsItem = new PutObjectRequest();
            putObjectNewsItem.WithBucketName(bucketName);
            putObjectNewsItem.CannedACL = S3CannedACL.PublicRead;
            putObjectNewsItem.Key = Convert.ToString(Guid.NewGuid());
            putObjectNewsItem.ContentType = "text/html";
            putObjectNewsItem.ContentBody = p;

            using (S3Response response = s3Client.PutObject(putObjectNewsItem))
            {
                WebHeaderCollection headers = response.Headers;
                foreach (string key in headers.Keys)
                {
                    //log headers ("Response Header: {0}, Value: {1}", key, headers.Get(key));
                }
            }
            return "https://" + Settings.Default.BucketName + ".s3.amazonaws.com " + "/" + Settings.Default.KenyaVideo + "/" + folder;
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Writes byte array data into an S3 Bucket
        /// </summary>
        /// <param name="data">The byte array data to write to the bucket.</param>
        /// <param name="location">The location as to where you want to save the data</param>
        /// <param name="guid">The guid of the content you're uploading</param>
        public void WriteObject(byte[] data, StorageLocations location, string guid)
        {
            // Do upload
            var stream = new MemoryStream(data);
            var keyName = string.Format("{0}/{1}.onx", StorageLocationToString(location), guid);
            var request = new PutObjectRequest();
            request.WithBucketName(Bucket).WithKey(keyName).WithInputStream(stream);

            // Response
            S3Response response = _client.PutObject(request);
            response.Dispose();
            stream.Dispose();
        }