Exemple #1
0
        //checks if file exists S3 cloud
        public static bool IsObjectExistS3(string filePath)
        {
            AmazonS3 client;

            if (CheckS3Credentials())
            {
                NameValueCollection appConfig =
                    ConfigurationManager.AppSettings;

                string accessKeyID       = appConfig["AWSAccessKey"];
                string secretAccessKeyID = appConfig["AWSSecretKey"];

                using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(
                           accessKeyID, secretAccessKeyID, RegionEndpoint.USWest1))
                {
                    try
                    {
                        S3Response response = client.GetObjectMetadata(new GetObjectMetadataRequest()
                                                                       .WithBucketName(Constants.AmazonS3BucketName)
                                                                       .WithKey(filePath));

                        return(true);
                    }
                    catch (Amazon.S3.AmazonS3Exception ex)
                    {
                        if (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
                        {
                            return(false);
                        }
                    }
                }
            }

            return(false);
        }
Exemple #2
0
        public void SaveFile(string folderName, string fileName, Stream fileStream)
        {
            //folder ignored - packages stored on top level of S3 bucket
            if (String.IsNullOrWhiteSpace(folderName))
            {
                throw new ArgumentNullException("folderName");
            }
            if (String.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentNullException("fileName");
            }
            if (fileStream == null)
            {
                throw new ArgumentNullException("fileStream");
            }

            var request = new PutObjectRequest();

            request.WithBucketName(clientContext.BucketName);
            request.WithKey(fileName);
            request.WithInputStream(fileStream);
            request.AutoCloseStream = true;
            request.CannedACL       = S3CannedACL.PublicRead;
            request.WithTimeout((int)TimeSpan.FromMinutes(30).TotalMilliseconds);

            using (AmazonS3 client = clientContext.CreateInstance())
            {
                S3Response response = WrapRequestInErrorHandler(() => client.PutObject(request));
            }
        }
Exemple #3
0
        public async Task <S3Response> CreateBucketAsync(string name)
        {
            try
            {
                S3Response Response = null;
                if (await AmazonS3Util.DoesS3BucketExistV2Async(_client, name) == false)
                {
                    var bucketrequest = new PutBucketRequest
                    {
                        BucketName      = name,
                        UseClientRegion = true
                    };
                    var bucketresponse = await _client.PutBucketAsync(bucketrequest);

                    Response = new S3Response {
                        Message = bucketresponse.ResponseMetadata.RequestId, status = bucketresponse.HttpStatusCode
                    };
                }
                return(Response);
            }
            catch (AmazonS3Exception e1)
            {
                return(new S3Response {
                    Message = e1.Message, status = e1.StatusCode
                });
                //Console.WriteLine(e1.StatusCode+"--"+e1.Message);
            }
            catch (Exception e1)
            {
                return(new S3Response {
                    Message = e1.Message, status = HttpStatusCode.InternalServerError
                });
                //Console.WriteLine(e1.StatusCode+"--"+e1.Message);
            }
        }
Exemple #4
0
        public async Task <S3Response> DeleteEntityAsync(string folderUrl)
        {
            var s3Response = new S3Response();

            try
            {
                var deleteObjectRequest = new DeleteObjectRequest
                {
                    BucketName = _bucketName,
                    Key        = folderUrl
                };

                Console.WriteLine("Deleting an object");
                await _s3Client.DeleteObjectAsync(deleteObjectRequest);
            }
            catch (AmazonS3Exception e)
            {
                s3Response.Message = e.Message;
                Console.WriteLine("Error encountered on server. Message:'{0}' when deleting an object", e.Message);
            }
            catch (Exception e)
            {
                s3Response.Message = e.Message;
                Console.WriteLine("Unknown encountered on server. Message:'{0}' when deleting an object", e.Message);
            }

            s3Response.StatusCode = System.Net.HttpStatusCode.InternalServerError;
            return(s3Response);
        }
Exemple #5
0
 public void UploadFile(string bucketName, Stream uploadFileStream, string remoteFileName)
 {
     using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKeyID, secretAccessKeyID, config))
     {
         try
         {
             PutObjectRequest request = new PutObjectRequest();
             request.WithBucketName(bucketName)
             .WithCannedACL(S3CannedACL.PublicRead)
             .WithKey(remoteFileName)
             .WithInputStream(uploadFileStream);
             using (S3Response response = client.PutObject(request))
             {
                 WebHeaderCollection headers = response.Headers;
                 foreach (string key in headers.Keys)
                 {
                     //log headers ("Response Header: {0}, Value: {1}", key, headers.Get(key));
                 }
             }
         }
         catch (AmazonS3Exception amazonS3Exception)
         {
             if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
             {
                 //log exception - ("Please check the provided AWS Credentials.");
             }
             else
             {
                 //log exception -("An error occurred with the message '{0}' when writing an object", amazonS3Exception.Message);
             }
         }
     }
 }
