コード例 #1
0
ファイル: Job.cs プロジェクト: plasma-umass/typissed
        public string UploadImageToS3(AST.Address addr, Bitmap b, string secret)
        {
            // convert Bitmap to MemoryStream
            MemoryStream stream = new MemoryStream();

            b.Save(stream, System.Drawing.Imaging.ImageFormat.Png);

            // the image name is the md
            var imagename = GetImageName(addr);

            // the url to the bitmap
            string url;

            // upload MemoryStream to S3
            using (AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(_id, secret))
            {
                // generate url
                GetPreSignedUrlRequest request = new GetPreSignedUrlRequest()
                {
                    BucketName = _s3bucket,
                    Key        = imagename,
                    Verb       = HttpVerb.GET,
                    Expires    = DateTime.Now.AddMonths(24)
                };
                url = client.GetPreSignedURL(request);

                // upload image
                var tu = new Amazon.S3.Transfer.TransferUtility(client);
                tu.Upload(stream, _s3bucket, imagename);
            }

            return(url);
        }
コード例 #2
0
ファイル: S3Storage.cs プロジェクト: Wifisoft/teamlab.v6.5
        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);
            }
        }
コード例 #3
0
        /// <summary>
        /// Determines whether an S3 bucket exists or not.
        /// This is done by:
        /// 1. Creating a PreSigned Url for the bucket (with an expiry date at the end of this decade)
        /// 2. Making a HEAD request to the Url
        /// </summary>
        /// <param name="bucketName">The name of the bucket to check.</param>
        /// <param name="client">The Amazon S3 Client to use for S3 specific operations.</param>
        /// <returns></returns>
        public static bool DoesS3BucketExist(string bucketName, AmazonS3 client)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client", "The s3Client cannot be null!");
            }

            if (String.IsNullOrEmpty(bucketName))
            {
                throw new ArgumentNullException("bucketName", "The bucketName cannot be null or the empty string!");
            }

            GetPreSignedUrlRequest request = new GetPreSignedUrlRequest();

            request.BucketName = bucketName;
            request.Expires    = new DateTime(2019, 12, 31);
            request.Verb       = HttpVerb.HEAD;
            request.Protocol   = Protocol.HTTP;
            Uri url = new Uri(client.GetPreSignedURL(request));

            HttpWebRequest httpRequest = WebRequest.Create(url) as HttpWebRequest;

            httpRequest.Method = "HEAD";
            bool response = true;

            try
            {
                httpRequest.BeginGetResponse(asyncResponse =>
                {
                    HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(asyncResponse);

                    if (null != httpResponse)
                    {
                        response = true;
                    }
                }, httpRequest);
            }
            catch (WebException we)
            {
                using (HttpWebResponse errorResponse = we.Response as HttpWebResponse)
                {
                    if (errorResponse != null)
                    {
                        HttpStatusCode code = errorResponse.StatusCode;
                        return(code != HttpStatusCode.NotFound &&
                               code != HttpStatusCode.BadRequest);
                    }

                    // The Error Response is null which is indicative of either
                    // a bad request or some other problem
                    response = false;
                }
            }
            return(response);
        }
コード例 #4
0
ファイル: S3Engine.cs プロジェクト: xescrp/breinstormin
        public static String MakeUrl(AmazonS3 s3Client, string filekey)
        {
            string preSignedURL = s3Client.GetPreSignedURL(new GetPreSignedUrlRequest()
            {
                BucketName = BUCKET_NAME,
                Key        = filekey,
                Expires    = System.DateTime.Now.AddYears(10)
            });

            return(preSignedURL);
        }
