/*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 #2
0
        public override void Execute()
        {
            int timeout = this._config.DefaultTimeout;

            if (this._fileTransporterRequest.Timeout != 0)
            {
                timeout = this._fileTransporterRequest.Timeout;
            }

            PutObjectRequest putRequest = new PutObjectRequest()
                                          .WithBucketName(this._fileTransporterRequest.BucketName)
                                          .WithKey(this._fileTransporterRequest.Key)
                                          .WithCannedACL(this._fileTransporterRequest.CannedACL)
                                          .WithContentType(this._fileTransporterRequest.ContentType)
                                          .WithFilePath(this._fileTransporterRequest.FilePath)
                                          .WithTimeout(timeout)
                                          .WithStorageClass(this._fileTransporterRequest.StorageClass)
                                          .WithAutoCloseStream(this._fileTransporterRequest.AutoCloseStream)
                                          .WithServerSideEncryptionMethod(this._fileTransporterRequest.ServerSideEncryptionMethod)
                                          .WithSubscriber(new EventHandler <PutObjectProgressArgs>(this.putObjectProgressEventCallback));

            putRequest.InputStream = this._fileTransporterRequest.InputStream;

            if (this._fileTransporterRequest.metadata != null && this._fileTransporterRequest.metadata.Count > 0)
            {
                putRequest.WithMetaData(this._fileTransporterRequest.metadata);
            }
            if (this._fileTransporterRequest.Headers != null && this._fileTransporterRequest.Headers.Count > 0)
            {
                putRequest.AddHeaders(this._fileTransporterRequest.Headers);
            }

            this._s3Client.PutObject(putRequest);
        }
Exemple #3
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 UploadObject(UploadRequest request)
        {
            CheckUri(request.Uri);

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

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

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

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

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

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

                    using (client.PutObject(putRequest))
                    {
                    }
                }
            }
            catch (Exception e)
            {
                throw new StorageException(string.Format("Failed to upload object with request {0}.", request), e);
            }
        }
        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);
            }
        }
        public override void Execute()
        {
            int timeout = this._config.DefaultTimeout;

            if (this._fileTransporterRequest.Timeout != 0)
            {
                timeout = this._fileTransporterRequest.Timeout;
            }

            PutObjectRequest putRequest = new PutObjectRequest
            {
                BucketName                 = this._fileTransporterRequest.BucketName,
                Key                        = this._fileTransporterRequest.Key,
                CannedACL                  = this._fileTransporterRequest.CannedACL,
                ContentType                = this._fileTransporterRequest.ContentType,
                FilePath                   = this._fileTransporterRequest.FilePath,
                Timeout                    = timeout,
                StorageClass               = this._fileTransporterRequest.StorageClass,
                AutoCloseStream            = this._fileTransporterRequest.AutoCloseStream,
                ServerSideEncryptionMethod = this._fileTransporterRequest.ServerSideEncryptionMethod,
            };

            putRequest.PutObjectProgressEvent += new EventHandler <PutObjectProgressArgs>(this.putObjectProgressEventCallback);

            putRequest.InputStream = this._fileTransporterRequest.InputStream;

            if (this._fileTransporterRequest.metadata != null && this._fileTransporterRequest.metadata.Count > 0)
            {
                putRequest.WithMetaData(this._fileTransporterRequest.metadata);
            }
            if (this._fileTransporterRequest.Headers != null && this._fileTransporterRequest.Headers.Count > 0)
            {
                putRequest.AddHeaders(this._fileTransporterRequest.Headers);
            }

            this._s3Client.PutObject(putRequest);
        }
        public void UploadObject(UploadRequest request)
        {
            CheckUri(request.Uri);

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

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

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

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

                    using (client.PutObject(putRequest))
                    {
                    }
                }
            }
            catch (Exception e)
            {
                throw new StorageException(string.Format("Failed to upload object with request {0}.", request), e);
            }
        }
    public static void AmazonUpload(string virtuelpath)
    {
        if (context.Cache[virtuelpath + _bucketServerName + "-file"] == null)
        {
            string filePath    = context.Request.MapPath(virtuelpath);
            string contentType = "image/" + Path.GetExtension(filePath).Replace(".", null);
            // Create a signature for this operation
            PutObjectRequest putObjReq = new PutObjectRequest();
            putObjReq.WithBucketName(_bucketServerName);
            putObjReq.WithContentType(contentType);
            putObjReq.WithFilePath(filePath);
            putObjReq.WithKey(Path.GetFileName(filePath));
            putObjReq.WithCannedACL(S3CannedACL.PublicRead);
            var headers = new System.Collections.Specialized.NameValueCollection();
            headers.Add("Expires", TimeZoneManager.DateTimeNow.AddMonths(6).ToString("ddd, dd MMM yyyy HH:mm:ss K"));


            putObjReq.AddHeaders(headers);


            //// COMPRESS file
            //MemoryStream ms = new MemoryStream();

            //using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
            //{
            //    byte[] buffer = File.ReadAllBytes(filePath);
            //    zip.Write(buffer, 0, buffer.Length);
            //    zip.Flush();
            //}

            //ms.Position = 0;
            //// Create a signature for this operation
            //PutObjectRequest putObjReqGZ = new PutObjectRequest();
            //putObjReqGZ.WithBucketName(_bucketServerName);
            //putObjReqGZ.WithContentType(contentType);
            //putObjReqGZ.WithInputStream(ms);
            //putObjReqGZ.WithKey(Path.GetFileName(filePath) + ".gz");
            //putObjReqGZ.WithCannedACL(S3CannedACL.PublicRead);
            //var headersGZ = new System.Collections.Specialized.NameValueCollection();
            //headersGZ.Add("Content-Encoding", "gzip");
            //headersGZ.Add("Expires", TimeZoneManager.DateTimeNow.AddMonths(6).ToString("ddd, dd MMM yyyy HH:mm:ss K"));


            //putObjReqGZ.AddHeaders(headersGZ);

            // connect client
            AmazonS3 s3Client = AWSClientFactory.CreateAmazonS3Client(_amazonID, _amazonSecretKey);
            s3Client.PutObject(putObjReq);     // upload file
            //s3Client.PutObject(putObjReqGZ); // upload file

            context.Cache.Add(virtuelpath.GetHashCode() + _bucketServerName + "-file", "isUploaded",
                              null,
                              TimeZoneManager.DateTimeNow.AddDays(30),
                              System.Web.Caching.Cache.NoSlidingExpiration,
                              System.Web.Caching.CacheItemPriority.Normal,
                              null);


            // clean amazon
            s3Client.Dispose();
            //ms.Close();
            //ms.Flush();
            //ms.Dispose();
        }
    }
    public static void AmazonUploadContent(string virtuelpath)
    {
        if (context.Cache[virtuelpath + _bucketServerName + "-content"] == null)
        {
            Uri    path    = new Uri(GetSiteRoot() + "/" + virtuelpath);
            string q       = path.Query;
            string qp      = HttpUtility.ParseQueryString(q).Get("p");
            string qpageId = "-" + qp;

            string source = null;
            // Create a request using a URL
            WebClient wrGETURL = new System.Net.WebClient();
            wrGETURL.CachePolicy           = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
            wrGETURL.UseDefaultCredentials = false;
            wrGETURL.Encoding = Encoding.UTF8;

            source = wrGETURL.DownloadString(path);


            wrGETURL.Dispose();
            wrGETURL.CancelAsync();

            string contentType = "text/javascript";
            // Create a signature for this operation
            PutObjectRequest putObjReq = new PutObjectRequest();
            putObjReq.WithBucketName(_bucketServerName);
            putObjReq.WithContentType(contentType);
            putObjReq.WithContentBody(source);
            putObjReq.WithKey(virtuelpath.Remove(0).GetHashCode() + "-" + qp + ".js");
            putObjReq.WithCannedACL(S3CannedACL.PublicRead);
            var headers = new System.Collections.Specialized.NameValueCollection();
            headers.Add("Expires", TimeZoneManager.DateTimeNow.AddMonths(6).ToString("ddd, dd MMM yyyy HH:mm:ss K"));

            putObjReq.AddHeaders(headers);


            // COMPRESS file
            MemoryStream ms = new MemoryStream();

            using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
            {
                byte[] buffer = Encoding.UTF8.GetBytes(source);
                zip.Write(buffer, 0, buffer.Length);
                zip.Flush();
            }

            ms.Position = 0;
            // Create a signature for this operation
            PutObjectRequest putObjReqGZ = new PutObjectRequest();
            putObjReqGZ.WithBucketName(_bucketServerName);
            putObjReqGZ.WithContentType(contentType);
            putObjReqGZ.WithInputStream(ms);
            putObjReqGZ.WithKey(virtuelpath.Remove(0).GetHashCode() + "-" + qp + ".js.gz");
            putObjReqGZ.WithCannedACL(S3CannedACL.PublicRead);

            var headersGZ = new System.Collections.Specialized.NameValueCollection();
            headersGZ.Add("Content-Encoding", "gzip");
            headersGZ.Add("Expires", TimeZoneManager.DateTimeNow.AddMonths(6).ToString("ddd, dd MMM yyyy HH:mm:ss K"));

            putObjReqGZ.AddHeaders(headersGZ);

            // connect client
            AmazonS3 s3Client = AWSClientFactory.CreateAmazonS3Client(_amazonID, _amazonSecretKey);
            s3Client.PutObject(putObjReq);     // upload file
            s3Client.PutObject(putObjReqGZ);   // upload file

            context.Cache.Add(virtuelpath + _bucketServerName + "-content", "isUploaded",
                              null,
                              TimeZoneManager.DateTimeNow.AddDays(30),
                              System.Web.Caching.Cache.NoSlidingExpiration,
                              System.Web.Caching.CacheItemPriority.Normal,
                              null);


            // clean amazon
            s3Client.Dispose();
            ms.Close();
            ms.Flush();
            ms.Dispose();
        }
    }
Exemple #10
0
        public Uri Save(string domain, string path, Stream stream, string contentType,
                        string contentDisposition, ACL acl, string contentEncoding = null, int cacheDays = 5)
        {
            bool postWriteCheck = false;

            if (QuotaController != null)
            {
                try
                {
                    QuotaController.QuotaUsedAdd(_modulename, domain, _dataList.GetData(domain), stream.Length);
                }
                catch (TenantQuotaException)
                {
                    //this exception occurs only if tenant has no free space
                    //or if file size larger than allowed by quota
                    //so we can exit this function without stream buffering etc
                    throw;
                }
                catch (Exception)
                {
                    postWriteCheck = true;
                }
            }


            using (AmazonS3 client = GetClient())
            {
                var    request = new PutObjectRequest();
                string mime    = string.IsNullOrEmpty(contentType)
                                  ? MimeMapping.GetMimeMapping(Path.GetFileName(path))
                                  : contentType;

                request.BucketName  = _bucket;
                request.Key         = MakePath(domain, path);
                request.CannedACL   = acl == ACL.Auto ? GetDomainACL(domain) : GetS3Acl(acl);
                request.ContentType = mime;

                request.ServerSideEncryptionMethod = ServerSideEncryptionMethod.AES256;

                var requestHeaders = new NameValueCollection();
                requestHeaders.Add("Cache-Control", string.Format("public, maxage={0}", (int)TimeSpan.FromDays(cacheDays).TotalSeconds));
                requestHeaders.Add("Etag", (DateTime.UtcNow.Ticks).ToString(CultureInfo.InvariantCulture));
                requestHeaders.Add("Last-Modified", DateTime.UtcNow.ToString("R"));
                requestHeaders.Add("Expires", DateTime.UtcNow.Add(TimeSpan.FromDays(cacheDays)).ToString("R"));

                if (!string.IsNullOrEmpty(contentDisposition))
                {
                    requestHeaders.Add("Content-Disposition", contentDisposition);
                }
                else if (mime == "application/octet-stream")
                {
                    requestHeaders.Add("Content-Disposition", "attachment");
                }

                if (!string.IsNullOrEmpty(contentEncoding))
                {
                    requestHeaders.Add("Content-Encoding", contentEncoding);
                }

                request.AddHeaders(requestHeaders);

                //Send body
                var buffered = stream.GetBuffered();
                if (postWriteCheck)
                {
                    QuotaController.QuotaUsedAdd(_modulename, domain, _dataList.GetData(domain), buffered.Length);
                }
                request.AutoCloseStream = false;

                request.InputStream = buffered;

                PutObjectResponse response            = client.PutObject(request);
                var destinationObjectEncryptionStatus = response.ServerSideEncryptionMethod;

                //..ServerSideEncryptionMethod;

                InvalidateCloudFront(MakePath(domain, path));

                return(GetUri(domain, path));
            }
        }
Exemple #11
0
        public Uri Save(string domain, string path, Stream stream, string contentType,
                        string contentDisposition, ACL acl)
        {
            bool postWriteCheck = false;

            if (QuotaController != null)
            {
                try
                {
                    QuotaController.QuotaUsedAdd(_modulename, domain, _dataList.GetData(domain), stream.Length);
                }
                catch (Exception)
                {
                    postWriteCheck = true;
                }
            }


            using (AmazonS3 client = GetClient())
            {
                var    request = new PutObjectRequest();
                string mime    = string.IsNullOrEmpty(contentType)
                                  ? MimeMapping.GetMimeMapping(Path.GetFileName(path))
                                  : contentType;

                request.WithBucketName(_bucket)
                .WithKey(MakePath(domain, path))
                .WithCannedACL(acl == ACL.Auto ? GetDomainACL(domain) : GetS3Acl(acl))
                .WithContentType(mime);

                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"));
                if (!string.IsNullOrEmpty(contentDisposition))
                {
                    headers.Add("Content-Disposition", contentDisposition);
                }
                else if (mime == "application/octet-stream")
                {
                    headers.Add("Content-Disposition", "attachment");
                }

                request.AddHeaders(headers);

                //Send body
                var buffered = stream.GetBuffered();
                if (postWriteCheck)
                {
                    QuotaController.QuotaUsedAdd(_modulename, domain, _dataList.GetData(domain), buffered.Length);
                }
                request.AutoCloseStream = false;

                request.WithInputStream(buffered);
                client.PutObject(request);
                InvalidateCloudFront(MakePath(domain, path));

                return(GetUri(domain, path));
            }
        }