예제 #1
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();
        }
예제 #2
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();
        }
예제 #3
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);
             }
         }
     }
 }
예제 #4
0
        public override string SavePrivate(string domain, string path, Stream stream, DateTime expires)
        {
            using (AmazonS3 client = GetClient())
            {
                var    request   = new PutObjectRequest();
                string objectKey = MakePath(domain, path);
                request.WithBucketName(_bucket)
                .WithKey(objectKey)
                .WithCannedACL(S3CannedACL.BucketOwnerFullControl)
                .WithContentType("application/octet-stream")
                .WithMetaData("private-expire", expires.ToFileTimeUtc().ToString());

                var headers = new NameValueCollection();
                headers.Add("Cache-Control", string.Format("public, maxage={0}", (int)TimeSpan.FromDays(5).TotalSeconds));
                headers.Add("Etag", (DateTime.UtcNow.Ticks).ToString());
                headers.Add("Last-Modified", DateTime.UtcNow.ToString("R"));
                headers.Add("Expires", DateTime.UtcNow.Add(TimeSpan.FromDays(5)).ToString("R"));
                headers.Add("Content-Disposition", "attachment");
                request.AddHeaders(headers);

                request.WithInputStream(stream);
                client.PutObject(request);
                //Get presigned url
                GetPreSignedUrlRequest pUrlRequest = new GetPreSignedUrlRequest()
                                                     .WithBucketName(_bucket)
                                                     .WithExpires(expires)
                                                     .WithKey(objectKey)
                                                     .WithProtocol(Protocol.HTTP)
                                                     .WithVerb(HttpVerb.GET);

                string url = client.GetPreSignedURL(pUrlRequest);
                //TODO: CNAME!
                return(url);
            }
        }
        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));
            }
        }
예제 #6
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));
            }
        }
        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);
            }
        }
예제 #8
0
        private void putWithRetry(PutObjectRequest request)
        {
            // Retry put request up to five times
            for (int i = 0; i < properties.S3MaxErrorRetry; i++)
            {
                try
                {
                    // Attempt to put the object
                    s3.PutObject(request);
                    log.Info("Successfully uploaded file to S3: " + request.ToString());
                    return;
                }
                catch (AmazonS3Exception exception)
                {
                    log.Info("Failed to upload file to S3: " + exception.ToString());
                    Thread.Sleep(properties.S3RetryDelayInterval);
                }
                catch (Exception e) {
                    log.Info("Failed to upload file to S3: " + e.ToString());
                    Thread.Sleep(properties.S3RetryDelayInterval);
                }
            }

            throw new AmazonS3Exception("Failed to upload file to S3");
        }
예제 #9
0
        public static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            log.Info("Initializing and connecting to AWS...");

            s3 = AWSClientFactory.CreateAmazonS3Client(RegionEndpoint.USWest1);
            indexer = new FileIndexer("Files");
            indexer.Index();

            s3indexer = new S3Indexer(Settings.Default.BucketName, Settings.Default.FolderName, "S3Tmp", s3);
            s3indexer.Index();

            log.Info("Comparing local index and remote index.");

            var filesToUpload = (from filePair in indexer.FileIndex where !s3indexer.HashedFiles.ContainsKey(filePair.Key) || !s3indexer.HashedFiles[filePair.Key].SequenceEqual(filePair.Value) select filePair.Key).ToList();
            var filesToDelete = (from filePair in s3indexer.HashedFiles where !indexer.FileIndex.ContainsKey(filePair.Key) select filePair.Key).ToList();

            foreach(var fileDelete in filesToDelete)
            {
                log.Debug("Deleting file "+fileDelete);
                s3.DeleteObject(new DeleteObjectRequest()
                                    {
                                        BucketName = Settings.Default.BucketName,
                                        Key = Settings.Default.FolderName + "/" + fileDelete
                                    });
            }

            foreach(var fileUpload in filesToUpload)
            {
                log.Debug("Uploading file "+fileUpload);
                s3.PutObject(new PutObjectRequest()
                                 {
                                     BucketName = Settings.Default.BucketName,
                                     Key = Settings.Default.FolderName + "/" + fileUpload,
                                     AutoCloseStream = true,
                                     InputStream = new FileStream("Files/" + fileUpload, FileMode.Open)
                                 });
            }

            log.Info("Re-indexing files...");

            using (MemoryStream stream = new MemoryStream())
            {
                Serializer.Serialize(stream, indexer.FileIndex);
                stream.Position = 0;
                s3.PutObject(new PutObjectRequest()
                {
                    BucketName = Settings.Default.BucketName,
                    Key = Settings.Default.FolderName + "/" + "index.mhash",
                    InputStream = stream
                });
            }

            log.Info("Done!");

            Console.Read();
        }