コード例 #5
0
        /// <summary>
        /// Determines whether an S3 bucket exists or not.
        /// This is done by:
        /// 1. Creating a PreSigned Url for the bucket (with an expiry date at the end of this decade)
        /// 2. Making a HEAD request to the Url
        /// </summary>
        /// <param name="bucketName">The name of the bucket to check.</param>
        /// <param name="s3Client">The Amazon S3 Client to use for S3 specific operations.</param>
        /// <returns></returns>
        public static bool DoesS3BucketExist(string bucketName, AmazonS3 s3Client)
        {
            if (s3Client == null)
            {
                throw new ArgumentNullException("s3Client", "The s3Client cannot be null!");
            }

            if (String.IsNullOrEmpty(bucketName))
            {
                throw new ArgumentNullException("bucketName", "The bucketName cannot be null or the empty string!");
            }

            GetPreSignedUrlRequest request = new GetPreSignedUrlRequest();

            request.BucketName = bucketName;
            request.Expires    = new DateTime(2019, 12, 31);
            request.Verb       = HttpVerb.HEAD;
            request.Protocol   = Protocol.HTTP;
            string url = s3Client.GetPreSignedURL(request);

            HttpWebRequest httpRequest = WebRequest.Create(url) as HttpWebRequest;

            httpRequest.Method = "HEAD";
            AmazonS3Client concreteClient = s3Client as AmazonS3Client;

            if (concreteClient != null)
            {
                concreteClient.ConfigureProxy(httpRequest);
            }

            try
            {
                HttpWebResponse httpResponse = httpRequest.GetResponse() as HttpWebResponse;
                // If all went well, the bucket was found!
                return(true);
            }
            catch (WebException we)
            {
                using (HttpWebResponse errorResponse = we.Response as HttpWebResponse)
                {
                    if (errorResponse != null)
                    {
                        HttpStatusCode code = errorResponse.StatusCode;
                        return(code != HttpStatusCode.NotFound &&
                               code != HttpStatusCode.BadRequest);
                    }

                    // The Error Response is null which is indicative of either
                    // a bad request or some other problem
                    return(false);
                }
            }
        }