Exemple #6
0
        public static Job DeserializeFromS3(string bucket, string state_id, string aws_id, string aws_secret)
        {
            Job j;

            // download Job from S3
            using (AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(aws_id, aws_secret))
            {
                GetObjectRequest getObjectRequest = new GetObjectRequest()
                {
                    BucketName = bucket,
                    Key        = "state_" + state_id
                };

                using (S3Response getObjectResponse = client.GetObject(getObjectRequest))
                {
                    using (Stream s = getObjectResponse.ResponseStream)
                    {
                        // deserialize
                        IFormatter formatter = new BinaryFormatter();
                        j = (Job)formatter.Deserialize(s);
                    }
                }
            }
            return(j);
        }
        public static bool WriteLogFile(string uploadFilePath, string credentialFilePath)
        {
            Type t = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType;

            LogEvents.S3UploadStarted(t, uploadFilePath);
            try
            {
                if (ReadS3Credentials(credentialFilePath) == false)
                {
                    LogEvents.S3NoCredentials(t);
                    return(false);
                }
                AmazonS3         client   = Amazon.AWSClientFactory.CreateAmazonS3Client(_accessKeyId, _secretAccessKey);
                PutObjectRequest request  = new PutObjectRequest();
                string           fileName = System.IO.Path.GetFileName(uploadFilePath);
                request.WithFilePath(uploadFilePath).WithBucketName(_bucketName).WithKey(fileName);
                S3Response responseWithMetadata = client.PutObject(request);
                return(true);
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                LogEvents.S3Error(t, amazonS3Exception);
                return(false);
            }
        }
        private FileInfo DownloadFile(PublishRequest publishRequest)
        {
            var bucketName = publishRequest.BucketName;
            var config     = Globals.Settings.Proxy.UseProxy
                ? new AmazonS3Config
            {
                ProxyHost = Globals.Settings.Proxy.Host,
                ProxyPort = int.Parse(Globals.Settings.Proxy.Port)
            }
                : new AmazonS3Config();


            var key  = publishRequest.Filename.TrimStart(new[] { '/' });
            var temp = Path.GetTempFileName();

            using (var client = new AmazonS3Client(publishRequest.AccessKey, publishRequest.SecretKey, config))
            {
                var getObjectRequest = new GetObjectRequest().WithBucketName(bucketName).WithKey(key);

                using (S3Response getObjectResponse = client.GetObject(getObjectRequest))
                    using (var fs = new FileStream(temp, FileMode.OpenOrCreate))
                        using (var s = getObjectResponse.ResponseStream)
                        {
                            s.CopyTo(fs);
                        }
            }

            return(RenameFile(new FileInfo(temp), key));
        }
        public void save_file(string folderName, string fileName, Stream fileStream)
        {
            // It's allowed to have an empty folder name.
            // if (String.IsNullOrWhiteSpace(folderName)) throw new ArgumentNullException("folderName");
            if (String.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentNullException("fileName");
            }
            if (fileStream == null)
            {
                throw new ArgumentNullException("fileStream");
            }

            folderName = (string.IsNullOrEmpty(folderName) ? String.Empty : folderName.Substring(folderName.Length - 1, 1) == "/" ? folderName : folderName + "/");
            fileName   = string.Format("{0}{1}", folderName, fileName);

            var request = new PutObjectRequest();

            request.WithBucketName(clientContext.BucketName);
            request.WithKey(fileName);
            request.WithInputStream(fileStream);
            request.AutoCloseStream = true;
            request.CannedACL       = S3CannedACL.PublicRead;
            request.WithTimeout((int)TimeSpan.FromMinutes(30).TotalMilliseconds);

            using (AmazonS3 client = clientContext.create_instance())
            {
                S3Response response = wrap_request_in_error_handler(() => client.PutObject(request));
            }
        }
    /*function geoTest() {
     * alert(google.loader.ClientLocation);
     * if (google.loader.ClientLocation) {
     *  var latitude = google.loader.ClientLocation.latitude;
     *  var longitude = google.loader.ClientLocation.longitude;
     *  var city = google.loader.ClientLocation.address.city;
     *  var country = google.loader.ClientLocation.address.country;
     *  var country_code = google.loader.ClientLocation.address.country_code;
     *  var region = google.loader.ClientLocation.address.region;
     *
     *  document.getElementById('<%=locationText.ClientID%>').innerHTML = city;
     * }
     * }
     * geoTest();*/