예제 #10
0
 public void WriteFile(string filePath, string contents)
 {
     AmazonS3.PutObject(new PutObjectRequest
     {
         Key         = SanitizePath(filePath),
         BucketName  = BucketName,
         ContentBody = contents,
     });
 }
예제 #11
0
 public void WriteFile(string filePath, Stream stream)
 {
     AmazonS3.PutObject(new PutObjectRequest
     {
         Key         = SanitizePath(filePath),
         BucketName  = BucketName,
         InputStream = stream,
     });
 }
예제 #12
0
파일: S3Sample.cs 프로젝트: jvitrifork/CCD
        static void WritingAnObject()
        {
            try
            {
                // simple object put
                PutObjectRequest request = new PutObjectRequest();
                request.WithContentBody("this is a test")
                .WithBucketName(bucketName)
                .WithKey(keyName);

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

                // put a more complex object with some metadata and http headers.
                PutObjectRequest titledRequest = new PutObjectRequest();
                titledRequest.WithMetaData("title", "the title")
                .WithContentBody("this object has a title")
                .WithBucketName(bucketName)
                .WithKey(keyName);

                using (S3Response responseWithMetadata = client.PutObject(titledRequest))
                {
                    WebHeaderCollection headers = response.Headers;
                    foreach (string key in headers.Keys)
                    {
                        Console.WriteLine("Response Header: {0}, Value: {1}", key, headers.Get(key));
                    }
                }
            }
            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);
                }
            }
        }
예제 #13
0
        public override bool Execute()
        {
            RequireSecretKey();
            AmazonS3 s3Client   = AWSClientFactory.CreateAmazonS3Client(AccessKey, SecretKey);
            string   bucketName = Bucket.ItemSpec;

            Log.LogMessage(MessageImportance.High, "Connecting to \"{0}\"", bucketName);

            WarnIfUneven(Tuple.Create("Puts", Puts), Tuple.Create("Keys", Keys));
            foreach (var tuple in Zip(Puts, Keys))
            {
                ITaskItem put     = tuple.Item1;
                ITaskItem keyItem = tuple.Item2;
                string    key     = keyItem.ItemSpec.Replace('\\', '/').TrimStart('/');
                if (!put.Exists())
                {
                    Log.LogMessage(MessageImportance.Normal, "Skipping {0} because it does not exist", key);
                    continue;
                }

                if (_Cancel)
                {
                    return(false);
                }

                var putObjectRequest = new PutObjectRequest
                {
                    BucketName       = bucketName,
                    FilePath         = put.ItemSpec,
                    Key              = key,
                    Timeout          = -1,
                    ReadWriteTimeout = 300000     // 5 minutes in milliseconds
                };

                S3CannedACL cannedACL;
                if (Enum.TryParse <S3CannedACL>(put.GetMetadata("CannedACL") ?? "", out cannedACL))
                {
                    Log.LogMessage(MessageImportance.Normal, "Applying CannedACL: {0}", cannedACL);
                    putObjectRequest.CannedACL = cannedACL;
                }

                string contentType = put.GetMetadata("ContentType");
                if (!string.IsNullOrWhiteSpace(contentType))
                {
                    Log.LogMessage(MessageImportance.Normal, "Applying ContentType: {0}", contentType);
                    putObjectRequest.ContentType = contentType;
                }

                Log.LogMessage(MessageImportance.High, "Putting \"{0}\"", key);

                using (var upload = s3Client.PutObject(putObjectRequest))
                {
                }
            }
            return(true);
        }