コード例 #6
0
        public string GeneratePreSignedURL(String sFolder, String objectKey)
        {
            AmazonS3 client      = AWSClientFactory.CreateAmazonS3Client(S3ACCESSKEY, S3SECRETKEY);
            string   BUCKET_NAME = ConfigurationManager.AppSettings["AWSBUCKET"];
            string   urlString;

            if (sFolder != "")
            {
                urlString = sFolder + "/";
            }
            else
            {
                urlString = "";
            }

            GetPreSignedUrlRequest request1 = new GetPreSignedUrlRequest
            {
                BucketName = BUCKET_NAME,
                Key        = objectKey,
                Expires    = DateTime.Now.AddMinutes(5),
                Protocol   = Amazon.S3.Model.Protocol.HTTP
            };

            try
            {
                urlString = client.GetPreSignedURL(request1);
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                if (amazonS3Exception.ErrorCode != null &&
                    (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
                     ||
                     amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                {
                    Console.WriteLine("Check the provided AWS Credentials.");
                    Console.WriteLine(
                        "To sign up for service, go to http://aws.amazon.com/s3");
                }
                else
                {
                    Console.WriteLine(
                        "Error occurred. Message:'{0}' when listing objects",
                        amazonS3Exception.Message);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            return(urlString);
        }
コード例 #7
0
        public Uri FetchFileUrl(string sObjectKey)
        {
            AmazonS3 client      = AWSClientFactory.CreateAmazonS3Client(S3ACCESSKEY, S3SECRETKEY);
            string   S3_KEY      = ConfigurationManager.AppSettings["AWSS3KEY"];
            string   BUCKET_NAME = ConfigurationManager.AppSettings["AWSBUCKET"];

            GetPreSignedUrlRequest request = new GetPreSignedUrlRequest();

            request.WithBucketName(BUCKET_NAME);
            request.WithKey(sObjectKey);
            request.WithProtocol(Protocol.HTTP);
            request.WithExpires(DateTime.Now.AddMinutes(3));
            return(new Uri(client.GetPreSignedURL(request), UriKind.Absolute));
        }
コード例 #8
0
        public static String MakeUrl(AmazonS3 s3Client)
        {
            string preSignedURL = s3Client.GetPreSignedURL(new GetPreSignedUrlRequest()
            {
                BucketName = BUCKET_NAME,
                Key        = S3_KEY,
                Expires    = System.DateTime.Now.AddMinutes(30),
                Protocol   = Protocol.HTTP
            });

            //Console.WriteLine(preSignedURL);

            return(preSignedURL);
        }
コード例 #9
0
        public override string SavePrivate(string domain, string path, Stream stream, DateTime expires)
        {
            using (AmazonS3 client = GetClient())
            {
                var objectKey = MakePath(domain, path);

                var request = new Amazon.S3.Transfer.TransferUtilityUploadRequest
                {
                    BucketName  = _bucket,
                    Key         = objectKey,
                    CannedACL   = S3CannedACL.BucketOwnerFullControl,
                    ContentType = "application/octet-stream",
                };

                request.WithMetadata("private-expire", expires.ToFileTimeUtc().ToString(CultureInfo.InvariantCulture));

                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(CultureInfo.InvariantCulture));
                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.InputStream = stream;
                new Amazon.S3.Transfer.TransferUtility(client).Upload(request);

                //Get presigned url
                var pUrlRequest = new GetPreSignedUrlRequest
                {
                    BucketName = _bucket,
                    Expires    = expires,
                    Key        = objectKey,
                    Protocol   = Protocol.HTTP,
                    Verb       = HttpVerb.GET
                };

                string url = client.GetPreSignedURL(pUrlRequest);
                //TODO: CNAME!
                return(url);
            }
        }
コード例 #10
0
        public static bool DoesS3BucketExist(string bucketName, AmazonS3 s3Client)
        {
            bool flag;

            if (s3Client == null)
            {
                throw new ArgumentNullException("s3Client", "The s3Client cannot be null!");
            }
            if (string.IsNullOrEmpty(bucketName))
            {
                throw new ArgumentNullException("bucketName", "The bucketName cannot be null or the empty string!");
            }
            GetPreSignedUrlRequest request = new GetPreSignedUrlRequest();

            request.BucketName = bucketName;
            request.Expires    = new DateTime(0x7e3, 12, 0x1f);
            request.Verb       = HttpVerb.HEAD;
            HttpWebRequest request2 = WebRequest.Create(s3Client.GetPreSignedURL(request)) as HttpWebRequest;

            request2.Method = "HEAD";
            try
            {
                request2.GetResponse();
                flag = true;
            }
            catch (WebException exception)
            {
                using (HttpWebResponse response = exception.Response as HttpWebResponse)
                {
                    if (response != null)
                    {
                        HttpStatusCode statusCode = response.StatusCode;
                        return((statusCode != HttpStatusCode.NotFound) && (statusCode != HttpStatusCode.BadRequest));
                    }
                    flag = false;
                }
            }
            return(flag);
        }
コード例 #11
0
        /// <summary>
        /// Determines whether an S3 bucket exists or not.
        /// This is done by:
        /// 1. Creating a PreSigned Url for the bucket (with an expiry date at the end of this decade)
        /// 2. Making a HEAD request to the Url
        /// </summary>
        /// <param name="bucketName">The name of the bucket to check.</param>
        /// <param name="s3Client">The Amazon S3 Client to use for S3 specific operations.</param>
        /// <returns></returns>
        public static bool DoesS3BucketExist(string bucketName, AmazonS3 s3Client)
        {
            if (s3Client == null)
            {
                throw new ArgumentNullException("s3Client", "The s3Client cannot be null!");
            }

            if (String.IsNullOrEmpty(bucketName))
            {
                throw new ArgumentNullException("bucketName", "The bucketName cannot be null or the empty string!");
            }

            GetPreSignedUrlRequest request = new GetPreSignedUrlRequest();
            request.BucketName = bucketName;
            request.Expires = new DateTime(2019, 12, 31);
            request.Verb = HttpVerb.HEAD;
            request.Protocol = Protocol.HTTP;
            string url = s3Client.GetPreSignedURL(request);

            HttpWebRequest httpRequest = WebRequest.Create(url) as HttpWebRequest;
            httpRequest.Method = "HEAD";
            try
            {
                HttpWebResponse httpResponse = httpRequest.GetResponse() as HttpWebResponse;
                // If all went well, the bucket was found!
                return true;
            }
            catch (WebException we)
            {
                using (HttpWebResponse errorResponse = we.Response as HttpWebResponse)
                {
                    if (errorResponse != null)
                    {
                        HttpStatusCode code = errorResponse.StatusCode;
                        return code != HttpStatusCode.NotFound &&
                            code != HttpStatusCode.BadRequest;
                    }

                    // The Error Response is null which is indicative of either
                    // a bad request or some other problem
                    return false;
                }
            }
        }
コード例 #12
0
ファイル: AmazonS3Util.cs プロジェクト: pusp/o2platform
 public static bool DoesS3BucketExist(string bucketName, AmazonS3 s3Client)
 {
     bool flag;
     if (s3Client == null)
     {
         throw new ArgumentNullException("s3Client", "The s3Client cannot be null!");
     }
     if (string.IsNullOrEmpty(bucketName))
     {
         throw new ArgumentNullException("bucketName", "The bucketName cannot be null or the empty string!");
     }
     GetPreSignedUrlRequest request = new GetPreSignedUrlRequest();
     request.BucketName = bucketName;
     request.Expires = new DateTime(0x7e3, 12, 0x1f);
     request.Verb = HttpVerb.HEAD;
     HttpWebRequest request2 = WebRequest.Create(s3Client.GetPreSignedURL(request)) as HttpWebRequest;
     request2.Method = "HEAD";
     try
     {
         request2.GetResponse();
         flag = true;
     }
     catch (WebException exception)
     {
         using (HttpWebResponse response = exception.Response as HttpWebResponse)
         {
             if (response != null)
             {
                 HttpStatusCode statusCode = response.StatusCode;
                 return ((statusCode != HttpStatusCode.NotFound) && (statusCode != HttpStatusCode.BadRequest));
             }
             flag = false;
         }
     }
     return flag;
 }
コード例 #13
0
ファイル: S3Engine.cs プロジェクト: xescrp/breinstormin
        public static String MakeUrl(AmazonS3 s3Client, string filekey)
        {
            string preSignedURL = s3Client.GetPreSignedURL(new GetPreSignedUrlRequest()
            {
                BucketName = BUCKET_NAME,
                Key = filekey,
                Expires = System.DateTime.Now.AddYears(10)

            });

            return preSignedURL;
        }
コード例 #14
0
        public string GenerateURL(string objectName)
        {
            AmazonS3 s3Client = Amazon.AWSClientFactory.CreateAmazonS3Client(AWSKey, AWSSecretKey);


            string url = "";

            try
            {
                using (s3Client)
                {
                    GetPreSignedUrlRequest request = new GetPreSignedUrlRequest();
                    request.WithBucketName(bucketName);
                    request.WithKey(prefix + objectName);
                    if (expires == 0)
                    {
                        request.WithExpires(DateTime.Now.AddYears(20));
                    }
                    else
                    {
                        request.WithExpires(DateTime.Now.AddDays(expires));
                    }


                    url = s3Client.GetPreSignedURL(request);
                }
            }
            catch (AmazonS3Exception)
            {
            }

            if (!isPrivate)
            {
                url = url.Substring(0, url.IndexOf("?")); //remove QS
            }

            if (!https)
            {
                url = url.Replace(@"https://", @"http://");
            }

            if (shorten)
            {
                //create is.gd url
                string resp = "";
                try
                {
                    string isgd = @"http://is.gd/create.php?format=simple&url=" + System.Uri.EscapeDataString(url);
                    resp = new System.Net.WebClient().DownloadString(isgd);
                }
                catch (Exception) { }
                if (resp != "")
                {
                    url = resp;
                    if (appendExt)
                    {
                        if (System.IO.Path.GetExtension(objectName).ToLower() == "png")
                        {
                            url += "?" + System.IO.Path.GetExtension(objectName).ToLower();
                        }
                        else
                        {
                            url += "?" + System.IO.Path.GetFileName(objectName).ToLower();
                        }
                    }
                }
            }


            return(url);
        }