//        <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCDLnmGm_kFXPikv3hzOjYTVYNcqGQnsF&language=zh&callback=initMap">
//</script>
//<script type="text/javascript" src="http://www.google.com/jsapi"></script>
//<script>
//        google.load("language", "zh");
//    </script>

    private void UploadImageS3(string fileName, MemoryStream fileStream)
    {
        try
        {
            AmazonS3       client;
            AmazonS3Config config = new AmazonS3Config().WithCommunicationProtocol(Protocol.HTTP);
            using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKey, secretKey, config))
            {
                PutObjectRequest request = new PutObjectRequest();
                request.WithBucketName("traffiti");
                request.WithCannedACL(S3CannedACL.PublicRead);
                request.WithKey(fileName).InputStream = fileStream;
                request.AddHeaders(Amazon.S3.Util.AmazonS3Util.CreateHeaderEntry("Cache-Control", "max-age=31536000"));

                S3Response response = client.PutObject(request);
            }
        }
        catch (AmazonS3Exception amazonS3Exception)
        {
            if (amazonS3Exception.ErrorCode != null &&
                (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
                 ||
                 amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
            {
                Console.WriteLine("Check the provided AWS Credentials.");
                Console.WriteLine("For service sign up go to http://aws.amazon.com/s3");
            }
            else
            {
                Console.WriteLine(
                    "Error occurred. Message:'{0}' when writing an object"
                    , amazonS3Exception.Message);
            }
        }
    }
Exemple #11
0
        public async Task <S3Response> UploadProfileImage(string bucketName, FileUpload fileUpload)
        {
            Guid g;

            g = Guid.NewGuid();
            var response = new S3Response();
            var image    = fileUpload.FormFile;

            if (image.ContentType != "image/jpg" && image.ContentType != "image/png" && image.ContentType != "image/jpeg")
            {
                return(response);
            }
            try
            {
                var ext = image.FileName.EndsWith(".JPG")
                                ? ".JPG" : image.FileName.EndsWith(".PNG")
                                    ? ".PNG" : ".JPEG";
                var keyName             = g.ToString() + ext;
                var fileTransferUtility = new TransferUtility(_amazonClient);
                using (var stream = new MemoryStream())
                {
                    image.CopyTo(stream);
                    await fileTransferUtility.UploadAsync(stream, bucketName, keyName);

                    response.Succeeded = true;
                    response.Guid      = keyName;
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, image);
            }
            return(response);
        }
Exemple #12
0
        /// <summary>
        /// Upload files to specified path in s3 bucket
        /// </summary>
        /// <param name="files"></param>
        /// <param name="folderUrl">Relative folder location where to upload files</param>
        /// <returns></returns>
        /// <see cref="https://docs.aws.amazon.com/AmazonS3/latest/dev/HLuploadFileDotNet.html"/>
        public async Task <S3Response> UploadFilesAsync(IFormFileCollection files, string folderUrl)//NOTE:
        {
            var s3Response = new S3Response();

            //NOTE folderUrl == Key in my case
            var fileTransferUtility = new TransferUtility(_s3Client);

            try
            {
                foreach (var file in files)
                {
                    Stream str = file.OpenReadStream();
                    string key = $"{folderUrl}/{file.FileName}";
                    await fileTransferUtility.UploadAsync(str, _bucketName, key);
                }
            }
            catch (AmazonS3Exception e)
            {
                s3Response.Message = e.Message;

                Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
            }
            catch (Exception e)
            {
                s3Response.Message = e.Message;

                Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
            }

            s3Response.StatusCode = System.Net.HttpStatusCode.InternalServerError;
            return(s3Response);
        }
Exemple #13
0
 public static void ShareFile(AmazonS3 s3Client, string filekey)
 {
     S3Response response1 = s3Client.SetACL(new SetACLRequest()
     {
         CannedACL  = S3CannedACL.PublicRead,
         BucketName = BUCKET_NAME,
         Key        = filekey
     });
 }
Exemple #14
0
        //------------------------------------------
        #endregion

        #region --------------DeleteFile--------------
        public void DeleteFile(string BucketName, string filefullPath)
        {
            DeleteObjectRequest request = new DeleteObjectRequest()
            {
                BucketName = BucketName,
                Key        = filefullPath
            };
            S3Response response = S3Client.DeleteObject(request);
        }
Exemple #15
0
        //------------------------------------------
        #endregion

        #region --------------ShareFile--------------
        public void ShareFile(string BucketName, string filefullPath)
        {
            S3Response response1 = S3Client.SetACL(new SetACLRequest()
            {
                CannedACL  = S3CannedACL.PublicRead,
                BucketName = BucketName,
                Key        = filefullPath
            });
        }
Exemple #16
0
 public static void DeleteFile(AmazonS3 Client, string filekey)
 {
     DeleteObjectRequest request = new DeleteObjectRequest()
     {
         BucketName = BUCKET_NAME,
         Key        = filekey
     };
     S3Response response = Client.DeleteObject(request);
 }
Exemple #17
0
        //copies source file with a new filename, then deletes original
        public static void RenameObjectInS3(string sourceFilePath, string destFilePath)
        {
            AmazonS3 client;

            if (CheckS3Credentials())
            {
                NameValueCollection appConfig =
                    ConfigurationManager.AppSettings;

                string accessKeyID       = appConfig["AWSAccessKey"];
                string secretAccessKeyID = appConfig["AWSSecretKey"];

                using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(
                           accessKeyID, secretAccessKeyID, RegionEndpoint.USWest1))
                {
                    try
                    {
                        //copy to new file
                        CopyObjectRequest copyRequest = new CopyObjectRequest()
                                                        .WithSourceBucket(Constants.AmazonS3BucketName)
                                                        .WithSourceKey(sourceFilePath)
                                                        .WithDestinationBucket(Constants.AmazonS3BucketName)
                                                        .WithDestinationKey(destFilePath)
                                                        .WithCannedACL(S3CannedACL.PublicRead);

                        S3Response response = client.CopyObject(copyRequest);
                        response.Dispose();

                        //delete the original
                        DeleteObjectRequest deleteRequest = new DeleteObjectRequest()
                                                            .WithBucketName(Constants.AmazonS3BucketName)
                                                            .WithKey(sourceFilePath);
                        response = client.DeleteObject(deleteRequest);
                        response.Dispose();
                    }
                    catch (AmazonS3Exception amazonS3Exception)
                    {
                        if (amazonS3Exception.ErrorCode != null &&
                            (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
                             ||
                             amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                        {
                            Console.WriteLine("Check the provided AWS Credentials.");
                            Console.WriteLine(
                                "For service sign up go to http://aws.amazon.com/s3");
                        }
                        else
                        {
                            Console.WriteLine(
                                "Error occurred. Message:'{0}' when writing an object"
                                , amazonS3Exception.Message);
                        }
                    }
                }
            }
        }
Exemple #18
0
        public static void DeletingAnObject(AmazonS3Client client, string bucketName, string keyName)
        {
            DeleteObjectRequest request = new DeleteObjectRequest();

            request.WithBucketName(bucketName)
            .WithKey(keyName);
            S3Response response = client.DeleteObject(request);

            response.Dispose();
        }
Exemple #19
0
        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();
        }
Exemple #20
0
        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);
        }