예제 #14
0
        /// <summary>
        /// /////////////////////Create a new file in folder/////////////////
        /// </summary>
        /// <param name="client"></param>
        public static void CreateNewFileInFolder(AmazonS3 client, string cmap, string clipping)
        {
            String           FolderKey = clipping + "/" + "Demo Create File.txt";
            PutObjectRequest request   = new PutObjectRequest();

            request.WithBucketName(cmap);
            request.WithKey(S3_KEY);
            request.WithContentBody("This is body of S3 object.");
            client.PutObject(request);
        }
예제 #15
0
        /// <summary>
        /// ///////////////////Create a new Folder///////////////////////////////
        /// </summary>
        /// <param name="client"></param>
        public static void CreateNewFolder(AmazonS3 client, string cmap, string clipping)
        {
            String           FolderKey = clipping + "/";
            PutObjectRequest request   = new PutObjectRequest();

            request.WithBucketName(cmap);
            request.WithKey(FolderKey);
            request.WithContentBody("");
            client.PutObject(request);
        }
예제 #16
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;
 }
예제 #17
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);
        }
예제 #18
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;
 }
예제 #19
0
        /// <summary>
        /// ////////////////// Upload a new file//////////////////////////////////
        /// </summary>
        /// <param name="client"></param>
        public static void UploadFile(AmazonS3 client)
        {
            //S3_KEY is name of file we want upload
            PutObjectRequest request = new PutObjectRequest();

            request.WithBucketName(BUCKET_NAME);
            request.WithKey(S3_KEY);
            //request.WithInputStream(MemoryStream);
            request.WithFilePath(File_Path);
            client.PutObject(request);
            //Console.WriteLine("Yay");
        }
예제 #20
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);
        }
예제 #21
0
        public static string UploadFile(AmazonS3 client, string filepath)
        {
            //S3_KEY is name of file we want upload
            S3_KEY = System.IO.Path.GetFileName(filepath);
            PutObjectRequest request = new PutObjectRequest();

            request.WithBucketName(BUCKET_NAME);
            request.WithKey(S3_KEY);
            //request.WithInputStream(MemoryStream);
            request.WithFilePath(filepath);
            client.PutObject(request);
            return(S3_KEY);
        }
예제 #22
0
        private static void PutObject(AmazonS3 s3Client, string bucket, string key)
        {
            var putObjectRequest = new PutObjectRequest();

            putObjectRequest.WithBucketName(bucket)
            .WithKey(key)
            .WithContentType("text/plain")
            .WithContentBody(key);

            var objectResponse = s3Client.PutObject(putObjectRequest);

            objectResponse.Dispose();
        }
예제 #23
0
        /// <summary>
        /// Store the content from a local file into a bucket.
        /// The key is the path under which the file will be stored.
        /// </summary>
        /// <param name="bucketName">The name of the bucket.</param>
        /// <param name="key">The key under which the file will be available afterwards.</param>
        /// <param name="file">The path to the local file.</param>
        /// <param name="publicRead">Flag which indicates if the file is publicly available or not.</param>
        /// <param name="timeoutMilliseconds">The timeout in milliseconds within the upload must have happend.</param>
        public void PutFile(string bucketName, string key, string file, bool publicRead, int timeoutMilliseconds)
        {
            var request = new PutObjectRequest
            {
                CannedACL  = publicRead ? S3CannedACL.PublicRead : S3CannedACL.Private,
                FilePath   = file,
                BucketName = bucketName,
                Key        = key,
                Timeout    = timeoutMilliseconds
            };

            _amazonS3.PutObject(request);
        }
예제 #24
0
        public static void Put(string bucket, string key, string fileName)
        {
            AmazonS3 s3Client = AWSClientFactory.CreateAmazonS3Client();
            FileInfo file     = new FileInfo(fileName);

            Console.Write("Uploading " + file.Name + " to " + bucket + ":" + key + file.Name);
            PutObjectRequest po_req = new PutObjectRequest();

            po_req.BucketName      = bucket;
            po_req.Key             = key + file.Name;
            po_req.FilePath        = fileName;
            po_req.AutoCloseStream = true;
            PutObjectResponse po_res = s3Client.PutObject(po_req);

            Console.WriteLine(po_res.AmazonId2);
        }
예제 #25
0
        public void TestInitialize()
        {
            try
            {
                this.objKey = Guid.NewGuid().ToString("N");
                var putRequest = new PutObjectRequest()
                                 .WithBucketName(bucket.BucketName)
                                 .WithKey(this.objKey)
                                 .WithContentBody(ObjectContent_Before);

                using (var putResponse = client.PutObject(putRequest)) { }
            }
            catch (Exception e)
            {
                Assert.Inconclusive("prerequisite: unable to create object.  Error: {0}", e.Message);
            }
        }
예제 #26
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);
        }
예제 #27
0
        /// <summary>
        /// Copies the file from the local file system to S3.
        /// If the file already exists in S3 and overwrite is set to false than an ArgumentException is thrown.
        /// </summary>
        /// <param name="srcFileName">Location of the file on the local file system to copy.</param>
        /// <param name="overwrite">Determines whether the file can be overwritten.</param>
        /// <exception cref="T:System.IO.IOException">If the file already exists in S3 and overwrite is set to false.</exception>
        /// <exception cref="T:System.Net.WebException"></exception>
        /// <exception cref="T:Amazon.S3.AmazonS3Exception"></exception>
        /// <returns>S3FileInfo where the file is copied to.</returns>
        public S3FileInfo CopyFromLocal(string srcFileName, bool overwrite)
        {
            if (!overwrite)
            {
                if (Exists)
                {
                    throw new IOException("File already exists");
                }
            }

            s3Client.PutObject(new PutObjectRequest()
                               .WithBucketName(bucket)
                               .WithKey(S3Helper.EncodeKey(key))
                               .WithFilePath(srcFileName)
                               .WithBeforeRequestHandler(S3Helper.FileIORequestEventHandler) as PutObjectRequest);

            return(this);
        }
예제 #28
0
        private void BackUpToAmazon(AmazonS3 client)
        {
            try
            {
                PutObjectRequest request = new PutObjectRequest();
                request.WithBucketName(this.BucketName).WithKey(FileLocations.CONFIG_FILENAME)
                .WithFilePath(settings.FileLocations.Configuration);

                client.PutObject(request);

                this.ErrorLabel.ForeColor = Color.Black;
                this.ErrorLabel.Text      = "The backup was a success!";
            }
            catch (Exception exception)
            {
                this.ErrorLabel.ForeColor = Color.Red;
                this.ErrorLabel.Text      = exception.Message;
            }
        }
예제 #29
0
        public void SaveObject(Stream fileContents, string fileName)
        {
            if (fileContents == null)
            {
                throw new ArgumentNullException("fileContents");
            }

            if (String.IsNullOrEmpty(fileName))
            {
                throw new ArgumentException("File name is required.", "fileName");
            }

            try
            {
                using (AmazonS3 client = CreateS3Client())
                {
                    if (DoesBucketExist(client) == false)
                    {
                        SetupBucket(client);
                    }

                    PutObjectRequest objectRequest = new PutObjectRequest().WithBucketName(BucketName).WithKey(fileName);

                    if (fileContents.CanSeek)
                    {
                        fileContents.Position = 0;
                    }

                    objectRequest.InputStream = fileContents;

                    client.PutObject(objectRequest);
                }
            }
            catch (AmazonS3Exception s3Ex)
            {
                throw AnAwsRelatedException(s3Ex);
            }
            catch (Exception ex)
            {
                throw new StorageException("An error occurred while processing your request.", ex);
            }
        }