Exemple #21
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(string data, StorageLocations location, string guid)
        {
            var keyName = string.Format("{0}/{1}.onx", StorageLocationToString(location), guid);

            var request = new PutObjectRequest();

            request.WithContentBody(data)
            .WithBucketName(Bucket)
            .WithKey(keyName);

            S3Response response = _client.PutObject(request);

            response.Dispose();
        }
Exemple #22
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();
        }
Exemple #23
0
        /* The following methods are for Amazon S3 filesystem */

        //writes plaintext data to S3 cloud
        public static void WritePlainTextObjectToS3(string data, string filePath)
        {
            AmazonS3 client;

            if (CheckS3Credentials())
            {
                NameValueCollection appConfig =
                    ConfigurationManager.AppSettings;

                string accessKeyID       = appConfig["AWSAccessKey"];
                string secretAccessKeyID = appConfig["AWSSecretKey"];

                using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(
                           accessKeyID, secretAccessKeyID, RegionEndpoint.USWest1))
                {
                    try
                    {
                        PutObjectRequest request = new PutObjectRequest();
                        request.WithContentBody(data)
                        .WithBucketName(Constants.AmazonS3BucketName)
                        .WithKey(filePath)
                        .WithContentType(Controllers.Constants.AmazonS3HtmlObjectType)
                        .WithCannedACL(S3CannedACL.PublicRead);

                        S3Response response3 = client.PutObject(request);
                        response3.Dispose();
                    }
                    catch (AmazonS3Exception amazonS3Exception)
                    {
                        if (amazonS3Exception.ErrorCode != null &&
                            (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
                             ||
                             amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                        {
                            Console.WriteLine("Check the provided AWS Credentials.");
                            Console.WriteLine(
                                "For service sign up go to http://aws.amazon.com/s3");
                        }
                        else
                        {
                            Console.WriteLine(
                                "Error occurred. Message:'{0}' when writing an object"
                                , amazonS3Exception.Message);
                        }
                    }
                }
            }
        }
Exemple #24
0
        public string UploadPhoto(Stream stream, string eventName, string photoName)
        {
            PutObjectRequest s3request = new PutObjectRequest();

            s3request.WithBucketName(_bucketName + "/" + eventName)
            .WithKey(photoName + ".jpg")
            .WithInputStream(stream);
            s3request.WithCannedACL(S3CannedACL.PublicRead);
            s3request.Timeout = 10000;
            S3Response s3response = _client.PutObject(s3request);

            s3response.Dispose();

            // TODO
            return(GetPicturePath(eventName, photoName));
        }
        public Stream get_file(string folderName, string fileName, bool useCache)
        {
            // It's allowed to have an empty folder name.
            // if (String.IsNullOrWhiteSpace(folderName)) throw new ArgumentNullException("folderName");
            if (String.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentNullException("fileName");
            }

            folderName = (string.IsNullOrEmpty(folderName) ? String.Empty : folderName.Substring(folderName.Length - 1, 1) == "/" ? folderName : folderName + "/");
            fileName   = string.Format("{0}{1}", folderName, fileName);

            if (useCache && !string.IsNullOrWhiteSpace(clientContext.ImagesUrl))
            {
                var         url      = new Uri(string.Format("{0}/{1}", clientContext.ImagesUrl, fileName));
                WebRequest  request  = WebRequest.Create(url);
                WebResponse response = request.GetResponse();

                return(response.GetResponseStream());
            }
            else
            {
                var request = new GetObjectRequest();
                request.WithBucketName(clientContext.BucketName);
                request.WithKey(fileName);
                request.WithTimeout((int)TimeSpan.FromMinutes(30).TotalMilliseconds);

                using (AmazonS3 client = clientContext.create_instance())
                {
                    try
                    {
                        S3Response response = wrap_request_in_error_handler(() => client.GetObject(request));

                        if (response != null)
                        {
                            return(response.ResponseStream);
                        }
                    }
                    catch (Exception)
                    {
                        //hate swallowing an error
                    }

                    return(null);
                }
            }
        }
Exemple #26
0
        public Stream GetFile(string folderName, string fileName, bool useCache)
        {
            //folder ignored - packages stored on top level of S3 bucket
            if (String.IsNullOrWhiteSpace(folderName))
            {
                throw new ArgumentNullException("folderName");
            }
            if (String.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentNullException("fileName");
            }

            if (useCache && !string.IsNullOrWhiteSpace(clientContext.PackagesUrl))
            {
                var         url      = new Uri(string.Format("{0}/{1}", clientContext.PackagesUrl, fileName));
                WebRequest  request  = WebRequest.Create(url);
                WebResponse response = request.GetResponse();

                return(response.GetResponseStream());
            }
            else
            {
                var request = new GetObjectRequest();
                request.WithBucketName(clientContext.BucketName);
                request.WithKey(fileName);
                request.WithTimeout((int)TimeSpan.FromMinutes(30).TotalMilliseconds);

                using (AmazonS3 client = clientContext.CreateInstance())
                {
                    try
                    {
                        S3Response response = WrapRequestInErrorHandler(() => client.GetObject(request));

                        if (response != null)
                        {
                            return(response.ResponseStream);
                        }
                    }
                    catch (Exception)
                    {
                        //hate swallowing an error
                    }

                    return(null);
                }
            }
        }
Exemple #27
0
        public string Sling(string path)
        {
            string token = Guid.NewGuid().ToString("N");

            string zipPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            ICSharpCode.SharpZipLib.Zip.FastZip fz = new ICSharpCode.SharpZipLib.Zip.FastZip();
            fz.CreateZip(zipPath, path, true, "", "");

            using (AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client("accesskey", "secret")) {
                try {
                    // simple object put
                    PutObjectRequest request = new PutObjectRequest();
                    request.WithBucketName("slingshot")
                    .WithKey(token + ".zip")
                    .WithCannedACL(S3CannedACL.PublicRead)
                    .WithFilePath(zipPath);

                    using (S3Response response = client.PutObject(request)) {
                        // work with it
                        Console.WriteLine(response.AmazonId2);
                    }
                }
                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);
                    }
                }
            }

            if (File.Exists(zipPath))
            {
                File.Delete(zipPath);
            }

            return(token);
        }