예제 #30
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();
        }
예제 #31
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);
        }
예제 #32
0
        void UploadContent(string key, Stream content)
        {
            var request = new PutObjectRequest()
                          .WithBucketName(bucket)
                          .WithKey(key)
                          .WithCannedACL(cannedACL)
                          .WithInputStream(content) as PutObjectRequest;

            if (headers != null)
            {
                request.AddHeaders(headers);
            }

            //TODO: handle exceptions properly
            s3client.PutObject(request);

            if (invalidator != null)
            {
                invalidator.InvalidateObject(bucket, key);
            }
        }
예제 #33
0
        public bool UploadFileToS3(string uploadAsFileName, Stream ImageStream, S3CannedACL filePermission, S3StorageClass storageType)
        {
            try
            {
                AmazonS3         client  = Amazon.AWSClientFactory.CreateAmazonS3Client("AKIAJ4A6DAATIDU6ELAA", "EiA6EILkCp7pqzvnIUhXg3FFOft0j+pA/DtBM8if");
                PutObjectRequest request = new PutObjectRequest();
                request.WithKey("folder" + "/" + uploadAsFileName);
                request.WithInputStream(ImageStream);
                request.WithBucketName("shriners_rms");
                request.CannedACL    = filePermission;
                request.StorageClass = storageType;

                client.PutObject(request);
                client.Dispose();
            }
            catch
            {
                return(false);
            }
            return(true);
        }
예제 #34
0
        public static String UploadToS3(string fileName, Stream fileContent)
        {
            if (String.IsNullOrEmpty(fileName))
            {
                return("");
            }

            AmazonS3 s3Client = Amazon.AWSClientFactory.CreateAmazonS3Client("AKIAJ4A6DAATIDU6ELAA", "EiA6EILkCp7pqzvnIUhXg3FFOft0j+pA/DtBM8if");

            PutObjectRequest putObjectRequest = new PutObjectRequest();

            putObjectRequest.WithBucketName("shriners_rms");
            putObjectRequest.CannedACL   = S3CannedACL.PublicRead;
            putObjectRequest.Key         = fileName;
            putObjectRequest.InputStream = fileContent;
            S3Response response = s3Client.PutObject(putObjectRequest);

            response.Dispose();

            return("http://shriners_rms.s3.amazonaws.com/" + fileName);
        }
예제 #35
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
            var response = _client.PutObject(request);

            response.Dispose();
        }
        public void WalkAndUpload(string path, string bucket, AmazonS3 client)
        {
            foreach (var f in Directory.GetFiles(path))
            {
                var fi = new FileInfo(f);
                if (fi.Name.StartsWith("."))
                {
                    continue;
                } //ignore ".gitignore"

                string fileToPush = f;
                string destinationName =
                    Regex.Split(fileToPush, @"gitCheckout-[\d]*")[1].Replace("\\", "/").TrimStart("/".ToCharArray());

                var poR = new PutObjectRequest()
                    {
                        BucketName = bucket,
                        FilePath = fileToPush,
                        Key = destinationName,
                        Timeout = -1,
                        ReadWriteTimeout = 300000,
                        CannedACL = S3CannedACL.PublicRead
                    };
                var res = client.PutObject(poR);

            }

            foreach (var d in Directory.GetDirectories(path))
            {
                var di = new DirectoryInfo(d);
                if (di.Name.StartsWith("."))
                {
                    continue;
                } //ignore ".git"
                WalkAndUpload(d, bucket, client);
            }
        }
예제 #37
0
        public void putInS3Bucket(resume resume, string txtResults, string[] generatedFiles, string storedFilePath, string generatedFilePath)
        {
            using (client = Amazon.AWSClientFactory.CreateAmazonS3Client("AKIAJ47VSG7WMA62WLCA", "3tqlHujlftpk6j/z5OtDw2eg9N2FJtz1RwL8bEa3"))
            {

                string keyName;
                S3Response response;

                if (resume.hasIMG)
                {
                    var pageNo = 0;
                    var append = false;
                    foreach (string fileName in generatedFiles)
                    {
                        keyName = "img/" + resume.resumeID.ToString();
                        keyName = append ? (keyName + "_" + pageNo.ToString()) : keyName;
                        PutObjectRequest imgRequest = new PutObjectRequest();
                        imgRequest.WithBucketName("intelrecruiter")
                            .WithCannedACL(S3CannedACL.PublicRead)
                            .WithFilePath(fileName)
                            .WithKey(keyName);

                        response = client.PutObject(imgRequest);
                        response.Dispose();
                        append = true;
                        pageNo++;
                    }
                }

                if (resume.hasTXT)
                {
                    keyName = "txt/" + resume.resumeID.ToString();
                    PutObjectRequest txtRequest = new PutObjectRequest();

                    if (resume.hasDOCX)
                    {
                        txtRequest.WithBucketName("intelrecruiter")
                            .WithCannedACL(S3CannedACL.PublicRead)
                            .WithContentBody(txtResults)
                            .WithKey(keyName);
                    }
                    else
                    {
                        txtRequest.WithBucketName("intelrecruiter")
                            .WithCannedACL(S3CannedACL.PublicRead)
                            .WithFilePath(generatedFilePath)
                            .WithKey(keyName);
                    }
                    response = client.PutObject(txtRequest);
                    response.Dispose();
                }

                if (resume.hasPDF)
                {
                    keyName = "pdf/" + resume.resumeID.ToString();
                    PutObjectRequest pdfRequest = new PutObjectRequest();
                    pdfRequest.WithBucketName("intelrecruiter")
                        .WithCannedACL(S3CannedACL.PublicRead)
                        .WithFilePath(storedFilePath)
                        .WithKey(keyName);

                    response = client.PutObject(pdfRequest);
                    response.Dispose();
                }

                if (resume.hasDOCX)
                {
                    keyName = "docx/" + resume.resumeID.ToString();
                    PutObjectRequest imgRequest = new PutObjectRequest();
                    imgRequest.WithBucketName("intelrecruiter")
                        .WithCannedACL(S3CannedACL.PublicRead)
                        .WithFilePath(storedFilePath)
                        .WithKey(keyName);

                    response = client.PutObject(imgRequest);
                    response.Dispose();
                }
            }
        }
예제 #38
0
        private void saveSession(Cookie cookie)
        {
            string cookieName = cookie.Name;
            string cookieValue = cookie.Value;

            using (client = Amazon.AWSClientFactory.CreateAmazonS3Client("AKIAJ47VSG7WMA62WLCA", "3tqlHujlftpk6j/z5OtDw2eg9N2FJtz1RwL8bEa3"))
            {
                PutObjectRequest txtRequest = new PutObjectRequest();

                txtRequest.WithBucketName("intelrecruiter")
                            .WithContentBody(cookieName)
                            .WithKey(nsbeCookieNameKey);

                var response = client.PutObject(txtRequest);
                response.Dispose();

                txtRequest = new PutObjectRequest();

                txtRequest.WithBucketName("intelrecruiter")
                            .WithContentBody(cookieValue)
                            .WithKey(nsbeCookieValueKey);

                response = client.PutObject(txtRequest);
                response.Dispose();

            }

            nsbeCookie = new Cookie(cookieName, cookieValue, "/");
        }