Exemple #28
0
        static void ReadingAnObject()
        {
            try
            {
                GetObjectRequest request = new GetObjectRequest().WithBucketName(bucketName).WithKey(keyName);

                using (S3Response response = client.GetObject(request))
                {
                    string title = response.Metadata["x-amz-meta-title"];
                    Console.WriteLine("The object's title is {0}", title);
                    string dest = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), keyName);
                    if (!File.Exists(dest))
                    {
                        using (Stream s = response.ResponseStream)
                        {
                            using (FileStream fs = new FileStream(dest, FileMode.Create, FileAccess.Write))
                            {
                                byte[] data      = new byte[32768];
                                int    bytesRead = 0;
                                do
                                {
                                    bytesRead = s.Read(data, 0, data.Length);
                                    fs.Write(data, 0, bytesRead);
                                }while (bytesRead > 0);
                                fs.Flush();
                            }
                        }
                    }
                }
            }
            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 reading an object", amazonS3Exception.Message);
                }
            }
        }
Exemple #29
0
        //removes a file in S3 cloud
        public static void RemoveObjectFromS3(string filePath)
        {
            AmazonS3 client;

            if (CheckS3Credentials())
            {
                NameValueCollection appConfig =
                    ConfigurationManager.AppSettings;

                string accessKeyID       = appConfig["AWSAccessKey"];
                string secretAccessKeyID = appConfig["AWSSecretKey"];

                using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(
                           accessKeyID, secretAccessKeyID, RegionEndpoint.USWest1))
                {
                    try
                    {
                        DeleteObjectRequest request = new DeleteObjectRequest();
                        request.WithBucketName(Constants.AmazonS3BucketName)
                        .WithKey(filePath);

                        S3Response response = client.DeleteObject(request);
                        response.Dispose();
                    }
                    catch (AmazonS3Exception amazonS3Exception)
                    {
                        if (amazonS3Exception.ErrorCode != null &&
                            (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
                             ||
                             amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                        {
                            Console.WriteLine("Check the provided AWS Credentials.");
                            Console.WriteLine(
                                "For service sign up go to http://aws.amazon.com/s3");
                        }
                        else
                        {
                            Console.WriteLine(
                                "Error occurred. Message:'{0}' when deleting an object"
                                , amazonS3Exception.Message);
                        }
                    }
                }
            }
        }
Exemple #30
0
        public async Task <S3Response> CreateBucketAsync(string bucketName)
        {
            var res = new S3Response
            {
                Status  = HttpStatusCode.InternalServerError,
                Message = "Error"
            };

            try
            {
                if (await AmazonS3Util.DoesS3BucketExistAsync(_client, bucketName) == false)
                {
                    var putBucketRequest = new PutBucketRequest
                    {
                        BucketName      = bucketName,
                        UseClientRegion = true
                    };

                    //relies on credentials C:\Users\<user>\.aws (access key in file & secret key can only be seen when creating access key 1st time via AWS console)
                    var response = await _client.PutBucketAsync(putBucketRequest);

                    res.Status  = response.HttpStatusCode;
                    res.Message = response.ResponseMetadata.RequestId;
                }
                else
                {
                    res.Status  = HttpStatusCode.Conflict;
                    res.Message = string.Format("Already exists : {0}", bucketName);
                }
            }
            catch (AmazonS3Exception exaws)
            {
                Console.WriteLine(exaws);
                res.Status  = exaws.StatusCode;
                res.Message = exaws.Message;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                res.Status  = HttpStatusCode.InternalServerError;
                res.Message = ex.Message;
            }

            return(res);
        }