예제 #39
0
 public static string UploadFile(AmazonS3 client, string filepath)
 {
     //S3_KEY is name of file we want upload
     S3_KEY = System.IO.Path.GetFileName(filepath);
     PutObjectRequest request = new PutObjectRequest();
     request.WithBucketName(BUCKET_NAME);
     request.WithKey(S3_KEY);
     //request.WithInputStream(MemoryStream);
     request.WithFilePath(filepath);
     client.PutObject(request);
     return S3_KEY;
 }
예제 #40
0
        private static void PutObject(AmazonS3 s3Client, string bucket, string key)
        {
            var putObjectRequest = new PutObjectRequest();
              putObjectRequest.WithBucketName(bucket)
                      .WithKey(key)
                      .WithContentType("text/plain")
                      .WithContentBody(key);

              var objectResponse = s3Client.PutObject(putObjectRequest);
              objectResponse.Dispose();
        }
예제 #41
0
        private bool AddImageToAmazon(Coupon coupon, HttpPostedFile File, string ext)
        {
            string count = "";
            string keyname = "";
            //ext = ".jpg";
            //try
            //{
                string accessKeyID = WebConfigurationManager.AppSettings["AWSAccessKey"];
                string secretAccessKeyID = WebConfigurationManager.AppSettings["AWSSecretKey"];

                AmazonS3Config s3Config = new AmazonS3Config();
                s3Config.UseSecureStringForAwsSecretKey = false;

                client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKeyID, secretAccessKeyID, s3Config);
                //count += "1";
                ICouponDAO couponDAO = _factoryDAO.GetCouponDAO();
                Byte[] imgByte = new byte[0];
                //count += "2";
                //Create byte Array with file len
                imgByte = new Byte[File.ContentLength];
                //count += "3";
                //force the control to load data in array
                File.InputStream.Read(imgByte, 0, File.ContentLength);
                //count += "4";
                //count += ext;
                //count += _merchantname;
                //count += _couponID.ToString();
                //count += File.FileName;
                //count += File.FileName.Substring(0, File.FileName.IndexOf("."));
                //count += ":";
                //count += string.Format("{0}{1}", _couponID.ToString(), ext);
                keyname = string.Format("{0}/{1}", _merchantname, File.FileName.Replace(File.FileName.Substring(0, File.FileName.IndexOf(".")), string.Format("{0}{1}", _couponID.ToString(), ext)));
                //keyname = string.Format("{0}/{1}", _merchantname, File.FileName.Replace(File.FileName.Substring(0, File.FileName.IndexOf(".")), _couponID.ToString()));
                count += keyname;
                /*try
                {
                    //first try deleting old item if applicable
                    DeleteObjectRequest delete_request = new DeleteObjectRequest();
                    delete_request.WithBucketName("gfck").WithKey(string.Format("coupon/{0}", keyname));
                    S3Response delete_response = client.DeleteObject(delete_request);
                    delete_response.Dispose();
                }
                catch (Exception ex)
                {
                    _log.ErrorFormat("Error trying to delete object from bucket: {0} with exception {1}", keyname, ex.Message);
                }*/
                string BUCKET_NAME = String.Format("gfck/coupon/{0}", _merchantname);
                try
                {
                    //add the bucket just in case not already there.
                    //PutObjectRequest request1 = new PutObjectRequest();
                    PutBucketRequest req = new PutBucketRequest();
                    req.WithBucketName(BUCKET_NAME);
                    //count += "6";
                    //request1.WithBucketName("gfck").WithContentType(File.ContentType).WithCannedACL(S3CannedACL.PublicReadWrite).WithKey(BUCKET_NAME);
                    //S3Response response = client.PutObject(request1);
                    //response.Dispose();
                    client.PutBucket(req);
                }
                catch (Exception ex)
                {
                    _log.DebugFormat("This bucket already exists: {0} with exception {1}", BUCKET_NAME, ex.Message);
                }

                //count += "5";
                PutObjectRequest request = new PutObjectRequest();
                //count += "6";
                request.WithBucketName("gfck").WithContentType(File.ContentType).WithCannedACL(S3CannedACL.PublicRead).WithKey(string.Format("coupon/{0}", keyname)).WithInputStream(File.InputStream);
                count += "here";
                S3Response response = client.PutObject(request);
                count += "7";
                response.Dispose();
                count += "8";
                if (ext == "")
                {
                    coupon.Image = keyname;
                }
                else
                {
                    coupon.BottomAdvertisement = keyname;
                }
                count += "9";

                return couponDAO.UpdateCoupon(coupon);
            /*}
            catch (Exception ex)
            {
                _log.ErrorFormat("Exception Occurred: Exception={0}", ex.Message);
                lblError.Text = String.Format("Error with coupon image. {0} {1} {2}", count, keyName, ex.Message);
                lblError.Visible = true;
                lblAddSuccessfull.Visible = false;
                lblEditSuccessfull.Visible = false;
                return false;
            }*/
        }
예제 #42
0
        public ActionResult GetAll(int[] resumesToDelete)
        {
            string executableDir = Server.MapPath("~/executables");

            resume resume;
            ResumeFiles resumeFileRequest = new ResumeFiles();

            var zipName = User.Identity.Name;
            var fileName = zipName + ".zip";

            string uploadDir = getUploadDir();
            Directory.SetCurrentDirectory(uploadDir);
            foreach (int resumeID in resumesToDelete)
            {

                resume = resumeRepository.GetResume(resumeID);

                resumeFileRequest.getFilefromS3(resume, zipName);

            }

            var command = "\"" + executableDir + "\\7za\" a " + fileName + " " + zipName;
            ExecuteCommandSync(command);

            var fullPath = Path.Combine(uploadDir, fileName);
            var folderPath = Path.Combine(uploadDir, zipName);
            string contentType = "application/zip";

               string keyName = "user_downloads/" + fileName;
               using (client = Amazon.AWSClientFactory.CreateAmazonS3Client("AKIAJ47VSG7WMA62WLCA", "3tqlHujlftpk6j/z5OtDw2eg9N2FJtz1RwL8bEa3"))
               {
               S3Response response;

                PutObjectRequest s3request = new PutObjectRequest();
                s3request.WithBucketName("intelrecruiter")
                    .WithCannedACL(S3CannedACL.PublicRead)
                    .WithFilePath(fullPath)
                    .WithKey(keyName);

                response = client.PutObject(s3request);
                response.Dispose();

               }
               FileInfo newFile = new FileInfo(fullPath);
               newFile.Delete();

               DirectoryInfo dir = new DirectoryInfo(folderPath);
               dir.Delete(true);

               return RedirectToAction("List", new { user_download = keyName });

            //return File(fullPath, contentType, zipName + ".zip");

            /*
            FileInfo newFile = new FileInfo(fullPath);

            string attachment = string.Format("attachment; filename={0}", fileName);
            Response.Clear();
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = contentType;
            Response.WriteFile(newFile.FullName);
            Response.Flush();
            newFile.Delete();

            DirectoryInfo dir = new DirectoryInfo(folderPath);
            dir.Delete(true);
            */
            //return RedirectToAction("Index");
        }
        private void BackUpToAmazon(AmazonS3 client)
        {
            try
            {
                PutObjectRequest request = new PutObjectRequest();
                request.WithBucketName(this.BucketName).WithKey(FileLocations.CONFIG_FILENAME)
                    .WithFilePath(settings.FileLocations.Configuration);

                client.PutObject(request);

                this.ErrorLabel.ForeColor = Color.Black;
                this.ErrorLabel.Text = "The backup was a success!";
            }
            catch (Exception exception)
            {
                this.ErrorLabel.ForeColor = Color.Red;
                this.ErrorLabel.Text = exception.Message;
            }
        }